babylon.max.js 4.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261
  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. /**
  20. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  21. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  22. */
  23. var EffectFallbacks = /** @class */ (function () {
  24. function EffectFallbacks() {
  25. this._defines = {};
  26. this._currentRank = 32;
  27. this._maxRank = -1;
  28. }
  29. /**
  30. * Removes the fallback from the bound mesh.
  31. */
  32. EffectFallbacks.prototype.unBindMesh = function () {
  33. this._mesh = null;
  34. };
  35. /**
  36. * Adds a fallback on the specified property.
  37. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  38. * @param define The name of the define in the shader
  39. */
  40. EffectFallbacks.prototype.addFallback = function (rank, define) {
  41. if (!this._defines[rank]) {
  42. if (rank < this._currentRank) {
  43. this._currentRank = rank;
  44. }
  45. if (rank > this._maxRank) {
  46. this._maxRank = rank;
  47. }
  48. this._defines[rank] = new Array();
  49. }
  50. this._defines[rank].push(define);
  51. };
  52. /**
  53. * Sets the mesh to use CPU skinning when needing to fallback.
  54. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  55. * @param mesh The mesh to use the fallbacks.
  56. */
  57. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  58. this._mesh = mesh;
  59. if (rank < this._currentRank) {
  60. this._currentRank = rank;
  61. }
  62. if (rank > this._maxRank) {
  63. this._maxRank = rank;
  64. }
  65. };
  66. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  67. /**
  68. * Checks to see if more fallbacks are still availible.
  69. */
  70. get: function () {
  71. return this._currentRank <= this._maxRank;
  72. },
  73. enumerable: true,
  74. configurable: true
  75. });
  76. /**
  77. * Removes the defines that shoould be removed when falling back.
  78. * @param currentDefines defines the current define statements for the shader.
  79. * @param effect defines the current effect we try to compile
  80. * @returns The resulting defines with defines of the current rank removed.
  81. */
  82. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  83. // First we try to switch to CPU skinning
  84. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  85. this._mesh.computeBonesUsingShaders = false;
  86. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  87. var scene = this._mesh.getScene();
  88. for (var index = 0; index < scene.meshes.length; index++) {
  89. var otherMesh = scene.meshes[index];
  90. if (!otherMesh.material) {
  91. continue;
  92. }
  93. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  94. continue;
  95. }
  96. if (otherMesh.material.getEffect() === effect) {
  97. otherMesh.computeBonesUsingShaders = false;
  98. }
  99. else {
  100. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  101. var subMesh = _a[_i];
  102. var subMeshEffect = subMesh.effect;
  103. if (subMeshEffect === effect) {
  104. otherMesh.computeBonesUsingShaders = false;
  105. break;
  106. }
  107. }
  108. }
  109. }
  110. }
  111. else {
  112. var currentFallbacks = this._defines[this._currentRank];
  113. if (currentFallbacks) {
  114. for (var index = 0; index < currentFallbacks.length; index++) {
  115. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  116. }
  117. }
  118. this._currentRank++;
  119. }
  120. return currentDefines;
  121. };
  122. return EffectFallbacks;
  123. }());
  124. BABYLON.EffectFallbacks = EffectFallbacks;
  125. /**
  126. * Options to be used when creating an effect.
  127. */
  128. var EffectCreationOptions = /** @class */ (function () {
  129. function EffectCreationOptions() {
  130. }
  131. return EffectCreationOptions;
  132. }());
  133. BABYLON.EffectCreationOptions = EffectCreationOptions;
  134. /**
  135. * Effect containing vertex and fragment shader that can be executed on an object.
  136. */
  137. var Effect = /** @class */ (function () {
  138. /**
  139. * Instantiates an effect.
  140. * An effect can be used to create/manage/execute vertex and fragment shaders.
  141. * @param baseName Name of the effect.
  142. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  143. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  144. * @param samplers List of sampler variables that will be passed to the shader.
  145. * @param engine Engine to be used to render the effect
  146. * @param defines Define statements to be added to the shader.
  147. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  148. * @param onCompiled Callback that will be called when the shader is compiled.
  149. * @param onError Callback that will be called if an error occurs during shader compilation.
  150. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  151. */
  152. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  153. if (samplers === void 0) { samplers = null; }
  154. if (defines === void 0) { defines = null; }
  155. if (fallbacks === void 0) { fallbacks = null; }
  156. if (onCompiled === void 0) { onCompiled = null; }
  157. if (onError === void 0) { onError = null; }
  158. var _this = this;
  159. /**
  160. * Unique ID of the effect.
  161. */
  162. this.uniqueId = 0;
  163. /**
  164. * Observable that will be called when the shader is compiled.
  165. */
  166. this.onCompileObservable = new BABYLON.Observable();
  167. /**
  168. * Observable that will be called if an error occurs during shader compilation.
  169. */
  170. this.onErrorObservable = new BABYLON.Observable();
  171. /**
  172. * Observable that will be called when effect is bound.
  173. */
  174. this.onBindObservable = new BABYLON.Observable();
  175. this._uniformBuffersNames = {};
  176. this._isReady = false;
  177. this._compilationError = "";
  178. this.name = baseName;
  179. if (attributesNamesOrOptions.attributes) {
  180. var options = attributesNamesOrOptions;
  181. this._engine = uniformsNamesOrEngine;
  182. this._attributesNames = options.attributes;
  183. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  184. this._samplers = options.samplers;
  185. this.defines = options.defines;
  186. this.onError = options.onError;
  187. this.onCompiled = options.onCompiled;
  188. this._fallbacks = options.fallbacks;
  189. this._indexParameters = options.indexParameters;
  190. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  191. if (options.uniformBuffersNames) {
  192. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  193. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  194. }
  195. }
  196. }
  197. else {
  198. this._engine = engine;
  199. this.defines = defines;
  200. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  201. this._samplers = samplers;
  202. this._attributesNames = attributesNamesOrOptions;
  203. this.onError = onError;
  204. this.onCompiled = onCompiled;
  205. this._indexParameters = indexParameters;
  206. this._fallbacks = fallbacks;
  207. }
  208. this.uniqueId = Effect._uniqueIdSeed++;
  209. var vertexSource;
  210. var fragmentSource;
  211. if (baseName.vertexElement) {
  212. vertexSource = document.getElementById(baseName.vertexElement);
  213. if (!vertexSource) {
  214. vertexSource = baseName.vertexElement;
  215. }
  216. }
  217. else {
  218. vertexSource = baseName.vertex || baseName;
  219. }
  220. if (baseName.fragmentElement) {
  221. fragmentSource = document.getElementById(baseName.fragmentElement);
  222. if (!fragmentSource) {
  223. fragmentSource = baseName.fragmentElement;
  224. }
  225. }
  226. else {
  227. fragmentSource = baseName.fragment || baseName;
  228. }
  229. var finalVertexCode;
  230. this._loadVertexShaderAsync(vertexSource)
  231. .then(function (vertexCode) {
  232. return _this._processIncludesAsync(vertexCode);
  233. })
  234. .then(function (vertexCodeWithIncludes) {
  235. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  236. return _this._loadFragmentShaderAsync(fragmentSource);
  237. })
  238. .then(function (fragmentCode) {
  239. return _this._processIncludesAsync(fragmentCode);
  240. })
  241. .then(function (fragmentCodeWithIncludes) {
  242. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  243. if (baseName) {
  244. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  245. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  246. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  247. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  248. }
  249. else {
  250. _this._vertexSourceCode = finalVertexCode;
  251. _this._fragmentSourceCode = migratedFragmentCode;
  252. }
  253. _this._prepareEffect();
  254. });
  255. }
  256. Object.defineProperty(Effect.prototype, "key", {
  257. /**
  258. * Unique key for this effect
  259. */
  260. get: function () {
  261. return this._key;
  262. },
  263. enumerable: true,
  264. configurable: true
  265. });
  266. /**
  267. * If the effect has been compiled and prepared.
  268. * @returns if the effect is compiled and prepared.
  269. */
  270. Effect.prototype.isReady = function () {
  271. return this._isReady;
  272. };
  273. /**
  274. * The engine the effect was initialized with.
  275. * @returns the engine.
  276. */
  277. Effect.prototype.getEngine = function () {
  278. return this._engine;
  279. };
  280. /**
  281. * The compiled webGL program for the effect
  282. * @returns the webGL program.
  283. */
  284. Effect.prototype.getProgram = function () {
  285. return this._program;
  286. };
  287. /**
  288. * The set of names of attribute variables for the shader.
  289. * @returns An array of attribute names.
  290. */
  291. Effect.prototype.getAttributesNames = function () {
  292. return this._attributesNames;
  293. };
  294. /**
  295. * Returns the attribute at the given index.
  296. * @param index The index of the attribute.
  297. * @returns The location of the attribute.
  298. */
  299. Effect.prototype.getAttributeLocation = function (index) {
  300. return this._attributes[index];
  301. };
  302. /**
  303. * Returns the attribute based on the name of the variable.
  304. * @param name of the attribute to look up.
  305. * @returns the attribute location.
  306. */
  307. Effect.prototype.getAttributeLocationByName = function (name) {
  308. var index = this._attributesNames.indexOf(name);
  309. return this._attributes[index];
  310. };
  311. /**
  312. * The number of attributes.
  313. * @returns the numnber of attributes.
  314. */
  315. Effect.prototype.getAttributesCount = function () {
  316. return this._attributes.length;
  317. };
  318. /**
  319. * Gets the index of a uniform variable.
  320. * @param uniformName of the uniform to look up.
  321. * @returns the index.
  322. */
  323. Effect.prototype.getUniformIndex = function (uniformName) {
  324. return this._uniformsNames.indexOf(uniformName);
  325. };
  326. /**
  327. * Returns the attribute based on the name of the variable.
  328. * @param uniformName of the uniform to look up.
  329. * @returns the location of the uniform.
  330. */
  331. Effect.prototype.getUniform = function (uniformName) {
  332. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  333. };
  334. /**
  335. * Returns an array of sampler variable names
  336. * @returns The array of sampler variable neames.
  337. */
  338. Effect.prototype.getSamplers = function () {
  339. return this._samplers;
  340. };
  341. /**
  342. * The error from the last compilation.
  343. * @returns the error string.
  344. */
  345. Effect.prototype.getCompilationError = function () {
  346. return this._compilationError;
  347. };
  348. /**
  349. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  350. * @param func The callback to be used.
  351. */
  352. Effect.prototype.executeWhenCompiled = function (func) {
  353. if (this.isReady()) {
  354. func(this);
  355. return;
  356. }
  357. this.onCompileObservable.add(function (effect) {
  358. func(effect);
  359. });
  360. };
  361. /** @ignore */
  362. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  363. if (BABYLON.Tools.IsWindowObjectExist()) {
  364. // DOM element ?
  365. if (vertex instanceof HTMLElement) {
  366. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  367. return Promise.resolve(vertexCode);
  368. }
  369. }
  370. // Base64 encoded ?
  371. if (vertex.substr(0, 7) === "base64:") {
  372. var vertexBinary = window.atob(vertex.substr(7));
  373. return Promise.resolve(vertexBinary);
  374. }
  375. // Is in local store ?
  376. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  377. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  378. }
  379. var vertexShaderUrl;
  380. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  381. vertexShaderUrl = vertex;
  382. }
  383. else {
  384. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  385. }
  386. // Vertex shader
  387. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  388. };
  389. /** @ignore */
  390. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  391. if (BABYLON.Tools.IsWindowObjectExist()) {
  392. // DOM element ?
  393. if (fragment instanceof HTMLElement) {
  394. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  395. return Promise.resolve(fragmentCode);
  396. }
  397. }
  398. // Base64 encoded ?
  399. if (fragment.substr(0, 7) === "base64:") {
  400. var fragmentBinary = window.atob(fragment.substr(7));
  401. return Promise.resolve(fragmentBinary);
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  406. }
  407. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  408. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  409. }
  410. var fragmentShaderUrl;
  411. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  412. fragmentShaderUrl = fragment;
  413. }
  414. else {
  415. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  416. }
  417. // Fragment shader
  418. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  419. };
  420. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  421. // Rebuild shaders source code
  422. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  423. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  424. vertexCode = prefix + vertexCode;
  425. fragmentCode = prefix + fragmentCode;
  426. // Number lines of shaders source code
  427. var i = 2;
  428. var regex = /\n/gm;
  429. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  430. i = 2;
  431. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  432. // Dump shaders name and formatted source code
  433. if (this.name.vertexElement) {
  434. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  435. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  436. }
  437. else if (this.name.vertex) {
  438. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  439. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  440. }
  441. else {
  442. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  443. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  444. }
  445. };
  446. ;
  447. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  448. var preparedSourceCode = this._processPrecision(sourceCode);
  449. if (this._engine.webGLVersion == 1) {
  450. return preparedSourceCode;
  451. }
  452. // Already converted
  453. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  454. return preparedSourceCode.replace("#version 300 es", "");
  455. }
  456. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  457. // Remove extensions
  458. // #extension GL_OES_standard_derivatives : enable
  459. // #extension GL_EXT_shader_texture_lod : enable
  460. // #extension GL_EXT_frag_depth : enable
  461. // #extension GL_EXT_draw_buffers : require
  462. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  463. var result = preparedSourceCode.replace(regex, "");
  464. // Migrate to GLSL v300
  465. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  466. result = result.replace(/attribute[ \t]/g, "in ");
  467. result = result.replace(/[ \t]attribute/g, " in");
  468. if (isFragment) {
  469. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  470. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  471. result = result.replace(/texture2D\s*\(/g, "texture(");
  472. result = result.replace(/textureCube\s*\(/g, "texture(");
  473. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  474. result = result.replace(/gl_FragColor/g, "glFragColor");
  475. result = result.replace(/gl_FragData/g, "glFragData");
  476. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  477. }
  478. return result;
  479. };
  480. Effect.prototype._processIncludesAsync = function (sourceCode) {
  481. var _this = this;
  482. return new Promise(function (resolve, reject) {
  483. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  484. var match = regex.exec(sourceCode);
  485. var returnValue = sourceCode;
  486. while (match != null) {
  487. var includeFile = match[1];
  488. // Uniform declaration
  489. if (includeFile.indexOf("__decl__") !== -1) {
  490. includeFile = includeFile.replace(/__decl__/, "");
  491. if (_this._engine.supportsUniformBuffers) {
  492. includeFile = includeFile.replace(/Vertex/, "Ubo");
  493. includeFile = includeFile.replace(/Fragment/, "Ubo");
  494. }
  495. includeFile = includeFile + "Declaration";
  496. }
  497. if (Effect.IncludesShadersStore[includeFile]) {
  498. // Substitution
  499. var includeContent = Effect.IncludesShadersStore[includeFile];
  500. if (match[2]) {
  501. var splits = match[3].split(",");
  502. for (var index = 0; index < splits.length; index += 2) {
  503. var source = new RegExp(splits[index], "g");
  504. var dest = splits[index + 1];
  505. includeContent = includeContent.replace(source, dest);
  506. }
  507. }
  508. if (match[4]) {
  509. var indexString = match[5];
  510. if (indexString.indexOf("..") !== -1) {
  511. var indexSplits = indexString.split("..");
  512. var minIndex = parseInt(indexSplits[0]);
  513. var maxIndex = parseInt(indexSplits[1]);
  514. var sourceIncludeContent = includeContent.slice(0);
  515. includeContent = "";
  516. if (isNaN(maxIndex)) {
  517. maxIndex = _this._indexParameters[indexSplits[1]];
  518. }
  519. for (var i = minIndex; i < maxIndex; i++) {
  520. if (!_this._engine.supportsUniformBuffers) {
  521. // Ubo replacement
  522. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  523. return p1 + "{X}";
  524. });
  525. }
  526. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  527. }
  528. }
  529. else {
  530. if (!_this._engine.supportsUniformBuffers) {
  531. // Ubo replacement
  532. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  533. return p1 + "{X}";
  534. });
  535. }
  536. includeContent = includeContent.replace(/\{X\}/g, indexString);
  537. }
  538. }
  539. // Replace
  540. returnValue = returnValue.replace(match[0], includeContent);
  541. }
  542. else {
  543. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  544. _this._engine._loadFileAsync(includeShaderUrl)
  545. .then(function (fileContent) {
  546. Effect.IncludesShadersStore[includeFile] = fileContent;
  547. return _this._processIncludesAsync(returnValue);
  548. })
  549. .then(function (returnValue) {
  550. resolve(returnValue);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. resolve(returnValue);
  557. });
  558. };
  559. Effect.prototype._processPrecision = function (source) {
  560. if (source.indexOf("precision highp float") === -1) {
  561. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  562. source = "precision mediump float;\n" + source;
  563. }
  564. else {
  565. source = "precision highp float;\n" + source;
  566. }
  567. }
  568. else {
  569. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  570. source = source.replace("precision highp float", "precision mediump float");
  571. }
  572. }
  573. return source;
  574. };
  575. /**
  576. * Recompiles the webGL program
  577. * @param vertexSourceCode The source code for the vertex shader.
  578. * @param fragmentSourceCode The source code for the fragment shader.
  579. * @param onCompiled Callback called when completed.
  580. * @param onError Callback called on error.
  581. */
  582. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  583. var _this = this;
  584. this._isReady = false;
  585. this._vertexSourceCodeOverride = vertexSourceCode;
  586. this._fragmentSourceCodeOverride = fragmentSourceCode;
  587. this.onError = function (effect, error) {
  588. if (onError) {
  589. onError(error);
  590. }
  591. };
  592. this.onCompiled = function () {
  593. var scenes = _this.getEngine().scenes;
  594. for (var i = 0; i < scenes.length; i++) {
  595. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  596. }
  597. if (onCompiled) {
  598. onCompiled(_this._program);
  599. }
  600. };
  601. this._fallbacks = null;
  602. this._prepareEffect();
  603. };
  604. /**
  605. * Gets the uniform locations of the the specified variable names
  606. * @param names THe names of the variables to lookup.
  607. * @returns Array of locations in the same order as variable names.
  608. */
  609. Effect.prototype.getSpecificUniformLocations = function (names) {
  610. var engine = this._engine;
  611. return engine.getUniforms(this._program, names);
  612. };
  613. /**
  614. * Prepares the effect
  615. */
  616. Effect.prototype._prepareEffect = function () {
  617. var attributesNames = this._attributesNames;
  618. var defines = this.defines;
  619. var fallbacks = this._fallbacks;
  620. this._valueCache = {};
  621. var previousProgram = this._program;
  622. try {
  623. var engine = this._engine;
  624. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  625. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  626. }
  627. else {
  628. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  629. }
  630. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  631. if (engine.supportsUniformBuffers) {
  632. for (var name in this._uniformBuffersNames) {
  633. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  634. }
  635. }
  636. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  637. this._attributes = engine.getAttributes(this._program, attributesNames);
  638. var index;
  639. for (index = 0; index < this._samplers.length; index++) {
  640. var sampler = this.getUniform(this._samplers[index]);
  641. if (sampler == null) {
  642. this._samplers.splice(index, 1);
  643. index--;
  644. }
  645. }
  646. engine.bindSamplers(this);
  647. this._compilationError = "";
  648. this._isReady = true;
  649. if (this.onCompiled) {
  650. this.onCompiled(this);
  651. }
  652. this.onCompileObservable.notifyObservers(this);
  653. this.onCompileObservable.clear();
  654. // Unbind mesh reference in fallbacks
  655. if (this._fallbacks) {
  656. this._fallbacks.unBindMesh();
  657. }
  658. if (previousProgram) {
  659. this.getEngine()._deleteProgram(previousProgram);
  660. }
  661. }
  662. catch (e) {
  663. this._compilationError = e.message;
  664. // Let's go through fallbacks then
  665. BABYLON.Tools.Error("Unable to compile effect:");
  666. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  667. return " " + uniform;
  668. }));
  669. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  670. return " " + attribute;
  671. }));
  672. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  673. BABYLON.Tools.Error("Error: " + this._compilationError);
  674. if (previousProgram) {
  675. this._program = previousProgram;
  676. this._isReady = true;
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. }
  682. if (fallbacks && fallbacks.isMoreFallbacks) {
  683. BABYLON.Tools.Error("Trying next fallback.");
  684. this.defines = fallbacks.reduce(this.defines, this);
  685. this._prepareEffect();
  686. }
  687. else {
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. this.onErrorObservable.clear();
  693. // Unbind mesh reference in fallbacks
  694. if (this._fallbacks) {
  695. this._fallbacks.unBindMesh();
  696. }
  697. }
  698. }
  699. };
  700. Object.defineProperty(Effect.prototype, "isSupported", {
  701. /**
  702. * Checks if the effect is supported. (Must be called after compilation)
  703. */
  704. get: function () {
  705. return this._compilationError === "";
  706. },
  707. enumerable: true,
  708. configurable: true
  709. });
  710. /**
  711. * Binds a texture to the engine to be used as output of the shader.
  712. * @param channel Name of the output variable.
  713. * @param texture Texture to bind.
  714. */
  715. Effect.prototype._bindTexture = function (channel, texture) {
  716. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  717. };
  718. /**
  719. * Sets a texture on the engine to be used in the shader.
  720. * @param channel Name of the sampler variable.
  721. * @param texture Texture to set.
  722. */
  723. Effect.prototype.setTexture = function (channel, texture) {
  724. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  725. };
  726. /**
  727. * Sets an array of textures on the engine to be used in the shader.
  728. * @param channel Name of the variable.
  729. * @param textures Textures to set.
  730. */
  731. Effect.prototype.setTextureArray = function (channel, textures) {
  732. if (this._samplers.indexOf(channel + "Ex") === -1) {
  733. var initialPos = this._samplers.indexOf(channel);
  734. for (var index = 1; index < textures.length; index++) {
  735. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  736. }
  737. }
  738. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  739. };
  740. /**
  741. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  742. * @param channel Name of the sampler variable.
  743. * @param postProcess Post process to get the input texture from.
  744. */
  745. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  746. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  747. };
  748. /** @ignore */
  749. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  750. var cache = this._valueCache[uniformName];
  751. var flag = matrix.updateFlag;
  752. if (cache !== undefined && cache === flag) {
  753. return false;
  754. }
  755. this._valueCache[uniformName] = flag;
  756. return true;
  757. };
  758. /** @ignore */
  759. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  760. var cache = this._valueCache[uniformName];
  761. if (!cache) {
  762. cache = [x, y];
  763. this._valueCache[uniformName] = cache;
  764. return true;
  765. }
  766. var changed = false;
  767. if (cache[0] !== x) {
  768. cache[0] = x;
  769. changed = true;
  770. }
  771. if (cache[1] !== y) {
  772. cache[1] = y;
  773. changed = true;
  774. }
  775. return changed;
  776. };
  777. /** @ignore */
  778. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  779. var cache = this._valueCache[uniformName];
  780. if (!cache) {
  781. cache = [x, y, z];
  782. this._valueCache[uniformName] = cache;
  783. return true;
  784. }
  785. var changed = false;
  786. if (cache[0] !== x) {
  787. cache[0] = x;
  788. changed = true;
  789. }
  790. if (cache[1] !== y) {
  791. cache[1] = y;
  792. changed = true;
  793. }
  794. if (cache[2] !== z) {
  795. cache[2] = z;
  796. changed = true;
  797. }
  798. return changed;
  799. };
  800. /** @ignore */
  801. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  802. var cache = this._valueCache[uniformName];
  803. if (!cache) {
  804. cache = [x, y, z, w];
  805. this._valueCache[uniformName] = cache;
  806. return true;
  807. }
  808. var changed = false;
  809. if (cache[0] !== x) {
  810. cache[0] = x;
  811. changed = true;
  812. }
  813. if (cache[1] !== y) {
  814. cache[1] = y;
  815. changed = true;
  816. }
  817. if (cache[2] !== z) {
  818. cache[2] = z;
  819. changed = true;
  820. }
  821. if (cache[3] !== w) {
  822. cache[3] = w;
  823. changed = true;
  824. }
  825. return changed;
  826. };
  827. /**
  828. * Binds a buffer to a uniform.
  829. * @param buffer Buffer to bind.
  830. * @param name Name of the uniform variable to bind to.
  831. */
  832. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  833. var bufferName = this._uniformBuffersNames[name];
  834. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  835. return;
  836. }
  837. Effect._baseCache[bufferName] = buffer;
  838. this._engine.bindUniformBufferBase(buffer, bufferName);
  839. };
  840. /**
  841. * Binds block to a uniform.
  842. * @param blockName Name of the block to bind.
  843. * @param index Index to bind.
  844. */
  845. Effect.prototype.bindUniformBlock = function (blockName, index) {
  846. this._engine.bindUniformBlock(this._program, blockName, index);
  847. };
  848. /**
  849. * Sets an interger value on a uniform variable.
  850. * @param uniformName Name of the variable.
  851. * @param value Value to be set.
  852. * @returns this effect.
  853. */
  854. Effect.prototype.setInt = function (uniformName, value) {
  855. var cache = this._valueCache[uniformName];
  856. if (cache !== undefined && cache === value)
  857. return this;
  858. this._valueCache[uniformName] = value;
  859. this._engine.setInt(this.getUniform(uniformName), value);
  860. return this;
  861. };
  862. /**
  863. * Sets an int array on a uniform variable.
  864. * @param uniformName Name of the variable.
  865. * @param array array to be set.
  866. * @returns this effect.
  867. */
  868. Effect.prototype.setIntArray = function (uniformName, array) {
  869. this._valueCache[uniformName] = null;
  870. this._engine.setIntArray(this.getUniform(uniformName), array);
  871. return this;
  872. };
  873. /**
  874. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  875. * @param uniformName Name of the variable.
  876. * @param array array to be set.
  877. * @returns this effect.
  878. */
  879. Effect.prototype.setIntArray2 = function (uniformName, array) {
  880. this._valueCache[uniformName] = null;
  881. this._engine.setIntArray2(this.getUniform(uniformName), array);
  882. return this;
  883. };
  884. /**
  885. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  886. * @param uniformName Name of the variable.
  887. * @param array array to be set.
  888. * @returns this effect.
  889. */
  890. Effect.prototype.setIntArray3 = function (uniformName, array) {
  891. this._valueCache[uniformName] = null;
  892. this._engine.setIntArray3(this.getUniform(uniformName), array);
  893. return this;
  894. };
  895. /**
  896. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray4 = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray4(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * Sets an float array on a uniform variable.
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setFloatArray = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setFloatArray(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * Sets an array on a uniform variable.
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setArray = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setArray(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setArray2 = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setArray2(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setArray3 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setArray3(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray4 = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray4(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * Sets matrices on a uniform variable.
  996. * @param uniformName Name of the variable.
  997. * @param matrices matrices to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1001. if (!matrices) {
  1002. return this;
  1003. }
  1004. this._valueCache[uniformName] = null;
  1005. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1006. return this;
  1007. };
  1008. /**
  1009. * Sets matrix on a uniform variable.
  1010. * @param uniformName Name of the variable.
  1011. * @param matrix matrix to be set.
  1012. * @returns this effect.
  1013. */
  1014. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1015. if (this._cacheMatrix(uniformName, matrix)) {
  1016. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1017. }
  1018. return this;
  1019. };
  1020. /**
  1021. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1022. * @param uniformName Name of the variable.
  1023. * @param matrix matrix to be set.
  1024. * @returns this effect.
  1025. */
  1026. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1027. this._valueCache[uniformName] = null;
  1028. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1029. return this;
  1030. };
  1031. /**
  1032. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1033. * @param uniformName Name of the variable.
  1034. * @param matrix matrix to be set.
  1035. * @returns this effect.
  1036. */
  1037. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1038. this._valueCache[uniformName] = null;
  1039. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1040. return this;
  1041. };
  1042. /**
  1043. * Sets a float on a uniform variable.
  1044. * @param uniformName Name of the variable.
  1045. * @param value value to be set.
  1046. * @returns this effect.
  1047. */
  1048. Effect.prototype.setFloat = function (uniformName, value) {
  1049. var cache = this._valueCache[uniformName];
  1050. if (cache !== undefined && cache === value)
  1051. return this;
  1052. this._valueCache[uniformName] = value;
  1053. this._engine.setFloat(this.getUniform(uniformName), value);
  1054. return this;
  1055. };
  1056. /**
  1057. * Sets a boolean on a uniform variable.
  1058. * @param uniformName Name of the variable.
  1059. * @param bool value to be set.
  1060. * @returns this effect.
  1061. */
  1062. Effect.prototype.setBool = function (uniformName, bool) {
  1063. var cache = this._valueCache[uniformName];
  1064. if (cache !== undefined && cache === bool)
  1065. return this;
  1066. this._valueCache[uniformName] = bool;
  1067. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1068. return this;
  1069. };
  1070. /**
  1071. * Sets a Vector2 on a uniform variable.
  1072. * @param uniformName Name of the variable.
  1073. * @param vector2 vector2 to be set.
  1074. * @returns this effect.
  1075. */
  1076. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1077. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1078. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1079. }
  1080. return this;
  1081. };
  1082. /**
  1083. * Sets a float2 on a uniform variable.
  1084. * @param uniformName Name of the variable.
  1085. * @param x First float in float2.
  1086. * @param y Second float in float2.
  1087. * @returns this effect.
  1088. */
  1089. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1090. if (this._cacheFloat2(uniformName, x, y)) {
  1091. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1092. }
  1093. return this;
  1094. };
  1095. /**
  1096. * Sets a Vector3 on a uniform variable.
  1097. * @param uniformName Name of the variable.
  1098. * @param vector3 Value to be set.
  1099. * @returns this effect.
  1100. */
  1101. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1102. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1103. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1104. }
  1105. return this;
  1106. };
  1107. /**
  1108. * Sets a float3 on a uniform variable.
  1109. * @param uniformName Name of the variable.
  1110. * @param x First float in float3.
  1111. * @param y Second float in float3.
  1112. * @param z Third float in float3.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1116. if (this._cacheFloat3(uniformName, x, y, z)) {
  1117. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1118. }
  1119. return this;
  1120. };
  1121. /**
  1122. * Sets a Vector4 on a uniform variable.
  1123. * @param uniformName Name of the variable.
  1124. * @param vector4 Value to be set.
  1125. * @returns this effect.
  1126. */
  1127. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1128. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1129. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1130. }
  1131. return this;
  1132. };
  1133. /**
  1134. * Sets a float4 on a uniform variable.
  1135. * @param uniformName Name of the variable.
  1136. * @param x First float in float4.
  1137. * @param y Second float in float4.
  1138. * @param z Third float in float4.
  1139. * @param w Fourth float in float4.
  1140. * @returns this effect.
  1141. */
  1142. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1143. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1144. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1145. }
  1146. return this;
  1147. };
  1148. /**
  1149. * Sets a Color3 on a uniform variable.
  1150. * @param uniformName Name of the variable.
  1151. * @param color3 Value to be set.
  1152. * @returns this effect.
  1153. */
  1154. Effect.prototype.setColor3 = function (uniformName, color3) {
  1155. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1156. this._engine.setColor3(this.getUniform(uniformName), color3);
  1157. }
  1158. return this;
  1159. };
  1160. /**
  1161. * Sets a Color4 on a uniform variable.
  1162. * @param uniformName Name of the variable.
  1163. * @param color3 Value to be set.
  1164. * @param alpha Alpha value to be set.
  1165. * @returns this effect.
  1166. */
  1167. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1168. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1169. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1170. }
  1171. return this;
  1172. };
  1173. /**
  1174. * Resets the cache of effects.
  1175. */
  1176. Effect.ResetCache = function () {
  1177. Effect._baseCache = {};
  1178. };
  1179. Effect._uniqueIdSeed = 0;
  1180. Effect._baseCache = {};
  1181. // Statics
  1182. /**
  1183. * Store of each shader (The can be looked up using effect.key)
  1184. */
  1185. Effect.ShadersStore = {};
  1186. /**
  1187. * Store of each included file for a shader (The can be looked up using effect.key)
  1188. */
  1189. Effect.IncludesShadersStore = {};
  1190. return Effect;
  1191. }());
  1192. BABYLON.Effect = Effect;
  1193. })(BABYLON || (BABYLON = {}));
  1194. //# sourceMappingURL=babylon.effect.js.map
  1195. //# sourceMappingURL=babylon.types.js.map
  1196. var BABYLON;
  1197. (function (BABYLON) {
  1198. var KeyboardEventTypes = /** @class */ (function () {
  1199. function KeyboardEventTypes() {
  1200. }
  1201. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1202. get: function () {
  1203. return KeyboardEventTypes._KEYDOWN;
  1204. },
  1205. enumerable: true,
  1206. configurable: true
  1207. });
  1208. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1209. get: function () {
  1210. return KeyboardEventTypes._KEYUP;
  1211. },
  1212. enumerable: true,
  1213. configurable: true
  1214. });
  1215. KeyboardEventTypes._KEYDOWN = 0x01;
  1216. KeyboardEventTypes._KEYUP = 0x02;
  1217. return KeyboardEventTypes;
  1218. }());
  1219. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1220. var KeyboardInfo = /** @class */ (function () {
  1221. function KeyboardInfo(type, event) {
  1222. this.type = type;
  1223. this.event = event;
  1224. }
  1225. return KeyboardInfo;
  1226. }());
  1227. BABYLON.KeyboardInfo = KeyboardInfo;
  1228. /**
  1229. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1230. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1231. */
  1232. var KeyboardInfoPre = /** @class */ (function (_super) {
  1233. __extends(KeyboardInfoPre, _super);
  1234. function KeyboardInfoPre(type, event) {
  1235. var _this = _super.call(this, type, event) || this;
  1236. _this.skipOnPointerObservable = false;
  1237. return _this;
  1238. }
  1239. return KeyboardInfoPre;
  1240. }(KeyboardInfo));
  1241. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1242. })(BABYLON || (BABYLON = {}));
  1243. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1244. var BABYLON;
  1245. (function (BABYLON) {
  1246. var PointerEventTypes = /** @class */ (function () {
  1247. function PointerEventTypes() {
  1248. }
  1249. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1250. get: function () {
  1251. return PointerEventTypes._POINTERDOWN;
  1252. },
  1253. enumerable: true,
  1254. configurable: true
  1255. });
  1256. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1257. get: function () {
  1258. return PointerEventTypes._POINTERUP;
  1259. },
  1260. enumerable: true,
  1261. configurable: true
  1262. });
  1263. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1264. get: function () {
  1265. return PointerEventTypes._POINTERMOVE;
  1266. },
  1267. enumerable: true,
  1268. configurable: true
  1269. });
  1270. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1271. get: function () {
  1272. return PointerEventTypes._POINTERWHEEL;
  1273. },
  1274. enumerable: true,
  1275. configurable: true
  1276. });
  1277. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1278. get: function () {
  1279. return PointerEventTypes._POINTERPICK;
  1280. },
  1281. enumerable: true,
  1282. configurable: true
  1283. });
  1284. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1285. get: function () {
  1286. return PointerEventTypes._POINTERTAP;
  1287. },
  1288. enumerable: true,
  1289. configurable: true
  1290. });
  1291. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1292. get: function () {
  1293. return PointerEventTypes._POINTERDOUBLETAP;
  1294. },
  1295. enumerable: true,
  1296. configurable: true
  1297. });
  1298. PointerEventTypes._POINTERDOWN = 0x01;
  1299. PointerEventTypes._POINTERUP = 0x02;
  1300. PointerEventTypes._POINTERMOVE = 0x04;
  1301. PointerEventTypes._POINTERWHEEL = 0x08;
  1302. PointerEventTypes._POINTERPICK = 0x10;
  1303. PointerEventTypes._POINTERTAP = 0x20;
  1304. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1305. return PointerEventTypes;
  1306. }());
  1307. BABYLON.PointerEventTypes = PointerEventTypes;
  1308. var PointerInfoBase = /** @class */ (function () {
  1309. function PointerInfoBase(type, event) {
  1310. this.type = type;
  1311. this.event = event;
  1312. }
  1313. return PointerInfoBase;
  1314. }());
  1315. BABYLON.PointerInfoBase = PointerInfoBase;
  1316. /**
  1317. * This class is used to store pointer related info for the onPrePointerObservable event.
  1318. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1319. */
  1320. var PointerInfoPre = /** @class */ (function (_super) {
  1321. __extends(PointerInfoPre, _super);
  1322. function PointerInfoPre(type, event, localX, localY) {
  1323. var _this = _super.call(this, type, event) || this;
  1324. _this.skipOnPointerObservable = false;
  1325. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1326. return _this;
  1327. }
  1328. return PointerInfoPre;
  1329. }(PointerInfoBase));
  1330. BABYLON.PointerInfoPre = PointerInfoPre;
  1331. /**
  1332. * This type contains all the data related to a pointer event in Babylon.js.
  1333. * 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.
  1334. */
  1335. var PointerInfo = /** @class */ (function (_super) {
  1336. __extends(PointerInfo, _super);
  1337. function PointerInfo(type, event, pickInfo) {
  1338. var _this = _super.call(this, type, event) || this;
  1339. _this.pickInfo = pickInfo;
  1340. return _this;
  1341. }
  1342. return PointerInfo;
  1343. }(PointerInfoBase));
  1344. BABYLON.PointerInfo = PointerInfo;
  1345. })(BABYLON || (BABYLON = {}));
  1346. //# sourceMappingURL=babylon.pointerEvents.js.map
  1347. var BABYLON;
  1348. (function (BABYLON) {
  1349. BABYLON.ToGammaSpace = 1 / 2.2;
  1350. BABYLON.ToLinearSpace = 2.2;
  1351. BABYLON.Epsilon = 0.001;
  1352. /**
  1353. * Class used to hold a RBG color
  1354. */
  1355. var Color3 = /** @class */ (function () {
  1356. /**
  1357. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1358. * @param r defines the red component (between 0 and 1, default is 0)
  1359. * @param g defines the green component (between 0 and 1, default is 0)
  1360. * @param b defines the blue component (between 0 and 1, default is 0)
  1361. */
  1362. function Color3(
  1363. /**
  1364. * Defines the red component (between 0 and 1, default is 0)
  1365. */
  1366. r,
  1367. /**
  1368. * Defines the green component (between 0 and 1, default is 0)
  1369. */
  1370. g,
  1371. /**
  1372. * Defines the blue component (between 0 and 1, default is 0)
  1373. */
  1374. b) {
  1375. if (r === void 0) { r = 0; }
  1376. if (g === void 0) { g = 0; }
  1377. if (b === void 0) { b = 0; }
  1378. this.r = r;
  1379. this.g = g;
  1380. this.b = b;
  1381. }
  1382. /**
  1383. * Creates a string with the Color3 current values
  1384. * @returns the string representation of the Color3 object
  1385. */
  1386. Color3.prototype.toString = function () {
  1387. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1388. };
  1389. /**
  1390. * Returns the string "Color3"
  1391. * @returns "Color3"
  1392. */
  1393. Color3.prototype.getClassName = function () {
  1394. return "Color3";
  1395. };
  1396. /**
  1397. * Compute the Color3 hash code
  1398. * @returns an unique number that can be used to hash Color3 objects
  1399. */
  1400. Color3.prototype.getHashCode = function () {
  1401. var hash = this.r || 0;
  1402. hash = (hash * 397) ^ (this.g || 0);
  1403. hash = (hash * 397) ^ (this.b || 0);
  1404. return hash;
  1405. };
  1406. // Operators
  1407. /**
  1408. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1409. * @param array defines the array where to store the r,g,b components
  1410. * @param index defines an optional index in the target array to define where to start storing values
  1411. * @returns the current Color3 object
  1412. */
  1413. Color3.prototype.toArray = function (array, index) {
  1414. if (index === undefined) {
  1415. index = 0;
  1416. }
  1417. array[index] = this.r;
  1418. array[index + 1] = this.g;
  1419. array[index + 2] = this.b;
  1420. return this;
  1421. };
  1422. /**
  1423. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1424. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1425. * @returns a new {BABYLON.Color4} object
  1426. */
  1427. Color3.prototype.toColor4 = function (alpha) {
  1428. if (alpha === void 0) { alpha = 1; }
  1429. return new Color4(this.r, this.g, this.b, alpha);
  1430. };
  1431. /**
  1432. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1433. * @returns the new array
  1434. */
  1435. Color3.prototype.asArray = function () {
  1436. var result = new Array();
  1437. this.toArray(result, 0);
  1438. return result;
  1439. };
  1440. /**
  1441. * Returns the luminance value
  1442. * @returns a float value
  1443. */
  1444. Color3.prototype.toLuminance = function () {
  1445. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1446. };
  1447. /**
  1448. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1449. * @param otherColor defines the second operand
  1450. * @returns the new Color3 object
  1451. */
  1452. Color3.prototype.multiply = function (otherColor) {
  1453. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1454. };
  1455. /**
  1456. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1457. * @param otherColor defines the second operand
  1458. * @param result defines the Color3 object where to store the result
  1459. * @returns the current Color3
  1460. */
  1461. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1462. result.r = this.r * otherColor.r;
  1463. result.g = this.g * otherColor.g;
  1464. result.b = this.b * otherColor.b;
  1465. return this;
  1466. };
  1467. /**
  1468. * Determines equality between Color3 objects
  1469. * @param otherColor defines the second operand
  1470. * @returns true if the rgb values are equal to the passed ones
  1471. */
  1472. Color3.prototype.equals = function (otherColor) {
  1473. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1474. };
  1475. /**
  1476. * Determines equality between the current Color3 object and a set of r,b,g values
  1477. * @param r defines the red component to check
  1478. * @param g defines the green component to check
  1479. * @param b defines the blue component to check
  1480. * @returns true if the rgb values are equal to the passed ones
  1481. */
  1482. Color3.prototype.equalsFloats = function (r, g, b) {
  1483. return this.r === r && this.g === g && this.b === b;
  1484. };
  1485. /**
  1486. * Multiplies in place each rgb value by scale
  1487. * @param scale defines the scaling factor
  1488. * @returns the updated Color3.
  1489. */
  1490. Color3.prototype.scale = function (scale) {
  1491. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1492. };
  1493. /**
  1494. * Multiplies the rgb values by scale and stores the result into "result"
  1495. * @param scale defines the scaling factor
  1496. * @param result defines the Color3 object where to store the result
  1497. * @returns the unmodified current Color3.
  1498. */
  1499. Color3.prototype.scaleToRef = function (scale, result) {
  1500. result.r = this.r * scale;
  1501. result.g = this.g * scale;
  1502. result.b = this.b * scale;
  1503. return this;
  1504. };
  1505. /**
  1506. * Clamps the rgb values by the min and max values and stores the result into "result"
  1507. * @param min defines minimum clamping value (default is 0)
  1508. * @param max defines maximum clamping value (default is 1)
  1509. * @param result defines color to store the result into
  1510. * @returns the original Color3
  1511. */
  1512. Color3.prototype.clampToRef = function (min, max, result) {
  1513. if (min === void 0) { min = 0; }
  1514. if (max === void 0) { max = 1; }
  1515. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1516. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1517. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1518. return this;
  1519. };
  1520. /**
  1521. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1522. * @param otherColor defines the second operand
  1523. * @returns the new Color3
  1524. */
  1525. Color3.prototype.add = function (otherColor) {
  1526. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1527. };
  1528. /**
  1529. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1530. * @param otherColor defines the second operand
  1531. * @param result defines Color3 object to store the result into
  1532. * @returns the unmodified current Color3
  1533. */
  1534. Color3.prototype.addToRef = function (otherColor, result) {
  1535. result.r = this.r + otherColor.r;
  1536. result.g = this.g + otherColor.g;
  1537. result.b = this.b + otherColor.b;
  1538. return this;
  1539. };
  1540. /**
  1541. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1542. * @param otherColor defines the second operand
  1543. * @returns the new Color3
  1544. */
  1545. Color3.prototype.subtract = function (otherColor) {
  1546. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1547. };
  1548. /**
  1549. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1550. * @param otherColor defines the second operand
  1551. * @param result defines Color3 object to store the result into
  1552. * @returns the unmodified current Color3
  1553. */
  1554. Color3.prototype.subtractToRef = function (otherColor, result) {
  1555. result.r = this.r - otherColor.r;
  1556. result.g = this.g - otherColor.g;
  1557. result.b = this.b - otherColor.b;
  1558. return this;
  1559. };
  1560. /**
  1561. * Copy the current object
  1562. * @returns a new Color3 copied the current one
  1563. */
  1564. Color3.prototype.clone = function () {
  1565. return new Color3(this.r, this.g, this.b);
  1566. };
  1567. /**
  1568. * Copies the rgb values from the source in the current Color3
  1569. * @param source defines the source Color3 object
  1570. * @returns the updated Color3 object
  1571. */
  1572. Color3.prototype.copyFrom = function (source) {
  1573. this.r = source.r;
  1574. this.g = source.g;
  1575. this.b = source.b;
  1576. return this;
  1577. };
  1578. /**
  1579. * Updates the Color3 rgb values from the passed floats
  1580. * @param r defines the red component to read from
  1581. * @param g defines the green component to read from
  1582. * @param b defines the blue component to read from
  1583. * @returns the current Color3 object
  1584. */
  1585. Color3.prototype.copyFromFloats = function (r, g, b) {
  1586. this.r = r;
  1587. this.g = g;
  1588. this.b = b;
  1589. return this;
  1590. };
  1591. /**
  1592. * Updates the Color3 rgb values from the passed floats
  1593. * @param r defines the red component to read from
  1594. * @param g defines the green component to read from
  1595. * @param b defines the blue component to read from
  1596. * @returns the current Color3 object
  1597. */
  1598. Color3.prototype.set = function (r, g, b) {
  1599. return this.copyFromFloats(r, g, b);
  1600. };
  1601. /**
  1602. * Compute the Color3 hexadecimal code as a string
  1603. * @returns a string containing the hexadecimal representation of the Color3 object
  1604. */
  1605. Color3.prototype.toHexString = function () {
  1606. var intR = (this.r * 255) | 0;
  1607. var intG = (this.g * 255) | 0;
  1608. var intB = (this.b * 255) | 0;
  1609. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1610. };
  1611. /**
  1612. * Computes a new Color3 converted from the current one to linear space
  1613. * @returns a new Color3 object
  1614. */
  1615. Color3.prototype.toLinearSpace = function () {
  1616. var convertedColor = new Color3();
  1617. this.toLinearSpaceToRef(convertedColor);
  1618. return convertedColor;
  1619. };
  1620. /**
  1621. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1622. * @param convertedColor defines the Color3 object where to store the linear space version
  1623. * @returns the unmodified Color3
  1624. */
  1625. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1626. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1627. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1628. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1629. return this;
  1630. };
  1631. /**
  1632. * Computes a new Color3 converted from the current one to gamma space
  1633. * @returns a new Color3 object
  1634. */
  1635. Color3.prototype.toGammaSpace = function () {
  1636. var convertedColor = new Color3();
  1637. this.toGammaSpaceToRef(convertedColor);
  1638. return convertedColor;
  1639. };
  1640. /**
  1641. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1642. * @param convertedColor defines the Color3 object where to store the gamma space version
  1643. * @returns the unmodified Color3
  1644. */
  1645. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1646. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1647. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1648. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1649. return this;
  1650. };
  1651. // Statics
  1652. /**
  1653. * Creates a new Color3 from the string containing valid hexadecimal values
  1654. * @param hex defines a string containing valid hexadecimal values
  1655. * @returns a new Color3 object
  1656. */
  1657. Color3.FromHexString = function (hex) {
  1658. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1659. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1660. return new Color3(0, 0, 0);
  1661. }
  1662. var r = parseInt(hex.substring(1, 3), 16);
  1663. var g = parseInt(hex.substring(3, 5), 16);
  1664. var b = parseInt(hex.substring(5, 7), 16);
  1665. return Color3.FromInts(r, g, b);
  1666. };
  1667. /**
  1668. * Creates a new Vector3 from the starting index of the passed array
  1669. * @param array defines the source array
  1670. * @param offset defines an offset in the source array
  1671. * @returns a new Color3 object
  1672. */
  1673. Color3.FromArray = function (array, offset) {
  1674. if (offset === void 0) { offset = 0; }
  1675. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1676. };
  1677. /**
  1678. * Creates a new Color3 from integer values (< 256)
  1679. * @param r defines the red component to read from (value between 0 and 255)
  1680. * @param g defines the green component to read from (value between 0 and 255)
  1681. * @param b defines the blue component to read from (value between 0 and 255)
  1682. * @returns a new Color3 object
  1683. */
  1684. Color3.FromInts = function (r, g, b) {
  1685. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1686. };
  1687. /**
  1688. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1689. * @param start defines the start Color3 value
  1690. * @param end defines the end Color3 value
  1691. * @param amount defines the gradient value between start and end
  1692. * @returns a new Color3 object
  1693. */
  1694. Color3.Lerp = function (start, end, amount) {
  1695. var r = start.r + ((end.r - start.r) * amount);
  1696. var g = start.g + ((end.g - start.g) * amount);
  1697. var b = start.b + ((end.b - start.b) * amount);
  1698. return new Color3(r, g, b);
  1699. };
  1700. /**
  1701. * Returns a Color3 value containing a red color
  1702. * @returns a new Color3 object
  1703. */
  1704. Color3.Red = function () { return new Color3(1, 0, 0); };
  1705. /**
  1706. * Returns a Color3 value containing a green color
  1707. * @returns a new Color3 object
  1708. */
  1709. Color3.Green = function () { return new Color3(0, 1, 0); };
  1710. /**
  1711. * Returns a Color3 value containing a blue color
  1712. * @returns a new Color3 object
  1713. */
  1714. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1715. /**
  1716. * Returns a Color3 value containing a black color
  1717. * @returns a new Color3 object
  1718. */
  1719. Color3.Black = function () { return new Color3(0, 0, 0); };
  1720. /**
  1721. * Returns a Color3 value containing a white color
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.White = function () { return new Color3(1, 1, 1); };
  1725. /**
  1726. * Returns a Color3 value containing a purple color
  1727. * @returns a new Color3 object
  1728. */
  1729. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1730. /**
  1731. * Returns a Color3 value containing a magenta color
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1735. /**
  1736. * Returns a Color3 value containing a yellow color
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1740. /**
  1741. * Returns a Color3 value containing a gray color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1745. /**
  1746. * Returns a Color3 value containing a teal color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1750. /**
  1751. * Returns a Color3 value containing a random color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1755. return Color3;
  1756. }());
  1757. BABYLON.Color3 = Color3;
  1758. /**
  1759. * Class used to hold a RBGA color
  1760. */
  1761. var Color4 = /** @class */ (function () {
  1762. /**
  1763. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1764. * @param r defines the red component (between 0 and 1, default is 0)
  1765. * @param g defines the green component (between 0 and 1, default is 0)
  1766. * @param b defines the blue component (between 0 and 1, default is 0)
  1767. * @param a defines the alpha component (between 0 and 1, default is 1)
  1768. */
  1769. function Color4(
  1770. /**
  1771. * Defines the red component (between 0 and 1, default is 0)
  1772. */
  1773. r,
  1774. /**
  1775. * Defines the green component (between 0 and 1, default is 0)
  1776. */
  1777. g,
  1778. /**
  1779. * Defines the blue component (between 0 and 1, default is 0)
  1780. */
  1781. b,
  1782. /**
  1783. * Defines the alpha component (between 0 and 1, default is 1)
  1784. */
  1785. a) {
  1786. if (r === void 0) { r = 0; }
  1787. if (g === void 0) { g = 0; }
  1788. if (b === void 0) { b = 0; }
  1789. if (a === void 0) { a = 1; }
  1790. this.r = r;
  1791. this.g = g;
  1792. this.b = b;
  1793. this.a = a;
  1794. }
  1795. // Operators
  1796. /**
  1797. * Adds in place the passed Color4 values to the current Color4 object
  1798. * @param right defines the second operand
  1799. * @returns the current updated Color4 object
  1800. */
  1801. Color4.prototype.addInPlace = function (right) {
  1802. this.r += right.r;
  1803. this.g += right.g;
  1804. this.b += right.b;
  1805. this.a += right.a;
  1806. return this;
  1807. };
  1808. /**
  1809. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1810. * @returns the new array
  1811. */
  1812. Color4.prototype.asArray = function () {
  1813. var result = new Array();
  1814. this.toArray(result, 0);
  1815. return result;
  1816. };
  1817. /**
  1818. * Stores from the starting index in the passed array the Color4 successive values
  1819. * @param array defines the array where to store the r,g,b components
  1820. * @param index defines an optional index in the target array to define where to start storing values
  1821. * @returns the current Color4 object
  1822. */
  1823. Color4.prototype.toArray = function (array, index) {
  1824. if (index === undefined) {
  1825. index = 0;
  1826. }
  1827. array[index] = this.r;
  1828. array[index + 1] = this.g;
  1829. array[index + 2] = this.b;
  1830. array[index + 3] = this.a;
  1831. return this;
  1832. };
  1833. /**
  1834. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1835. * @param right defines the second operand
  1836. * @returns a new Color4 object
  1837. */
  1838. Color4.prototype.add = function (right) {
  1839. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1840. };
  1841. /**
  1842. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1843. * @param right defines the second operand
  1844. * @returns a new Color4 object
  1845. */
  1846. Color4.prototype.subtract = function (right) {
  1847. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1848. };
  1849. /**
  1850. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1851. * @param right defines the second operand
  1852. * @param result defines the Color4 object where to store the result
  1853. * @returns the current Color4 object
  1854. */
  1855. Color4.prototype.subtractToRef = function (right, result) {
  1856. result.r = this.r - right.r;
  1857. result.g = this.g - right.g;
  1858. result.b = this.b - right.b;
  1859. result.a = this.a - right.a;
  1860. return this;
  1861. };
  1862. /**
  1863. * Creates a new Color4 with the current Color4 values multiplied by scale
  1864. * @param scale defines the scaling factor to apply
  1865. * @returns a new Color4 object
  1866. */
  1867. Color4.prototype.scale = function (scale) {
  1868. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1869. };
  1870. /**
  1871. * Multiplies the current Color4 values by scale and stores the result in "result"
  1872. * @param scale defines the scaling factor to apply
  1873. * @param result defines the Color4 object where to store the result
  1874. * @returns the current Color4.
  1875. */
  1876. Color4.prototype.scaleToRef = function (scale, result) {
  1877. result.r = this.r * scale;
  1878. result.g = this.g * scale;
  1879. result.b = this.b * scale;
  1880. result.a = this.a * scale;
  1881. return this;
  1882. };
  1883. /**
  1884. * Clamps the rgb values by the min and max values and stores the result into "result"
  1885. * @param min defines minimum clamping value (default is 0)
  1886. * @param max defines maximum clamping value (default is 1)
  1887. * @param result defines color to store the result into.
  1888. * @returns the cuurent Color4
  1889. */
  1890. Color4.prototype.clampToRef = function (min, max, result) {
  1891. if (min === void 0) { min = 0; }
  1892. if (max === void 0) { max = 1; }
  1893. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1894. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1895. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1896. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1897. return this;
  1898. };
  1899. /**
  1900. * Multipy an Color4 value by another and return a new Color4 object
  1901. * @param color defines the Color4 value to multiply by
  1902. * @returns a new Color4 object
  1903. */
  1904. Color4.prototype.multiply = function (color) {
  1905. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1906. };
  1907. /**
  1908. * Multipy a Color4 value by another and push the result in a reference value
  1909. * @param color defines the Color4 value to multiply by
  1910. * @param result defines the Color4 to fill the result in
  1911. * @returns the result Color4
  1912. */
  1913. Color4.prototype.multiplyToRef = function (color, result) {
  1914. result.r = this.r * color.r;
  1915. result.g = this.g * color.g;
  1916. result.b = this.b * color.b;
  1917. result.a = this.a * color.a;
  1918. return result;
  1919. };
  1920. /**
  1921. * Creates a string with the Color4 current values
  1922. * @returns the string representation of the Color4 object
  1923. */
  1924. Color4.prototype.toString = function () {
  1925. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1926. };
  1927. /**
  1928. * Returns the string "Color4"
  1929. * @returns "Color4"
  1930. */
  1931. Color4.prototype.getClassName = function () {
  1932. return "Color4";
  1933. };
  1934. /**
  1935. * Compute the Color4 hash code
  1936. * @returns an unique number that can be used to hash Color4 objects
  1937. */
  1938. Color4.prototype.getHashCode = function () {
  1939. var hash = this.r || 0;
  1940. hash = (hash * 397) ^ (this.g || 0);
  1941. hash = (hash * 397) ^ (this.b || 0);
  1942. hash = (hash * 397) ^ (this.a || 0);
  1943. return hash;
  1944. };
  1945. /**
  1946. * Creates a new Color4 copied from the current one
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.clone = function () {
  1950. return new Color4(this.r, this.g, this.b, this.a);
  1951. };
  1952. /**
  1953. * Copies the passed Color4 values into the current one
  1954. * @param source defines the source Color4 object
  1955. * @returns the current updated Color4 object
  1956. */
  1957. Color4.prototype.copyFrom = function (source) {
  1958. this.r = source.r;
  1959. this.g = source.g;
  1960. this.b = source.b;
  1961. this.a = source.a;
  1962. return this;
  1963. };
  1964. /**
  1965. * Copies the passed float values into the current one
  1966. * @param r defines the red component to read from
  1967. * @param g defines the green component to read from
  1968. * @param b defines the blue component to read from
  1969. * @param a defines the alpha component to read from
  1970. * @returns the current updated Color4 object
  1971. */
  1972. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1973. this.r = r;
  1974. this.g = g;
  1975. this.b = b;
  1976. this.a = a;
  1977. return this;
  1978. };
  1979. /**
  1980. * Copies the passed float values into the current one
  1981. * @param r defines the red component to read from
  1982. * @param g defines the green component to read from
  1983. * @param b defines the blue component to read from
  1984. * @param a defines the alpha component to read from
  1985. * @returns the current updated Color4 object
  1986. */
  1987. Color4.prototype.set = function (r, g, b, a) {
  1988. return this.copyFromFloats(r, g, b, a);
  1989. };
  1990. /**
  1991. * Compute the Color4 hexadecimal code as a string
  1992. * @returns a string containing the hexadecimal representation of the Color4 object
  1993. */
  1994. Color4.prototype.toHexString = function () {
  1995. var intR = (this.r * 255) | 0;
  1996. var intG = (this.g * 255) | 0;
  1997. var intB = (this.b * 255) | 0;
  1998. var intA = (this.a * 255) | 0;
  1999. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2000. };
  2001. /**
  2002. * Computes a new Color4 converted from the current one to linear space
  2003. * @returns a new Color4 object
  2004. */
  2005. Color4.prototype.toLinearSpace = function () {
  2006. var convertedColor = new Color4();
  2007. this.toLinearSpaceToRef(convertedColor);
  2008. return convertedColor;
  2009. };
  2010. /**
  2011. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2012. * @param convertedColor defines the Color4 object where to store the linear space version
  2013. * @returns the unmodified Color4
  2014. */
  2015. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2016. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2017. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2018. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2019. convertedColor.a = this.a;
  2020. return this;
  2021. };
  2022. /**
  2023. * Computes a new Color4 converted from the current one to gamma space
  2024. * @returns a new Color4 object
  2025. */
  2026. Color4.prototype.toGammaSpace = function () {
  2027. var convertedColor = new Color4();
  2028. this.toGammaSpaceToRef(convertedColor);
  2029. return convertedColor;
  2030. };
  2031. /**
  2032. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2033. * @param convertedColor defines the Color4 object where to store the gamma space version
  2034. * @returns the unmodified Color4
  2035. */
  2036. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2037. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2038. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2039. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2040. convertedColor.a = this.a;
  2041. return this;
  2042. };
  2043. // Statics
  2044. /**
  2045. * Creates a new Color4 from the string containing valid hexadecimal values
  2046. * @param hex defines a string containing valid hexadecimal values
  2047. * @returns a new Color4 object
  2048. */
  2049. Color4.FromHexString = function (hex) {
  2050. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2051. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  2052. return new Color4(0.0, 0.0, 0.0, 0.0);
  2053. }
  2054. var r = parseInt(hex.substring(1, 3), 16);
  2055. var g = parseInt(hex.substring(3, 5), 16);
  2056. var b = parseInt(hex.substring(5, 7), 16);
  2057. var a = parseInt(hex.substring(7, 9), 16);
  2058. return Color4.FromInts(r, g, b, a);
  2059. };
  2060. /**
  2061. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2062. * @param left defines the start value
  2063. * @param right defines the end value
  2064. * @param amount defines the gradient factor
  2065. * @returns a new Color4 object
  2066. */
  2067. Color4.Lerp = function (left, right, amount) {
  2068. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2069. Color4.LerpToRef(left, right, amount, result);
  2070. return result;
  2071. };
  2072. /**
  2073. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2074. * @param left defines the start value
  2075. * @param right defines the end value
  2076. * @param amount defines the gradient factor
  2077. * @param result defines the Color4 object where to store data
  2078. */
  2079. Color4.LerpToRef = function (left, right, amount, result) {
  2080. result.r = left.r + (right.r - left.r) * amount;
  2081. result.g = left.g + (right.g - left.g) * amount;
  2082. result.b = left.b + (right.b - left.b) * amount;
  2083. result.a = left.a + (right.a - left.a) * amount;
  2084. };
  2085. /**
  2086. * Creates a new Color4 from the starting index element of the passed array
  2087. * @param array defines the source array to read from
  2088. * @param offset defines the offset in the source array
  2089. * @returns a new Color4 object
  2090. */
  2091. Color4.FromArray = function (array, offset) {
  2092. if (offset === void 0) { offset = 0; }
  2093. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2094. };
  2095. /**
  2096. * Creates a new Color3 from integer values (< 256)
  2097. * @param r defines the red component to read from (value between 0 and 255)
  2098. * @param g defines the green component to read from (value between 0 and 255)
  2099. * @param b defines the blue component to read from (value between 0 and 255)
  2100. * @param a defines the alpha component to read from (value between 0 and 255)
  2101. * @returns a new Color3 object
  2102. */
  2103. Color4.FromInts = function (r, g, b, a) {
  2104. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2105. };
  2106. /**
  2107. * Check the content of a given array and convert it to an array containing RGBA data
  2108. * If the original array was already containing count * 4 values then it is returned directly
  2109. * @param colors defines the array to check
  2110. * @param count defines the number of RGBA data to expect
  2111. * @returns an array containing count * 4 values (RGBA)
  2112. */
  2113. Color4.CheckColors4 = function (colors, count) {
  2114. // Check if color3 was used
  2115. if (colors.length === count * 3) {
  2116. var colors4 = [];
  2117. for (var index = 0; index < colors.length; index += 3) {
  2118. var newIndex = (index / 3) * 4;
  2119. colors4[newIndex] = colors[index];
  2120. colors4[newIndex + 1] = colors[index + 1];
  2121. colors4[newIndex + 2] = colors[index + 2];
  2122. colors4[newIndex + 3] = 1.0;
  2123. }
  2124. return colors4;
  2125. }
  2126. return colors;
  2127. };
  2128. return Color4;
  2129. }());
  2130. BABYLON.Color4 = Color4;
  2131. var Vector2 = /** @class */ (function () {
  2132. /**
  2133. * Creates a new Vector2 from the passed x and y coordinates.
  2134. */
  2135. function Vector2(x, y) {
  2136. this.x = x;
  2137. this.y = y;
  2138. }
  2139. /**
  2140. * Returns a string with the Vector2 coordinates.
  2141. */
  2142. Vector2.prototype.toString = function () {
  2143. return "{X: " + this.x + " Y:" + this.y + "}";
  2144. };
  2145. /**
  2146. * Returns the string "Vector2"
  2147. */
  2148. Vector2.prototype.getClassName = function () {
  2149. return "Vector2";
  2150. };
  2151. /**
  2152. * Returns the Vector2 hash code as a number.
  2153. */
  2154. Vector2.prototype.getHashCode = function () {
  2155. var hash = this.x || 0;
  2156. hash = (hash * 397) ^ (this.y || 0);
  2157. return hash;
  2158. };
  2159. // Operators
  2160. /**
  2161. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2162. * Returns the Vector2.
  2163. */
  2164. Vector2.prototype.toArray = function (array, index) {
  2165. if (index === void 0) { index = 0; }
  2166. array[index] = this.x;
  2167. array[index + 1] = this.y;
  2168. return this;
  2169. };
  2170. /**
  2171. * Returns a new array with 2 elements : the Vector2 coordinates.
  2172. */
  2173. Vector2.prototype.asArray = function () {
  2174. var result = new Array();
  2175. this.toArray(result, 0);
  2176. return result;
  2177. };
  2178. /**
  2179. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2180. * Returns the updated Vector2.
  2181. */
  2182. Vector2.prototype.copyFrom = function (source) {
  2183. this.x = source.x;
  2184. this.y = source.y;
  2185. return this;
  2186. };
  2187. /**
  2188. * Sets the Vector2 coordinates with the passed floats.
  2189. * Returns the updated Vector2.
  2190. */
  2191. Vector2.prototype.copyFromFloats = function (x, y) {
  2192. this.x = x;
  2193. this.y = y;
  2194. return this;
  2195. };
  2196. /**
  2197. * Sets the Vector2 coordinates with the passed floats.
  2198. * Returns the updated Vector2.
  2199. */
  2200. Vector2.prototype.set = function (x, y) {
  2201. return this.copyFromFloats(x, y);
  2202. };
  2203. /**
  2204. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2205. */
  2206. Vector2.prototype.add = function (otherVector) {
  2207. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2208. };
  2209. /**
  2210. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2211. * Returns the Vector2.
  2212. */
  2213. Vector2.prototype.addToRef = function (otherVector, result) {
  2214. result.x = this.x + otherVector.x;
  2215. result.y = this.y + otherVector.y;
  2216. return this;
  2217. };
  2218. /**
  2219. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2220. * Returns the updated Vector2.
  2221. */
  2222. Vector2.prototype.addInPlace = function (otherVector) {
  2223. this.x += otherVector.x;
  2224. this.y += otherVector.y;
  2225. return this;
  2226. };
  2227. /**
  2228. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2229. */
  2230. Vector2.prototype.addVector3 = function (otherVector) {
  2231. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2232. };
  2233. /**
  2234. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2235. */
  2236. Vector2.prototype.subtract = function (otherVector) {
  2237. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2238. };
  2239. /**
  2240. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2241. * Returns the Vector2.
  2242. */
  2243. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2244. result.x = this.x - otherVector.x;
  2245. result.y = this.y - otherVector.y;
  2246. return this;
  2247. };
  2248. /**
  2249. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2250. * Returns the updated Vector2.
  2251. */
  2252. Vector2.prototype.subtractInPlace = function (otherVector) {
  2253. this.x -= otherVector.x;
  2254. this.y -= otherVector.y;
  2255. return this;
  2256. };
  2257. /**
  2258. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2259. * Returns the updated Vector2.
  2260. */
  2261. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2262. this.x *= otherVector.x;
  2263. this.y *= otherVector.y;
  2264. return this;
  2265. };
  2266. /**
  2267. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2268. */
  2269. Vector2.prototype.multiply = function (otherVector) {
  2270. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2271. };
  2272. /**
  2273. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2274. * Returns the Vector2.
  2275. */
  2276. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2277. result.x = this.x * otherVector.x;
  2278. result.y = this.y * otherVector.y;
  2279. return this;
  2280. };
  2281. /**
  2282. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2283. */
  2284. Vector2.prototype.multiplyByFloats = function (x, y) {
  2285. return new Vector2(this.x * x, this.y * y);
  2286. };
  2287. /**
  2288. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2289. */
  2290. Vector2.prototype.divide = function (otherVector) {
  2291. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2292. };
  2293. /**
  2294. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2295. * Returns the Vector2.
  2296. */
  2297. Vector2.prototype.divideToRef = function (otherVector, result) {
  2298. result.x = this.x / otherVector.x;
  2299. result.y = this.y / otherVector.y;
  2300. return this;
  2301. };
  2302. /**
  2303. * Divides the current Vector3 coordinates by the passed ones.
  2304. * Returns the updated Vector3.
  2305. */
  2306. Vector2.prototype.divideInPlace = function (otherVector) {
  2307. return this.divideToRef(otherVector, this);
  2308. };
  2309. /**
  2310. * Returns a new Vector2 with current Vector2 negated coordinates.
  2311. */
  2312. Vector2.prototype.negate = function () {
  2313. return new Vector2(-this.x, -this.y);
  2314. };
  2315. /**
  2316. * Multiply the Vector2 coordinates by scale.
  2317. * Returns the updated Vector2.
  2318. */
  2319. Vector2.prototype.scaleInPlace = function (scale) {
  2320. this.x *= scale;
  2321. this.y *= scale;
  2322. return this;
  2323. };
  2324. /**
  2325. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2326. */
  2327. Vector2.prototype.scale = function (scale) {
  2328. return new Vector2(this.x * scale, this.y * scale);
  2329. };
  2330. /**
  2331. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2332. */
  2333. Vector2.prototype.equals = function (otherVector) {
  2334. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2335. };
  2336. /**
  2337. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2338. */
  2339. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2340. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2341. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2342. };
  2343. // Properties
  2344. /**
  2345. * Returns the vector length (float).
  2346. */
  2347. Vector2.prototype.length = function () {
  2348. return Math.sqrt(this.x * this.x + this.y * this.y);
  2349. };
  2350. /**
  2351. * Returns the vector squared length (float);
  2352. */
  2353. Vector2.prototype.lengthSquared = function () {
  2354. return (this.x * this.x + this.y * this.y);
  2355. };
  2356. // Methods
  2357. /**
  2358. * Normalize the vector.
  2359. * Returns the updated Vector2.
  2360. */
  2361. Vector2.prototype.normalize = function () {
  2362. var len = this.length();
  2363. if (len === 0)
  2364. return this;
  2365. var num = 1.0 / len;
  2366. this.x *= num;
  2367. this.y *= num;
  2368. return this;
  2369. };
  2370. /**
  2371. * Returns a new Vector2 copied from the Vector2.
  2372. */
  2373. Vector2.prototype.clone = function () {
  2374. return new Vector2(this.x, this.y);
  2375. };
  2376. // Statics
  2377. /**
  2378. * Returns a new Vector2(0, 0)
  2379. */
  2380. Vector2.Zero = function () {
  2381. return new Vector2(0, 0);
  2382. };
  2383. /**
  2384. * Returns a new Vector2(1, 1)
  2385. */
  2386. Vector2.One = function () {
  2387. return new Vector2(1, 1);
  2388. };
  2389. /**
  2390. * Returns a new Vector2 set from the passed index element of the passed array.
  2391. */
  2392. Vector2.FromArray = function (array, offset) {
  2393. if (offset === void 0) { offset = 0; }
  2394. return new Vector2(array[offset], array[offset + 1]);
  2395. };
  2396. /**
  2397. * Sets "result" from the passed index element of the passed array.
  2398. */
  2399. Vector2.FromArrayToRef = function (array, offset, result) {
  2400. result.x = array[offset];
  2401. result.y = array[offset + 1];
  2402. };
  2403. /**
  2404. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2405. */
  2406. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2407. var squared = amount * amount;
  2408. var cubed = amount * squared;
  2409. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2410. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2411. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2412. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2413. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2414. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2415. return new Vector2(x, y);
  2416. };
  2417. /**
  2418. * 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".
  2419. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2420. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2421. */
  2422. Vector2.Clamp = function (value, min, max) {
  2423. var x = value.x;
  2424. x = (x > max.x) ? max.x : x;
  2425. x = (x < min.x) ? min.x : x;
  2426. var y = value.y;
  2427. y = (y > max.y) ? max.y : y;
  2428. y = (y < min.y) ? min.y : y;
  2429. return new Vector2(x, y);
  2430. };
  2431. /**
  2432. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2433. */
  2434. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2435. var squared = amount * amount;
  2436. var cubed = amount * squared;
  2437. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2438. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2439. var part3 = (cubed - (2.0 * squared)) + amount;
  2440. var part4 = cubed - squared;
  2441. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2442. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2443. return new Vector2(x, y);
  2444. };
  2445. /**
  2446. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2447. */
  2448. Vector2.Lerp = function (start, end, amount) {
  2449. var x = start.x + ((end.x - start.x) * amount);
  2450. var y = start.y + ((end.y - start.y) * amount);
  2451. return new Vector2(x, y);
  2452. };
  2453. /**
  2454. * Returns the dot product (float) of the vector "left" and the vector "right".
  2455. */
  2456. Vector2.Dot = function (left, right) {
  2457. return left.x * right.x + left.y * right.y;
  2458. };
  2459. /**
  2460. * Returns a new Vector2 equal to the normalized passed vector.
  2461. */
  2462. Vector2.Normalize = function (vector) {
  2463. var newVector = vector.clone();
  2464. newVector.normalize();
  2465. return newVector;
  2466. };
  2467. /**
  2468. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2469. */
  2470. Vector2.Minimize = function (left, right) {
  2471. var x = (left.x < right.x) ? left.x : right.x;
  2472. var y = (left.y < right.y) ? left.y : right.y;
  2473. return new Vector2(x, y);
  2474. };
  2475. /**
  2476. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2477. */
  2478. Vector2.Maximize = function (left, right) {
  2479. var x = (left.x > right.x) ? left.x : right.x;
  2480. var y = (left.y > right.y) ? left.y : right.y;
  2481. return new Vector2(x, y);
  2482. };
  2483. /**
  2484. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2485. */
  2486. Vector2.Transform = function (vector, transformation) {
  2487. var r = Vector2.Zero();
  2488. Vector2.TransformToRef(vector, transformation, r);
  2489. return r;
  2490. };
  2491. /**
  2492. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2493. */
  2494. Vector2.TransformToRef = function (vector, transformation, result) {
  2495. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2496. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2497. result.x = x;
  2498. result.y = y;
  2499. };
  2500. /**
  2501. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2502. */
  2503. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2504. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2505. var sign = a < 0 ? -1 : 1;
  2506. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2507. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2508. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2509. };
  2510. /**
  2511. * Returns the distance (float) between the vectors "value1" and "value2".
  2512. */
  2513. Vector2.Distance = function (value1, value2) {
  2514. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2515. };
  2516. /**
  2517. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2518. */
  2519. Vector2.DistanceSquared = function (value1, value2) {
  2520. var x = value1.x - value2.x;
  2521. var y = value1.y - value2.y;
  2522. return (x * x) + (y * y);
  2523. };
  2524. /**
  2525. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2526. */
  2527. Vector2.Center = function (value1, value2) {
  2528. var center = value1.add(value2);
  2529. center.scaleInPlace(0.5);
  2530. return center;
  2531. };
  2532. /**
  2533. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2534. */
  2535. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2536. var l2 = Vector2.DistanceSquared(segA, segB);
  2537. if (l2 === 0.0) {
  2538. return Vector2.Distance(p, segA);
  2539. }
  2540. var v = segB.subtract(segA);
  2541. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2542. var proj = segA.add(v.multiplyByFloats(t, t));
  2543. return Vector2.Distance(p, proj);
  2544. };
  2545. return Vector2;
  2546. }());
  2547. BABYLON.Vector2 = Vector2;
  2548. /**
  2549. * Classed used to store (x,y,z) vector representation
  2550. * A Vector3 is the main object used in 3D geometry
  2551. * It can represent etiher the coordinates of a point the space, either a direction
  2552. * Reminder: Babylon.js uses a left handed forward facing system
  2553. */
  2554. var Vector3 = /** @class */ (function () {
  2555. /**
  2556. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2557. * @param x defines the first coordinates (on X axis)
  2558. * @param y defines the second coordinates (on Y axis)
  2559. * @param z defines the third coordinates (on Z axis)
  2560. */
  2561. function Vector3(
  2562. /**
  2563. * Defines the first coordinates (on X axis)
  2564. */
  2565. x,
  2566. /**
  2567. * Defines the second coordinates (on Y axis)
  2568. */
  2569. y,
  2570. /**
  2571. * Defines the third coordinates (on Z axis)
  2572. */
  2573. z) {
  2574. this.x = x;
  2575. this.y = y;
  2576. this.z = z;
  2577. }
  2578. /**
  2579. * Creates a string representation of the Vector3
  2580. * @returns a string with the Vector3 coordinates.
  2581. */
  2582. Vector3.prototype.toString = function () {
  2583. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2584. };
  2585. /**
  2586. * Gets the class name
  2587. * @returns the string "Vector3"
  2588. */
  2589. Vector3.prototype.getClassName = function () {
  2590. return "Vector3";
  2591. };
  2592. /**
  2593. * Creates the Vector3 hash code
  2594. * @returns a number which tends to be unique between Vector3 instances
  2595. */
  2596. Vector3.prototype.getHashCode = function () {
  2597. var hash = this.x || 0;
  2598. hash = (hash * 397) ^ (this.y || 0);
  2599. hash = (hash * 397) ^ (this.z || 0);
  2600. return hash;
  2601. };
  2602. // Operators
  2603. /**
  2604. * Creates an array containing three elements : the coordinates of the Vector3
  2605. * @returns a new array of numbers
  2606. */
  2607. Vector3.prototype.asArray = function () {
  2608. var result = [];
  2609. this.toArray(result, 0);
  2610. return result;
  2611. };
  2612. /**
  2613. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2614. * @param array defines the destination array
  2615. * @param index defines the offset in the destination array
  2616. * @returns the current Vector3
  2617. */
  2618. Vector3.prototype.toArray = function (array, index) {
  2619. if (index === void 0) { index = 0; }
  2620. array[index] = this.x;
  2621. array[index + 1] = this.y;
  2622. array[index + 2] = this.z;
  2623. return this;
  2624. };
  2625. /**
  2626. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2627. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2628. */
  2629. Vector3.prototype.toQuaternion = function () {
  2630. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2631. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2632. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2633. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2634. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2635. var cosy = Math.cos(this.y * 0.5);
  2636. var siny = Math.sin(this.y * 0.5);
  2637. result.x = coszMinusx * siny;
  2638. result.y = -sinzMinusx * siny;
  2639. result.z = sinxPlusz * cosy;
  2640. result.w = cosxPlusz * cosy;
  2641. return result;
  2642. };
  2643. /**
  2644. * Adds the passed vector to the current Vector3
  2645. * @param otherVector defines the second operand
  2646. * @returns the current updated Vector3
  2647. */
  2648. Vector3.prototype.addInPlace = function (otherVector) {
  2649. this.x += otherVector.x;
  2650. this.y += otherVector.y;
  2651. this.z += otherVector.z;
  2652. return this;
  2653. };
  2654. /**
  2655. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2656. * @param otherVector defines the second operand
  2657. * @returns the resulting Vector3
  2658. */
  2659. Vector3.prototype.add = function (otherVector) {
  2660. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2661. };
  2662. /**
  2663. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2664. * @param otherVector defines the second operand
  2665. * @param result defines the Vector3 object where to store the result
  2666. * @returns the current Vector3
  2667. */
  2668. Vector3.prototype.addToRef = function (otherVector, result) {
  2669. result.x = this.x + otherVector.x;
  2670. result.y = this.y + otherVector.y;
  2671. result.z = this.z + otherVector.z;
  2672. return this;
  2673. };
  2674. /**
  2675. * Subtract the passed vector from the current Vector3
  2676. * @param otherVector defines the second operand
  2677. * @returns the current updated Vector3
  2678. */
  2679. Vector3.prototype.subtractInPlace = function (otherVector) {
  2680. this.x -= otherVector.x;
  2681. this.y -= otherVector.y;
  2682. this.z -= otherVector.z;
  2683. return this;
  2684. };
  2685. /**
  2686. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2687. * @param otherVector defines the second operand
  2688. * @returns the resulting Vector3
  2689. */
  2690. Vector3.prototype.subtract = function (otherVector) {
  2691. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2692. };
  2693. /**
  2694. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2695. * @param otherVector defines the second operand
  2696. * @param result defines the Vector3 object where to store the result
  2697. * @returns the current Vector3
  2698. */
  2699. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2700. result.x = this.x - otherVector.x;
  2701. result.y = this.y - otherVector.y;
  2702. result.z = this.z - otherVector.z;
  2703. return this;
  2704. };
  2705. /**
  2706. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2707. * @param x defines the x coordinate of the operand
  2708. * @param y defines the y coordinate of the operand
  2709. * @param z defines the z coordinate of the operand
  2710. * @returns the resulting Vector3
  2711. */
  2712. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2713. return new Vector3(this.x - x, this.y - y, this.z - z);
  2714. };
  2715. /**
  2716. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2717. * @param x defines the x coordinate of the operand
  2718. * @param y defines the y coordinate of the operand
  2719. * @param z defines the z coordinate of the operand
  2720. * @param result defines the Vector3 object where to store the result
  2721. * @returns the current Vector3
  2722. */
  2723. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2724. result.x = this.x - x;
  2725. result.y = this.y - y;
  2726. result.z = this.z - z;
  2727. return this;
  2728. };
  2729. /**
  2730. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2731. * @returns a new Vector3
  2732. */
  2733. Vector3.prototype.negate = function () {
  2734. return new Vector3(-this.x, -this.y, -this.z);
  2735. };
  2736. /**
  2737. * Multiplies the Vector3 coordinates by the float "scale"
  2738. * @param scale defines the multiplier factor
  2739. * @returns the current updated Vector3
  2740. */
  2741. Vector3.prototype.scaleInPlace = function (scale) {
  2742. this.x *= scale;
  2743. this.y *= scale;
  2744. this.z *= scale;
  2745. return this;
  2746. };
  2747. /**
  2748. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2749. * @param scale defines the multiplier factor
  2750. * @returns a new Vector3
  2751. */
  2752. Vector3.prototype.scale = function (scale) {
  2753. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2754. };
  2755. /**
  2756. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2757. * @param scale defines the multiplier factor
  2758. * @param result defines the Vector3 object where to store the result
  2759. * @returns the current Vector3
  2760. */
  2761. Vector3.prototype.scaleToRef = function (scale, result) {
  2762. result.x = this.x * scale;
  2763. result.y = this.y * scale;
  2764. result.z = this.z * scale;
  2765. return this;
  2766. };
  2767. /**
  2768. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2769. * @param otherVector defines the second operand
  2770. * @returns true if both vectors are equals
  2771. */
  2772. Vector3.prototype.equals = function (otherVector) {
  2773. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2774. };
  2775. /**
  2776. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2777. * @param otherVector defines the second operand
  2778. * @param epsilon defines the minimal distance to define values as equals
  2779. * @returns true if both vectors are distant less than epsilon
  2780. */
  2781. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2782. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2783. 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);
  2784. };
  2785. /**
  2786. * Returns true if the current Vector3 coordinates equals the passed floats
  2787. * @param x defines the x coordinate of the operand
  2788. * @param y defines the y coordinate of the operand
  2789. * @param z defines the z coordinate of the operand
  2790. * @returns true if both vectors are equals
  2791. */
  2792. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2793. return this.x === x && this.y === y && this.z === z;
  2794. };
  2795. /**
  2796. * Multiplies the current Vector3 coordinates by the passed ones
  2797. * @param otherVector defines the second operand
  2798. * @returns the current updated Vector3
  2799. */
  2800. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2801. this.x *= otherVector.x;
  2802. this.y *= otherVector.y;
  2803. this.z *= otherVector.z;
  2804. return this;
  2805. };
  2806. /**
  2807. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2808. * @param otherVector defines the second operand
  2809. * @returns the new Vector3
  2810. */
  2811. Vector3.prototype.multiply = function (otherVector) {
  2812. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2813. };
  2814. /**
  2815. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2816. * @param otherVector defines the second operand
  2817. * @param result defines the Vector3 object where to store the result
  2818. * @returns the current Vector3
  2819. */
  2820. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2821. result.x = this.x * otherVector.x;
  2822. result.y = this.y * otherVector.y;
  2823. result.z = this.z * otherVector.z;
  2824. return this;
  2825. };
  2826. /**
  2827. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2828. * @param x defines the x coordinate of the operand
  2829. * @param y defines the y coordinate of the operand
  2830. * @param z defines the z coordinate of the operand
  2831. * @returns the new Vector3
  2832. */
  2833. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2834. return new Vector3(this.x * x, this.y * y, this.z * z);
  2835. };
  2836. /**
  2837. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2838. * @param otherVector defines the second operand
  2839. * @returns the new Vector3
  2840. */
  2841. Vector3.prototype.divide = function (otherVector) {
  2842. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2843. };
  2844. /**
  2845. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2846. * @param otherVector defines the second operand
  2847. * @param result defines the Vector3 object where to store the result
  2848. * @returns the current Vector3
  2849. */
  2850. Vector3.prototype.divideToRef = function (otherVector, result) {
  2851. result.x = this.x / otherVector.x;
  2852. result.y = this.y / otherVector.y;
  2853. result.z = this.z / otherVector.z;
  2854. return this;
  2855. };
  2856. /**
  2857. * Divides the current Vector3 coordinates by the passed ones.
  2858. * @param otherVector defines the second operand
  2859. * @returns the current updated Vector3
  2860. */
  2861. Vector3.prototype.divideInPlace = function (otherVector) {
  2862. return this.divideToRef(otherVector, this);
  2863. };
  2864. /**
  2865. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2866. * @param other defines the second operand
  2867. * @returns the current updated Vector3
  2868. */
  2869. Vector3.prototype.minimizeInPlace = function (other) {
  2870. if (other.x < this.x)
  2871. this.x = other.x;
  2872. if (other.y < this.y)
  2873. this.y = other.y;
  2874. if (other.z < this.z)
  2875. this.z = other.z;
  2876. return this;
  2877. };
  2878. /**
  2879. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2880. * @param other defines the second operand
  2881. * @returns the current updated Vector3
  2882. */
  2883. Vector3.prototype.maximizeInPlace = function (other) {
  2884. if (other.x > this.x)
  2885. this.x = other.x;
  2886. if (other.y > this.y)
  2887. this.y = other.y;
  2888. if (other.z > this.z)
  2889. this.z = other.z;
  2890. return this;
  2891. };
  2892. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2893. /**
  2894. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2895. */
  2896. get: function () {
  2897. var absX = Math.abs(this.x);
  2898. var absY = Math.abs(this.y);
  2899. if (absX !== absY) {
  2900. return true;
  2901. }
  2902. var absZ = Math.abs(this.z);
  2903. if (absX !== absZ) {
  2904. return true;
  2905. }
  2906. if (absY !== absZ) {
  2907. return true;
  2908. }
  2909. return false;
  2910. },
  2911. enumerable: true,
  2912. configurable: true
  2913. });
  2914. // Properties
  2915. /**
  2916. * Gets the length of the Vector3
  2917. * @returns the length of the Vecto3
  2918. */
  2919. Vector3.prototype.length = function () {
  2920. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2921. };
  2922. /**
  2923. * Gets the squared length of the Vector3
  2924. * @returns squared length of the Vector3
  2925. */
  2926. Vector3.prototype.lengthSquared = function () {
  2927. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2928. };
  2929. /**
  2930. * Normalize the current Vector3.
  2931. * Please note that this is an in place operation.
  2932. * @returns the current updated Vector3
  2933. */
  2934. Vector3.prototype.normalize = function () {
  2935. var len = this.length();
  2936. if (len === 0 || len === 1.0)
  2937. return this;
  2938. var num = 1.0 / len;
  2939. this.x *= num;
  2940. this.y *= num;
  2941. this.z *= num;
  2942. return this;
  2943. };
  2944. /**
  2945. * Normalize the current Vector3 to a new vector
  2946. * @returns the new Vector3
  2947. */
  2948. Vector3.prototype.normalizeToNew = function () {
  2949. var normalized = new Vector3(0, 0, 0);
  2950. this.normalizeToRef(normalized);
  2951. return normalized;
  2952. };
  2953. /**
  2954. * Normalize the current Vector3 to the reference
  2955. * @param reference define the Vector3 to update
  2956. * @returns the updated Vector3
  2957. */
  2958. Vector3.prototype.normalizeToRef = function (reference) {
  2959. var len = this.length();
  2960. if (len === 0 || len === 1.0) {
  2961. reference.set(this.x, this.y, this.z);
  2962. return reference;
  2963. }
  2964. var scale = 1.0 / len;
  2965. this.scaleToRef(scale, reference);
  2966. return reference;
  2967. };
  2968. /**
  2969. * Creates a new Vector3 copied from the current Vector3
  2970. * @returns the new Vector3
  2971. */
  2972. Vector3.prototype.clone = function () {
  2973. return new Vector3(this.x, this.y, this.z);
  2974. };
  2975. /**
  2976. * Copies the passed vector coordinates to the current Vector3 ones
  2977. * @param source defines the source Vector3
  2978. * @returns the current updated Vector3
  2979. */
  2980. Vector3.prototype.copyFrom = function (source) {
  2981. this.x = source.x;
  2982. this.y = source.y;
  2983. this.z = source.z;
  2984. return this;
  2985. };
  2986. /**
  2987. * Copies the passed floats to the current Vector3 coordinates
  2988. * @param x defines the x coordinate of the operand
  2989. * @param y defines the y coordinate of the operand
  2990. * @param z defines the z coordinate of the operand
  2991. * @returns the current updated Vector3
  2992. */
  2993. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2994. this.x = x;
  2995. this.y = y;
  2996. this.z = z;
  2997. return this;
  2998. };
  2999. /**
  3000. * Copies the passed floats to the current Vector3 coordinates
  3001. * @param x defines the x coordinate of the operand
  3002. * @param y defines the y coordinate of the operand
  3003. * @param z defines the z coordinate of the operand
  3004. * @returns the current updated Vector3
  3005. */
  3006. Vector3.prototype.set = function (x, y, z) {
  3007. return this.copyFromFloats(x, y, z);
  3008. };
  3009. // Statics
  3010. /**
  3011. * Get the clip factor between two vectors
  3012. * @param vector0 defines the first operand
  3013. * @param vector1 defines the second operand
  3014. * @param axis defines the axis to use
  3015. * @param size defines the size along the axis
  3016. * @returns the clip factor
  3017. */
  3018. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3019. var d0 = Vector3.Dot(vector0, axis) - size;
  3020. var d1 = Vector3.Dot(vector1, axis) - size;
  3021. var s = d0 / (d0 - d1);
  3022. return s;
  3023. };
  3024. /**
  3025. * Get angle between two vectors
  3026. * @param vector0 angle between vector0 and vector1
  3027. * @param vector1 angle between vector0 and vector1
  3028. * @param normal direction of the normal
  3029. * @return the angle between vector0 and vector1
  3030. */
  3031. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3032. var v0 = vector0.clone().normalize();
  3033. var v1 = vector1.clone().normalize();
  3034. var dot = Vector3.Dot(v0, v1);
  3035. var n = Vector3.Cross(v0, v1);
  3036. if (Vector3.Dot(n, normal) > 0) {
  3037. return Math.acos(dot);
  3038. }
  3039. return -Math.acos(dot);
  3040. };
  3041. /**
  3042. * Returns a new Vector3 set from the index "offset" of the passed array
  3043. * @param array defines the source array
  3044. * @param offset defines the offset in the source array
  3045. * @returns the new Vector3
  3046. */
  3047. Vector3.FromArray = function (array, offset) {
  3048. if (!offset) {
  3049. offset = 0;
  3050. }
  3051. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3052. };
  3053. /**
  3054. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3055. * This function is deprecated. Use FromArray instead
  3056. * @param array defines the source array
  3057. * @param offset defines the offset in the source array
  3058. * @returns the new Vector3
  3059. */
  3060. Vector3.FromFloatArray = function (array, offset) {
  3061. return Vector3.FromArray(array, offset);
  3062. };
  3063. /**
  3064. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3065. * @param array defines the source array
  3066. * @param offset defines the offset in the source array
  3067. * @param result defines the Vector3 where to store the result
  3068. */
  3069. Vector3.FromArrayToRef = function (array, offset, result) {
  3070. result.x = array[offset];
  3071. result.y = array[offset + 1];
  3072. result.z = array[offset + 2];
  3073. };
  3074. /**
  3075. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3076. * This function is deprecated. Use FromArrayToRef instead.
  3077. * @param array defines the source array
  3078. * @param offset defines the offset in the source array
  3079. * @param result defines the Vector3 where to store the result
  3080. */
  3081. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3082. return Vector3.FromArrayToRef(array, offset, result);
  3083. };
  3084. /**
  3085. * Sets the passed vector "result" with the passed floats.
  3086. * @param x defines the x coordinate of the source
  3087. * @param y defines the y coordinate of the source
  3088. * @param z defines the z coordinate of the source
  3089. * @param result defines the Vector3 where to store the result
  3090. */
  3091. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3092. result.x = x;
  3093. result.y = y;
  3094. result.z = z;
  3095. };
  3096. /**
  3097. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3098. * @returns a new empty Vector3
  3099. */
  3100. Vector3.Zero = function () {
  3101. return new Vector3(0.0, 0.0, 0.0);
  3102. };
  3103. /**
  3104. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3105. * @returns a new unit Vector3
  3106. */
  3107. Vector3.One = function () {
  3108. return new Vector3(1.0, 1.0, 1.0);
  3109. };
  3110. /**
  3111. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3112. * @returns a new up Vector3
  3113. */
  3114. Vector3.Up = function () {
  3115. return new Vector3(0.0, 1.0, 0.0);
  3116. };
  3117. /**
  3118. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3119. * @returns a new forward Vector3
  3120. */
  3121. Vector3.Forward = function () {
  3122. return new Vector3(0.0, 0.0, 1.0);
  3123. };
  3124. /**
  3125. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3126. * @returns a new right Vector3
  3127. */
  3128. Vector3.Right = function () {
  3129. return new Vector3(1.0, 0.0, 0.0);
  3130. };
  3131. /**
  3132. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3133. * @returns a new left Vector3
  3134. */
  3135. Vector3.Left = function () {
  3136. return new Vector3(-1.0, 0.0, 0.0);
  3137. };
  3138. /**
  3139. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3140. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3141. * @param vector defines the Vector3 to transform
  3142. * @param transformation defines the transformation matrix
  3143. * @returns the transformed Vector3
  3144. */
  3145. Vector3.TransformCoordinates = function (vector, transformation) {
  3146. var result = Vector3.Zero();
  3147. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3148. return result;
  3149. };
  3150. /**
  3151. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3152. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3153. * @param vector defines the Vector3 to transform
  3154. * @param transformation defines the transformation matrix
  3155. * @param result defines the Vector3 where to store the result
  3156. */
  3157. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3158. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3159. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3160. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3161. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3162. result.x = x / w;
  3163. result.y = y / w;
  3164. result.z = z / w;
  3165. };
  3166. /**
  3167. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3168. * This method computes tranformed coordinates only, not transformed direction vectors
  3169. * @param x define the x coordinate of the source vector
  3170. * @param y define the y coordinate of the source vector
  3171. * @param z define the z coordinate of the source vector
  3172. * @param transformation defines the transformation matrix
  3173. * @param result defines the Vector3 where to store the result
  3174. */
  3175. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3176. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3177. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3178. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3179. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3180. result.x = rx / rw;
  3181. result.y = ry / rw;
  3182. result.z = rz / rw;
  3183. };
  3184. /**
  3185. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3186. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3187. * @param vector defines the Vector3 to transform
  3188. * @param transformation defines the transformation matrix
  3189. * @returns the new Vector3
  3190. */
  3191. Vector3.TransformNormal = function (vector, transformation) {
  3192. var result = Vector3.Zero();
  3193. Vector3.TransformNormalToRef(vector, transformation, result);
  3194. return result;
  3195. };
  3196. /**
  3197. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3198. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3199. * @param vector defines the Vector3 to transform
  3200. * @param transformation defines the transformation matrix
  3201. * @param result defines the Vector3 where to store the result
  3202. */
  3203. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3204. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3205. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3206. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3207. result.x = x;
  3208. result.y = y;
  3209. result.z = z;
  3210. };
  3211. /**
  3212. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3213. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3214. * @param x define the x coordinate of the source vector
  3215. * @param y define the y coordinate of the source vector
  3216. * @param z define the z coordinate of the source vector
  3217. * @param transformation defines the transformation matrix
  3218. * @param result defines the Vector3 where to store the result
  3219. */
  3220. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3221. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3222. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3223. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3224. };
  3225. /**
  3226. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3227. * @param value1 defines the first control point
  3228. * @param value2 defines the second control point
  3229. * @param value3 defines the third control point
  3230. * @param value4 defines the fourth control point
  3231. * @param amount defines the amount on the spline to use
  3232. * @returns the new Vector3
  3233. */
  3234. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3235. var squared = amount * amount;
  3236. var cubed = amount * squared;
  3237. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3238. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3239. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3240. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3241. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3242. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3243. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3244. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3245. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3246. return new Vector3(x, y, z);
  3247. };
  3248. /**
  3249. * 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"
  3250. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3251. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3252. * @param value defines the current value
  3253. * @param min defines the lower range value
  3254. * @param max defines the upper range value
  3255. * @returns the new Vector3
  3256. */
  3257. Vector3.Clamp = function (value, min, max) {
  3258. var x = value.x;
  3259. x = (x > max.x) ? max.x : x;
  3260. x = (x < min.x) ? min.x : x;
  3261. var y = value.y;
  3262. y = (y > max.y) ? max.y : y;
  3263. y = (y < min.y) ? min.y : y;
  3264. var z = value.z;
  3265. z = (z > max.z) ? max.z : z;
  3266. z = (z < min.z) ? min.z : z;
  3267. return new Vector3(x, y, z);
  3268. };
  3269. /**
  3270. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3271. * @param value1 defines the first control point
  3272. * @param tangent1 defines the first tangent vector
  3273. * @param value2 defines the second control point
  3274. * @param tangent2 defines the second tangent vector
  3275. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3276. * @returns the new Vector3
  3277. */
  3278. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3279. var squared = amount * amount;
  3280. var cubed = amount * squared;
  3281. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3282. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3283. var part3 = (cubed - (2.0 * squared)) + amount;
  3284. var part4 = cubed - squared;
  3285. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3286. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3287. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3288. return new Vector3(x, y, z);
  3289. };
  3290. /**
  3291. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3292. * @param start defines the start value
  3293. * @param end defines the end value
  3294. * @param amount max defines amount between both (between 0 and 1)
  3295. * @returns the new Vector3
  3296. */
  3297. Vector3.Lerp = function (start, end, amount) {
  3298. var result = new Vector3(0, 0, 0);
  3299. Vector3.LerpToRef(start, end, amount, result);
  3300. return result;
  3301. };
  3302. /**
  3303. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3304. * @param start defines the start value
  3305. * @param end defines the end value
  3306. * @param amount max defines amount between both (between 0 and 1)
  3307. * @param result defines the Vector3 where to store the result
  3308. */
  3309. Vector3.LerpToRef = function (start, end, amount, result) {
  3310. result.x = start.x + ((end.x - start.x) * amount);
  3311. result.y = start.y + ((end.y - start.y) * amount);
  3312. result.z = start.z + ((end.z - start.z) * amount);
  3313. };
  3314. /**
  3315. * Returns the dot product (float) between the vectors "left" and "right"
  3316. * @param left defines the left operand
  3317. * @param right defines the right operand
  3318. * @returns the dot product
  3319. */
  3320. Vector3.Dot = function (left, right) {
  3321. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3322. };
  3323. /**
  3324. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3325. * The cross product is then orthogonal to both "left" and "right"
  3326. * @param left defines the left operand
  3327. * @param right defines the right operand
  3328. * @returns the cross product
  3329. */
  3330. Vector3.Cross = function (left, right) {
  3331. var result = Vector3.Zero();
  3332. Vector3.CrossToRef(left, right, result);
  3333. return result;
  3334. };
  3335. /**
  3336. * Sets the passed vector "result" with the cross product of "left" and "right"
  3337. * The cross product is then orthogonal to both "left" and "right"
  3338. * @param left defines the left operand
  3339. * @param right defines the right operand
  3340. * @param result defines the Vector3 where to store the result
  3341. */
  3342. Vector3.CrossToRef = function (left, right, result) {
  3343. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3344. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3345. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3346. result.copyFrom(MathTmp.Vector3[0]);
  3347. };
  3348. /**
  3349. * Returns a new Vector3 as the normalization of the passed vector
  3350. * @param vector defines the Vector3 to normalize
  3351. * @returns the new Vector3
  3352. */
  3353. Vector3.Normalize = function (vector) {
  3354. var result = Vector3.Zero();
  3355. Vector3.NormalizeToRef(vector, result);
  3356. return result;
  3357. };
  3358. /**
  3359. * Sets the passed vector "result" with the normalization of the passed first vector
  3360. * @param vector defines the Vector3 to normalize
  3361. * @param result defines the Vector3 where to store the result
  3362. */
  3363. Vector3.NormalizeToRef = function (vector, result) {
  3364. result.copyFrom(vector);
  3365. result.normalize();
  3366. };
  3367. /**
  3368. * Project a Vector3 onto screen space
  3369. * @param vector defines the Vector3 to project
  3370. * @param world defines the world matrix to use
  3371. * @param transform defines the transform (view x projection) matrix to use
  3372. * @param viewport defines the screen viewport to use
  3373. * @returns the new Vector3
  3374. */
  3375. Vector3.Project = function (vector, world, transform, viewport) {
  3376. var cw = viewport.width;
  3377. var ch = viewport.height;
  3378. var cx = viewport.x;
  3379. var cy = viewport.y;
  3380. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3381. 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);
  3382. var matrix = MathTmp.Matrix[0];
  3383. world.multiplyToRef(transform, matrix);
  3384. matrix.multiplyToRef(viewportMatrix, matrix);
  3385. return Vector3.TransformCoordinates(vector, matrix);
  3386. };
  3387. /**
  3388. * Unproject from screen space to object space
  3389. * @param source defines the screen space Vector3 to use
  3390. * @param viewportWidth defines the current width of the viewport
  3391. * @param viewportHeight defines the current height of the viewport
  3392. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3393. * @param transform defines the transform (view x projection) matrix to use
  3394. * @returns the new Vector3
  3395. */
  3396. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3397. var matrix = MathTmp.Matrix[0];
  3398. world.multiplyToRef(transform, matrix);
  3399. matrix.invert();
  3400. source.x = source.x / viewportWidth * 2 - 1;
  3401. source.y = -(source.y / viewportHeight * 2 - 1);
  3402. var vector = Vector3.TransformCoordinates(source, matrix);
  3403. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3404. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3405. vector = vector.scale(1.0 / num);
  3406. }
  3407. return vector;
  3408. };
  3409. /**
  3410. * Unproject from screen space to object space
  3411. * @param source defines the screen space Vector3 to use
  3412. * @param viewportWidth defines the current width of the viewport
  3413. * @param viewportHeight defines the current height of the viewport
  3414. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3415. * @param view defines the view matrix to use
  3416. * @param projection defines the projection matrix to use
  3417. * @returns the new Vector3
  3418. */
  3419. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3420. var result = Vector3.Zero();
  3421. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3422. return result;
  3423. };
  3424. /**
  3425. * Unproject from screen space to object space
  3426. * @param source defines the screen space Vector3 to use
  3427. * @param viewportWidth defines the current width of the viewport
  3428. * @param viewportHeight defines the current height of the viewport
  3429. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3430. * @param view defines the view matrix to use
  3431. * @param projection defines the projection matrix to use
  3432. * @param result defines the Vector3 where to store the result
  3433. */
  3434. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3435. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3436. };
  3437. /**
  3438. * Unproject from screen space to object space
  3439. * @param sourceX defines the screen space x coordinate to use
  3440. * @param sourceY defines the screen space y coordinate to use
  3441. * @param sourceZ defines the screen space z coordinate to use
  3442. * @param viewportWidth defines the current width of the viewport
  3443. * @param viewportHeight defines the current height of the viewport
  3444. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3445. * @param view defines the view matrix to use
  3446. * @param projection defines the projection matrix to use
  3447. * @param result defines the Vector3 where to store the result
  3448. */
  3449. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3450. var matrix = MathTmp.Matrix[0];
  3451. world.multiplyToRef(view, matrix);
  3452. matrix.multiplyToRef(projection, matrix);
  3453. matrix.invert();
  3454. var screenSource = MathTmp.Vector3[0];
  3455. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3456. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3457. screenSource.z = 2 * sourceZ - 1.0;
  3458. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3459. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3460. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3461. result.scaleInPlace(1.0 / num);
  3462. }
  3463. };
  3464. /**
  3465. * Gets the minimal coordinate values between two Vector3
  3466. * @param left defines the first operand
  3467. * @param right defines the second operand
  3468. * @returns the new Vector3
  3469. */
  3470. Vector3.Minimize = function (left, right) {
  3471. var min = left.clone();
  3472. min.minimizeInPlace(right);
  3473. return min;
  3474. };
  3475. /**
  3476. * Gets the maximal coordinate values between two Vector3
  3477. * @param left defines the first operand
  3478. * @param right defines the second operand
  3479. * @returns the new Vector3
  3480. */
  3481. Vector3.Maximize = function (left, right) {
  3482. var max = left.clone();
  3483. max.maximizeInPlace(right);
  3484. return max;
  3485. };
  3486. /**
  3487. * Returns the distance between the vectors "value1" and "value2"
  3488. * @param value1 defines the first operand
  3489. * @param value2 defines the second operand
  3490. * @returns the distance
  3491. */
  3492. Vector3.Distance = function (value1, value2) {
  3493. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3494. };
  3495. /**
  3496. * Returns the squared distance between the vectors "value1" and "value2"
  3497. * @param value1 defines the first operand
  3498. * @param value2 defines the second operand
  3499. * @returns the squared distance
  3500. */
  3501. Vector3.DistanceSquared = function (value1, value2) {
  3502. var x = value1.x - value2.x;
  3503. var y = value1.y - value2.y;
  3504. var z = value1.z - value2.z;
  3505. return (x * x) + (y * y) + (z * z);
  3506. };
  3507. /**
  3508. * Returns a new Vector3 located at the center between "value1" and "value2"
  3509. * @param value1 defines the first operand
  3510. * @param value2 defines the second operand
  3511. * @returns the new Vector3
  3512. */
  3513. Vector3.Center = function (value1, value2) {
  3514. var center = value1.add(value2);
  3515. center.scaleInPlace(0.5);
  3516. return center;
  3517. };
  3518. /**
  3519. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3520. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3521. * to something in order to rotate it from its local system to the given target system
  3522. * Note: axis1, axis2 and axis3 are normalized during this operation
  3523. * @param axis1 defines the first axis
  3524. * @param axis2 defines the second axis
  3525. * @param axis3 defines the third axis
  3526. * @returns a new Vector3
  3527. */
  3528. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3529. var rotation = Vector3.Zero();
  3530. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3531. return rotation;
  3532. };
  3533. /**
  3534. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3535. * @param axis1 defines the first axis
  3536. * @param axis2 defines the second axis
  3537. * @param axis3 defines the third axis
  3538. * @param ref defines the Vector3 where to store the result
  3539. */
  3540. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3541. var quat = MathTmp.Quaternion[0];
  3542. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3543. quat.toEulerAnglesToRef(ref);
  3544. };
  3545. return Vector3;
  3546. }());
  3547. BABYLON.Vector3 = Vector3;
  3548. //Vector4 class created for EulerAngle class conversion to Quaternion
  3549. var Vector4 = /** @class */ (function () {
  3550. /**
  3551. * Creates a Vector4 object from the passed floats.
  3552. */
  3553. function Vector4(x, y, z, w) {
  3554. this.x = x;
  3555. this.y = y;
  3556. this.z = z;
  3557. this.w = w;
  3558. }
  3559. /**
  3560. * Returns the string with the Vector4 coordinates.
  3561. */
  3562. Vector4.prototype.toString = function () {
  3563. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3564. };
  3565. /**
  3566. * Returns the string "Vector4".
  3567. */
  3568. Vector4.prototype.getClassName = function () {
  3569. return "Vector4";
  3570. };
  3571. /**
  3572. * Returns the Vector4 hash code.
  3573. */
  3574. Vector4.prototype.getHashCode = function () {
  3575. var hash = this.x || 0;
  3576. hash = (hash * 397) ^ (this.y || 0);
  3577. hash = (hash * 397) ^ (this.z || 0);
  3578. hash = (hash * 397) ^ (this.w || 0);
  3579. return hash;
  3580. };
  3581. // Operators
  3582. /**
  3583. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3584. */
  3585. Vector4.prototype.asArray = function () {
  3586. var result = new Array();
  3587. this.toArray(result, 0);
  3588. return result;
  3589. };
  3590. /**
  3591. * Populates the passed array from the passed index with the Vector4 coordinates.
  3592. * Returns the Vector4.
  3593. */
  3594. Vector4.prototype.toArray = function (array, index) {
  3595. if (index === undefined) {
  3596. index = 0;
  3597. }
  3598. array[index] = this.x;
  3599. array[index + 1] = this.y;
  3600. array[index + 2] = this.z;
  3601. array[index + 3] = this.w;
  3602. return this;
  3603. };
  3604. /**
  3605. * Adds the passed vector to the current Vector4.
  3606. * Returns the updated Vector4.
  3607. */
  3608. Vector4.prototype.addInPlace = function (otherVector) {
  3609. this.x += otherVector.x;
  3610. this.y += otherVector.y;
  3611. this.z += otherVector.z;
  3612. this.w += otherVector.w;
  3613. return this;
  3614. };
  3615. /**
  3616. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3617. */
  3618. Vector4.prototype.add = function (otherVector) {
  3619. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3620. };
  3621. /**
  3622. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3623. * Returns the current Vector4.
  3624. */
  3625. Vector4.prototype.addToRef = function (otherVector, result) {
  3626. result.x = this.x + otherVector.x;
  3627. result.y = this.y + otherVector.y;
  3628. result.z = this.z + otherVector.z;
  3629. result.w = this.w + otherVector.w;
  3630. return this;
  3631. };
  3632. /**
  3633. * Subtract in place the passed vector from the current Vector4.
  3634. * Returns the updated Vector4.
  3635. */
  3636. Vector4.prototype.subtractInPlace = function (otherVector) {
  3637. this.x -= otherVector.x;
  3638. this.y -= otherVector.y;
  3639. this.z -= otherVector.z;
  3640. this.w -= otherVector.w;
  3641. return this;
  3642. };
  3643. /**
  3644. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3645. */
  3646. Vector4.prototype.subtract = function (otherVector) {
  3647. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3648. };
  3649. /**
  3650. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3651. * Returns the current Vector4.
  3652. */
  3653. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3654. result.x = this.x - otherVector.x;
  3655. result.y = this.y - otherVector.y;
  3656. result.z = this.z - otherVector.z;
  3657. result.w = this.w - otherVector.w;
  3658. return this;
  3659. };
  3660. /**
  3661. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3662. */
  3663. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3664. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3665. };
  3666. /**
  3667. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3668. * Returns the current Vector4.
  3669. */
  3670. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3671. result.x = this.x - x;
  3672. result.y = this.y - y;
  3673. result.z = this.z - z;
  3674. result.w = this.w - w;
  3675. return this;
  3676. };
  3677. /**
  3678. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3679. */
  3680. Vector4.prototype.negate = function () {
  3681. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3682. };
  3683. /**
  3684. * Multiplies the current Vector4 coordinates by scale (float).
  3685. * Returns the updated Vector4.
  3686. */
  3687. Vector4.prototype.scaleInPlace = function (scale) {
  3688. this.x *= scale;
  3689. this.y *= scale;
  3690. this.z *= scale;
  3691. this.w *= scale;
  3692. return this;
  3693. };
  3694. /**
  3695. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3696. */
  3697. Vector4.prototype.scale = function (scale) {
  3698. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3699. };
  3700. /**
  3701. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3702. * Returns the current Vector4.
  3703. */
  3704. Vector4.prototype.scaleToRef = function (scale, result) {
  3705. result.x = this.x * scale;
  3706. result.y = this.y * scale;
  3707. result.z = this.z * scale;
  3708. result.w = this.w * scale;
  3709. return this;
  3710. };
  3711. /**
  3712. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3713. */
  3714. Vector4.prototype.equals = function (otherVector) {
  3715. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3716. };
  3717. /**
  3718. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3719. */
  3720. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3721. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3722. return otherVector
  3723. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3724. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3725. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3726. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3727. };
  3728. /**
  3729. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3730. */
  3731. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3732. return this.x === x && this.y === y && this.z === z && this.w === w;
  3733. };
  3734. /**
  3735. * Multiplies in place the current Vector4 by the passed one.
  3736. * Returns the updated Vector4.
  3737. */
  3738. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3739. this.x *= otherVector.x;
  3740. this.y *= otherVector.y;
  3741. this.z *= otherVector.z;
  3742. this.w *= otherVector.w;
  3743. return this;
  3744. };
  3745. /**
  3746. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3747. */
  3748. Vector4.prototype.multiply = function (otherVector) {
  3749. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3750. };
  3751. /**
  3752. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3753. * Returns the current Vector4.
  3754. */
  3755. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3756. result.x = this.x * otherVector.x;
  3757. result.y = this.y * otherVector.y;
  3758. result.z = this.z * otherVector.z;
  3759. result.w = this.w * otherVector.w;
  3760. return this;
  3761. };
  3762. /**
  3763. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3764. */
  3765. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3766. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3767. };
  3768. /**
  3769. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3770. */
  3771. Vector4.prototype.divide = function (otherVector) {
  3772. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3773. };
  3774. /**
  3775. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3776. * Returns the current Vector4.
  3777. */
  3778. Vector4.prototype.divideToRef = function (otherVector, result) {
  3779. result.x = this.x / otherVector.x;
  3780. result.y = this.y / otherVector.y;
  3781. result.z = this.z / otherVector.z;
  3782. result.w = this.w / otherVector.w;
  3783. return this;
  3784. };
  3785. /**
  3786. * Divides the current Vector3 coordinates by the passed ones.
  3787. * @returns the updated Vector3.
  3788. */
  3789. Vector4.prototype.divideInPlace = function (otherVector) {
  3790. return this.divideToRef(otherVector, this);
  3791. };
  3792. /**
  3793. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3794. * @param other defines the second operand
  3795. * @returns the current updated Vector4
  3796. */
  3797. Vector4.prototype.minimizeInPlace = function (other) {
  3798. if (other.x < this.x)
  3799. this.x = other.x;
  3800. if (other.y < this.y)
  3801. this.y = other.y;
  3802. if (other.z < this.z)
  3803. this.z = other.z;
  3804. if (other.w < this.w)
  3805. this.w = other.w;
  3806. return this;
  3807. };
  3808. /**
  3809. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3810. * @param other defines the second operand
  3811. * @returns the current updated Vector4
  3812. */
  3813. Vector4.prototype.maximizeInPlace = function (other) {
  3814. if (other.x > this.x)
  3815. this.x = other.x;
  3816. if (other.y > this.y)
  3817. this.y = other.y;
  3818. if (other.z > this.z)
  3819. this.z = other.z;
  3820. if (other.w > this.w)
  3821. this.w = other.w;
  3822. return this;
  3823. };
  3824. // Properties
  3825. /**
  3826. * Returns the Vector4 length (float).
  3827. */
  3828. Vector4.prototype.length = function () {
  3829. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3830. };
  3831. /**
  3832. * Returns the Vector4 squared length (float).
  3833. */
  3834. Vector4.prototype.lengthSquared = function () {
  3835. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3836. };
  3837. // Methods
  3838. /**
  3839. * Normalizes in place the Vector4.
  3840. * Returns the updated Vector4.
  3841. */
  3842. Vector4.prototype.normalize = function () {
  3843. var len = this.length();
  3844. if (len === 0)
  3845. return this;
  3846. var num = 1.0 / len;
  3847. this.x *= num;
  3848. this.y *= num;
  3849. this.z *= num;
  3850. this.w *= num;
  3851. return this;
  3852. };
  3853. /**
  3854. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3855. */
  3856. Vector4.prototype.toVector3 = function () {
  3857. return new Vector3(this.x, this.y, this.z);
  3858. };
  3859. /**
  3860. * Returns a new Vector4 copied from the current one.
  3861. */
  3862. Vector4.prototype.clone = function () {
  3863. return new Vector4(this.x, this.y, this.z, this.w);
  3864. };
  3865. /**
  3866. * Updates the current Vector4 with the passed one coordinates.
  3867. * Returns the updated Vector4.
  3868. */
  3869. Vector4.prototype.copyFrom = function (source) {
  3870. this.x = source.x;
  3871. this.y = source.y;
  3872. this.z = source.z;
  3873. this.w = source.w;
  3874. return this;
  3875. };
  3876. /**
  3877. * Updates the current Vector4 coordinates with the passed floats.
  3878. * Returns the updated Vector4.
  3879. */
  3880. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3881. this.x = x;
  3882. this.y = y;
  3883. this.z = z;
  3884. this.w = w;
  3885. return this;
  3886. };
  3887. /**
  3888. * Updates the current Vector4 coordinates with the passed floats.
  3889. * Returns the updated Vector4.
  3890. */
  3891. Vector4.prototype.set = function (x, y, z, w) {
  3892. return this.copyFromFloats(x, y, z, w);
  3893. };
  3894. // Statics
  3895. /**
  3896. * Returns a new Vector4 set from the starting index of the passed array.
  3897. */
  3898. Vector4.FromArray = function (array, offset) {
  3899. if (!offset) {
  3900. offset = 0;
  3901. }
  3902. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3903. };
  3904. /**
  3905. * Updates the passed vector "result" from the starting index of the passed array.
  3906. */
  3907. Vector4.FromArrayToRef = function (array, offset, result) {
  3908. result.x = array[offset];
  3909. result.y = array[offset + 1];
  3910. result.z = array[offset + 2];
  3911. result.w = array[offset + 3];
  3912. };
  3913. /**
  3914. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3915. */
  3916. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3917. Vector4.FromArrayToRef(array, offset, result);
  3918. };
  3919. /**
  3920. * Updates the passed vector "result" coordinates from the passed floats.
  3921. */
  3922. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3923. result.x = x;
  3924. result.y = y;
  3925. result.z = z;
  3926. result.w = w;
  3927. };
  3928. /**
  3929. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3930. */
  3931. Vector4.Zero = function () {
  3932. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3933. };
  3934. /**
  3935. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3936. */
  3937. Vector4.One = function () {
  3938. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3939. };
  3940. /**
  3941. * Returns a new normalized Vector4 from the passed one.
  3942. */
  3943. Vector4.Normalize = function (vector) {
  3944. var result = Vector4.Zero();
  3945. Vector4.NormalizeToRef(vector, result);
  3946. return result;
  3947. };
  3948. /**
  3949. * Updates the passed vector "result" from the normalization of the passed one.
  3950. */
  3951. Vector4.NormalizeToRef = function (vector, result) {
  3952. result.copyFrom(vector);
  3953. result.normalize();
  3954. };
  3955. Vector4.Minimize = function (left, right) {
  3956. var min = left.clone();
  3957. min.minimizeInPlace(right);
  3958. return min;
  3959. };
  3960. Vector4.Maximize = function (left, right) {
  3961. var max = left.clone();
  3962. max.maximizeInPlace(right);
  3963. return max;
  3964. };
  3965. /**
  3966. * Returns the distance (float) between the vectors "value1" and "value2".
  3967. */
  3968. Vector4.Distance = function (value1, value2) {
  3969. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3970. };
  3971. /**
  3972. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3973. */
  3974. Vector4.DistanceSquared = function (value1, value2) {
  3975. var x = value1.x - value2.x;
  3976. var y = value1.y - value2.y;
  3977. var z = value1.z - value2.z;
  3978. var w = value1.w - value2.w;
  3979. return (x * x) + (y * y) + (z * z) + (w * w);
  3980. };
  3981. /**
  3982. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3983. */
  3984. Vector4.Center = function (value1, value2) {
  3985. var center = value1.add(value2);
  3986. center.scaleInPlace(0.5);
  3987. return center;
  3988. };
  3989. /**
  3990. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3991. * This methods computes transformed normalized direction vectors only.
  3992. */
  3993. Vector4.TransformNormal = function (vector, transformation) {
  3994. var result = Vector4.Zero();
  3995. Vector4.TransformNormalToRef(vector, transformation, result);
  3996. return result;
  3997. };
  3998. /**
  3999. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4000. * This methods computes transformed normalized direction vectors only.
  4001. */
  4002. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4003. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4004. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4005. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4006. result.x = x;
  4007. result.y = y;
  4008. result.z = z;
  4009. result.w = vector.w;
  4010. };
  4011. /**
  4012. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4013. * This methods computes transformed normalized direction vectors only.
  4014. */
  4015. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4016. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4017. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4018. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4019. result.w = w;
  4020. };
  4021. return Vector4;
  4022. }());
  4023. BABYLON.Vector4 = Vector4;
  4024. var Size = /** @class */ (function () {
  4025. /**
  4026. * Creates a Size object from the passed width and height (floats).
  4027. */
  4028. function Size(width, height) {
  4029. this.width = width;
  4030. this.height = height;
  4031. }
  4032. // Returns a string with the Size width and height.
  4033. Size.prototype.toString = function () {
  4034. return "{W: " + this.width + ", H: " + this.height + "}";
  4035. };
  4036. /**
  4037. * Returns the string "Size"
  4038. */
  4039. Size.prototype.getClassName = function () {
  4040. return "Size";
  4041. };
  4042. /**
  4043. * Returns the Size hash code.
  4044. */
  4045. Size.prototype.getHashCode = function () {
  4046. var hash = this.width || 0;
  4047. hash = (hash * 397) ^ (this.height || 0);
  4048. return hash;
  4049. };
  4050. /**
  4051. * Updates the current size from the passed one.
  4052. * Returns the updated Size.
  4053. */
  4054. Size.prototype.copyFrom = function (src) {
  4055. this.width = src.width;
  4056. this.height = src.height;
  4057. };
  4058. /**
  4059. * Updates in place the current Size from the passed floats.
  4060. * Returns the updated Size.
  4061. */
  4062. Size.prototype.copyFromFloats = function (width, height) {
  4063. this.width = width;
  4064. this.height = height;
  4065. return this;
  4066. };
  4067. /**
  4068. * Updates in place the current Size from the passed floats.
  4069. * Returns the updated Size.
  4070. */
  4071. Size.prototype.set = function (width, height) {
  4072. return this.copyFromFloats(width, height);
  4073. };
  4074. /**
  4075. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4076. */
  4077. Size.prototype.multiplyByFloats = function (w, h) {
  4078. return new Size(this.width * w, this.height * h);
  4079. };
  4080. /**
  4081. * Returns a new Size copied from the passed one.
  4082. */
  4083. Size.prototype.clone = function () {
  4084. return new Size(this.width, this.height);
  4085. };
  4086. /**
  4087. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4088. */
  4089. Size.prototype.equals = function (other) {
  4090. if (!other) {
  4091. return false;
  4092. }
  4093. return (this.width === other.width) && (this.height === other.height);
  4094. };
  4095. Object.defineProperty(Size.prototype, "surface", {
  4096. /**
  4097. * Returns the surface of the Size : width * height (float).
  4098. */
  4099. get: function () {
  4100. return this.width * this.height;
  4101. },
  4102. enumerable: true,
  4103. configurable: true
  4104. });
  4105. /**
  4106. * Returns a new Size set to (0.0, 0.0)
  4107. */
  4108. Size.Zero = function () {
  4109. return new Size(0.0, 0.0);
  4110. };
  4111. /**
  4112. * Returns a new Size set as the addition result of the current Size and the passed one.
  4113. */
  4114. Size.prototype.add = function (otherSize) {
  4115. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4116. return r;
  4117. };
  4118. /**
  4119. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4120. */
  4121. Size.prototype.subtract = function (otherSize) {
  4122. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4123. return r;
  4124. };
  4125. /**
  4126. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4127. */
  4128. Size.Lerp = function (start, end, amount) {
  4129. var w = start.width + ((end.width - start.width) * amount);
  4130. var h = start.height + ((end.height - start.height) * amount);
  4131. return new Size(w, h);
  4132. };
  4133. return Size;
  4134. }());
  4135. BABYLON.Size = Size;
  4136. var Quaternion = /** @class */ (function () {
  4137. /**
  4138. * Creates a new Quaternion from the passed floats.
  4139. */
  4140. function Quaternion(x, y, z, w) {
  4141. if (x === void 0) { x = 0.0; }
  4142. if (y === void 0) { y = 0.0; }
  4143. if (z === void 0) { z = 0.0; }
  4144. if (w === void 0) { w = 1.0; }
  4145. this.x = x;
  4146. this.y = y;
  4147. this.z = z;
  4148. this.w = w;
  4149. }
  4150. /**
  4151. * Returns a string with the Quaternion coordinates.
  4152. */
  4153. Quaternion.prototype.toString = function () {
  4154. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4155. };
  4156. /**
  4157. * Returns the string "Quaternion".
  4158. */
  4159. Quaternion.prototype.getClassName = function () {
  4160. return "Quaternion";
  4161. };
  4162. /**
  4163. * Returns the Quaternion hash code.
  4164. */
  4165. Quaternion.prototype.getHashCode = function () {
  4166. var hash = this.x || 0;
  4167. hash = (hash * 397) ^ (this.y || 0);
  4168. hash = (hash * 397) ^ (this.z || 0);
  4169. hash = (hash * 397) ^ (this.w || 0);
  4170. return hash;
  4171. };
  4172. /**
  4173. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4174. */
  4175. Quaternion.prototype.asArray = function () {
  4176. return [this.x, this.y, this.z, this.w];
  4177. };
  4178. /**
  4179. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4180. */
  4181. Quaternion.prototype.equals = function (otherQuaternion) {
  4182. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4183. };
  4184. /**
  4185. * Returns a new Quaternion copied from the current one.
  4186. */
  4187. Quaternion.prototype.clone = function () {
  4188. return new Quaternion(this.x, this.y, this.z, this.w);
  4189. };
  4190. /**
  4191. * Updates the current Quaternion from the passed one coordinates.
  4192. * Returns the updated Quaterion.
  4193. */
  4194. Quaternion.prototype.copyFrom = function (other) {
  4195. this.x = other.x;
  4196. this.y = other.y;
  4197. this.z = other.z;
  4198. this.w = other.w;
  4199. return this;
  4200. };
  4201. /**
  4202. * Updates the current Quaternion from the passed float coordinates.
  4203. * Returns the updated Quaterion.
  4204. */
  4205. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4206. this.x = x;
  4207. this.y = y;
  4208. this.z = z;
  4209. this.w = w;
  4210. return this;
  4211. };
  4212. /**
  4213. * Updates the current Quaternion from the passed float coordinates.
  4214. * Returns the updated Quaterion.
  4215. */
  4216. Quaternion.prototype.set = function (x, y, z, w) {
  4217. return this.copyFromFloats(x, y, z, w);
  4218. };
  4219. /**
  4220. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4221. */
  4222. Quaternion.prototype.add = function (other) {
  4223. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4224. };
  4225. /**
  4226. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4227. */
  4228. Quaternion.prototype.subtract = function (other) {
  4229. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4230. };
  4231. /**
  4232. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4233. */
  4234. Quaternion.prototype.scale = function (value) {
  4235. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4236. };
  4237. /**
  4238. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4239. */
  4240. Quaternion.prototype.multiply = function (q1) {
  4241. var result = new Quaternion(0, 0, 0, 1.0);
  4242. this.multiplyToRef(q1, result);
  4243. return result;
  4244. };
  4245. /**
  4246. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4247. * Returns the current Quaternion.
  4248. */
  4249. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4250. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4251. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4252. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4253. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4254. result.copyFromFloats(x, y, z, w);
  4255. return this;
  4256. };
  4257. /**
  4258. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4259. * Returns the updated Quaternion.
  4260. */
  4261. Quaternion.prototype.multiplyInPlace = function (q1) {
  4262. this.multiplyToRef(q1, this);
  4263. return this;
  4264. };
  4265. /**
  4266. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4267. * Returns the current Quaternion.
  4268. */
  4269. Quaternion.prototype.conjugateToRef = function (ref) {
  4270. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4271. return this;
  4272. };
  4273. /**
  4274. * Conjugates in place the current Quaternion.
  4275. * Returns the updated Quaternion.
  4276. */
  4277. Quaternion.prototype.conjugateInPlace = function () {
  4278. this.x *= -1;
  4279. this.y *= -1;
  4280. this.z *= -1;
  4281. return this;
  4282. };
  4283. /**
  4284. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4285. */
  4286. Quaternion.prototype.conjugate = function () {
  4287. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4288. return result;
  4289. };
  4290. /**
  4291. * Returns the Quaternion length (float).
  4292. */
  4293. Quaternion.prototype.length = function () {
  4294. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4295. };
  4296. /**
  4297. * Normalize in place the current Quaternion.
  4298. * Returns the updated Quaternion.
  4299. */
  4300. Quaternion.prototype.normalize = function () {
  4301. var length = 1.0 / this.length();
  4302. this.x *= length;
  4303. this.y *= length;
  4304. this.z *= length;
  4305. this.w *= length;
  4306. return this;
  4307. };
  4308. /**
  4309. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4310. */
  4311. Quaternion.prototype.toEulerAngles = function (order) {
  4312. if (order === void 0) { order = "YZX"; }
  4313. var result = Vector3.Zero();
  4314. this.toEulerAnglesToRef(result, order);
  4315. return result;
  4316. };
  4317. /**
  4318. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4319. * Returns the current Quaternion.
  4320. */
  4321. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4322. if (order === void 0) { order = "YZX"; }
  4323. var qz = this.z;
  4324. var qx = this.x;
  4325. var qy = this.y;
  4326. var qw = this.w;
  4327. var sqw = qw * qw;
  4328. var sqz = qz * qz;
  4329. var sqx = qx * qx;
  4330. var sqy = qy * qy;
  4331. var zAxisY = qy * qz - qx * qw;
  4332. var limit = .4999999;
  4333. if (zAxisY < -limit) {
  4334. result.y = 2 * Math.atan2(qy, qw);
  4335. result.x = Math.PI / 2;
  4336. result.z = 0;
  4337. }
  4338. else if (zAxisY > limit) {
  4339. result.y = 2 * Math.atan2(qy, qw);
  4340. result.x = -Math.PI / 2;
  4341. result.z = 0;
  4342. }
  4343. else {
  4344. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4345. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4346. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4347. }
  4348. return this;
  4349. };
  4350. /**
  4351. * Updates the passed rotation matrix with the current Quaternion values.
  4352. * Returns the current Quaternion.
  4353. */
  4354. Quaternion.prototype.toRotationMatrix = function (result) {
  4355. var xx = this.x * this.x;
  4356. var yy = this.y * this.y;
  4357. var zz = this.z * this.z;
  4358. var xy = this.x * this.y;
  4359. var zw = this.z * this.w;
  4360. var zx = this.z * this.x;
  4361. var yw = this.y * this.w;
  4362. var yz = this.y * this.z;
  4363. var xw = this.x * this.w;
  4364. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4365. result.m[1] = 2.0 * (xy + zw);
  4366. result.m[2] = 2.0 * (zx - yw);
  4367. result.m[3] = 0;
  4368. result.m[4] = 2.0 * (xy - zw);
  4369. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4370. result.m[6] = 2.0 * (yz + xw);
  4371. result.m[7] = 0;
  4372. result.m[8] = 2.0 * (zx + yw);
  4373. result.m[9] = 2.0 * (yz - xw);
  4374. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4375. result.m[11] = 0;
  4376. result.m[12] = 0;
  4377. result.m[13] = 0;
  4378. result.m[14] = 0;
  4379. result.m[15] = 1.0;
  4380. result._markAsUpdated();
  4381. return this;
  4382. };
  4383. /**
  4384. * Updates the current Quaternion from the passed rotation matrix values.
  4385. * Returns the updated Quaternion.
  4386. */
  4387. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4388. Quaternion.FromRotationMatrixToRef(matrix, this);
  4389. return this;
  4390. };
  4391. // Statics
  4392. /**
  4393. * Returns a new Quaternion set from the passed rotation matrix values.
  4394. */
  4395. Quaternion.FromRotationMatrix = function (matrix) {
  4396. var result = new Quaternion();
  4397. Quaternion.FromRotationMatrixToRef(matrix, result);
  4398. return result;
  4399. };
  4400. /**
  4401. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4402. */
  4403. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4404. var data = matrix.m;
  4405. var m11 = data[0], m12 = data[4], m13 = data[8];
  4406. var m21 = data[1], m22 = data[5], m23 = data[9];
  4407. var m31 = data[2], m32 = data[6], m33 = data[10];
  4408. var trace = m11 + m22 + m33;
  4409. var s;
  4410. if (trace > 0) {
  4411. s = 0.5 / Math.sqrt(trace + 1.0);
  4412. result.w = 0.25 / s;
  4413. result.x = (m32 - m23) * s;
  4414. result.y = (m13 - m31) * s;
  4415. result.z = (m21 - m12) * s;
  4416. }
  4417. else if (m11 > m22 && m11 > m33) {
  4418. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4419. result.w = (m32 - m23) / s;
  4420. result.x = 0.25 * s;
  4421. result.y = (m12 + m21) / s;
  4422. result.z = (m13 + m31) / s;
  4423. }
  4424. else if (m22 > m33) {
  4425. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4426. result.w = (m13 - m31) / s;
  4427. result.x = (m12 + m21) / s;
  4428. result.y = 0.25 * s;
  4429. result.z = (m23 + m32) / s;
  4430. }
  4431. else {
  4432. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4433. result.w = (m21 - m12) / s;
  4434. result.x = (m13 + m31) / s;
  4435. result.y = (m23 + m32) / s;
  4436. result.z = 0.25 * s;
  4437. }
  4438. };
  4439. /**
  4440. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4441. */
  4442. Quaternion.Zero = function () {
  4443. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4444. };
  4445. /**
  4446. * Returns a new Quaternion as the inverted current Quaternion.
  4447. */
  4448. Quaternion.Inverse = function (q) {
  4449. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4450. };
  4451. /**
  4452. * Returns the identity Quaternion.
  4453. */
  4454. Quaternion.Identity = function () {
  4455. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4456. };
  4457. Quaternion.IsIdentity = function (quaternion) {
  4458. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4459. };
  4460. /**
  4461. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4462. */
  4463. Quaternion.RotationAxis = function (axis, angle) {
  4464. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4465. };
  4466. /**
  4467. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4468. */
  4469. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4470. var sin = Math.sin(angle / 2);
  4471. axis.normalize();
  4472. result.w = Math.cos(angle / 2);
  4473. result.x = axis.x * sin;
  4474. result.y = axis.y * sin;
  4475. result.z = axis.z * sin;
  4476. return result;
  4477. };
  4478. /**
  4479. * Retuns a new Quaternion set from the starting index of the passed array.
  4480. */
  4481. Quaternion.FromArray = function (array, offset) {
  4482. if (!offset) {
  4483. offset = 0;
  4484. }
  4485. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4486. };
  4487. /**
  4488. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4489. */
  4490. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4491. var q = new Quaternion();
  4492. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4493. return q;
  4494. };
  4495. /**
  4496. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4497. */
  4498. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4499. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4500. var halfRoll = roll * 0.5;
  4501. var halfPitch = pitch * 0.5;
  4502. var halfYaw = yaw * 0.5;
  4503. var sinRoll = Math.sin(halfRoll);
  4504. var cosRoll = Math.cos(halfRoll);
  4505. var sinPitch = Math.sin(halfPitch);
  4506. var cosPitch = Math.cos(halfPitch);
  4507. var sinYaw = Math.sin(halfYaw);
  4508. var cosYaw = Math.cos(halfYaw);
  4509. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4510. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4511. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4512. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4513. };
  4514. /**
  4515. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4516. */
  4517. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4518. var result = new Quaternion();
  4519. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4520. return result;
  4521. };
  4522. /**
  4523. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4524. */
  4525. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4526. // Produces a quaternion from Euler angles in the z-x-z orientation
  4527. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4528. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4529. var halfBeta = beta * 0.5;
  4530. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4531. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4532. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4533. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4534. };
  4535. /**
  4536. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4537. * cf to Vector3.RotationFromAxis() documentation.
  4538. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4539. */
  4540. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4541. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4542. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4543. return quat;
  4544. };
  4545. /**
  4546. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4547. * cf to Vector3.RotationFromAxis() documentation.
  4548. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4549. */
  4550. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4551. var rotMat = MathTmp.Matrix[0];
  4552. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4553. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4554. };
  4555. Quaternion.Slerp = function (left, right, amount) {
  4556. var result = Quaternion.Identity();
  4557. Quaternion.SlerpToRef(left, right, amount, result);
  4558. return result;
  4559. };
  4560. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4561. var num2;
  4562. var num3;
  4563. var num = amount;
  4564. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4565. var flag = false;
  4566. if (num4 < 0) {
  4567. flag = true;
  4568. num4 = -num4;
  4569. }
  4570. if (num4 > 0.999999) {
  4571. num3 = 1 - num;
  4572. num2 = flag ? -num : num;
  4573. }
  4574. else {
  4575. var num5 = Math.acos(num4);
  4576. var num6 = (1.0 / Math.sin(num5));
  4577. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4578. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4579. }
  4580. result.x = (num3 * left.x) + (num2 * right.x);
  4581. result.y = (num3 * left.y) + (num2 * right.y);
  4582. result.z = (num3 * left.z) + (num2 * right.z);
  4583. result.w = (num3 * left.w) + (num2 * right.w);
  4584. };
  4585. /**
  4586. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4587. */
  4588. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4589. var squared = amount * amount;
  4590. var cubed = amount * squared;
  4591. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4592. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4593. var part3 = (cubed - (2.0 * squared)) + amount;
  4594. var part4 = cubed - squared;
  4595. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4596. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4597. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4598. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4599. return new Quaternion(x, y, z, w);
  4600. };
  4601. return Quaternion;
  4602. }());
  4603. BABYLON.Quaternion = Quaternion;
  4604. var Matrix = /** @class */ (function () {
  4605. function Matrix() {
  4606. this._isIdentity = false;
  4607. this._isIdentityDirty = true;
  4608. this.m = new Float32Array(16);
  4609. this._markAsUpdated();
  4610. }
  4611. Matrix.prototype._markAsUpdated = function () {
  4612. this.updateFlag = Matrix._updateFlagSeed++;
  4613. this._isIdentityDirty = true;
  4614. };
  4615. // Properties
  4616. /**
  4617. * Boolean : True is the matrix is the identity matrix
  4618. */
  4619. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4620. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4621. if (this._isIdentityDirty) {
  4622. this._isIdentityDirty = false;
  4623. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4624. this._isIdentity = false;
  4625. }
  4626. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4627. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4628. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4629. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4630. this._isIdentity = false;
  4631. }
  4632. else {
  4633. this._isIdentity = true;
  4634. }
  4635. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4636. this._isIdentity = false;
  4637. }
  4638. }
  4639. return this._isIdentity;
  4640. };
  4641. /**
  4642. * Returns the matrix determinant (float).
  4643. */
  4644. Matrix.prototype.determinant = function () {
  4645. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4646. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4647. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4648. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4649. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4650. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4651. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4652. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4653. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4654. };
  4655. // Methods
  4656. /**
  4657. * Returns the matrix underlying array.
  4658. */
  4659. Matrix.prototype.toArray = function () {
  4660. return this.m;
  4661. };
  4662. /**
  4663. * Returns the matrix underlying array.
  4664. */
  4665. Matrix.prototype.asArray = function () {
  4666. return this.toArray();
  4667. };
  4668. /**
  4669. * Inverts in place the Matrix.
  4670. * Returns the Matrix inverted.
  4671. */
  4672. Matrix.prototype.invert = function () {
  4673. this.invertToRef(this);
  4674. return this;
  4675. };
  4676. /**
  4677. * Sets all the matrix elements to zero.
  4678. * Returns the Matrix.
  4679. */
  4680. Matrix.prototype.reset = function () {
  4681. for (var index = 0; index < 16; index++) {
  4682. this.m[index] = 0.0;
  4683. }
  4684. this._markAsUpdated();
  4685. return this;
  4686. };
  4687. /**
  4688. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4689. */
  4690. Matrix.prototype.add = function (other) {
  4691. var result = new Matrix();
  4692. this.addToRef(other, result);
  4693. return result;
  4694. };
  4695. /**
  4696. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4697. * Returns the Matrix.
  4698. */
  4699. Matrix.prototype.addToRef = function (other, result) {
  4700. for (var index = 0; index < 16; index++) {
  4701. result.m[index] = this.m[index] + other.m[index];
  4702. }
  4703. result._markAsUpdated();
  4704. return this;
  4705. };
  4706. /**
  4707. * Adds in place the passed matrix to the current Matrix.
  4708. * Returns the updated Matrix.
  4709. */
  4710. Matrix.prototype.addToSelf = function (other) {
  4711. for (var index = 0; index < 16; index++) {
  4712. this.m[index] += other.m[index];
  4713. }
  4714. this._markAsUpdated();
  4715. return this;
  4716. };
  4717. /**
  4718. * Sets the passed matrix with the current inverted Matrix.
  4719. * Returns the unmodified current Matrix.
  4720. */
  4721. Matrix.prototype.invertToRef = function (other) {
  4722. var l1 = this.m[0];
  4723. var l2 = this.m[1];
  4724. var l3 = this.m[2];
  4725. var l4 = this.m[3];
  4726. var l5 = this.m[4];
  4727. var l6 = this.m[5];
  4728. var l7 = this.m[6];
  4729. var l8 = this.m[7];
  4730. var l9 = this.m[8];
  4731. var l10 = this.m[9];
  4732. var l11 = this.m[10];
  4733. var l12 = this.m[11];
  4734. var l13 = this.m[12];
  4735. var l14 = this.m[13];
  4736. var l15 = this.m[14];
  4737. var l16 = this.m[15];
  4738. var l17 = (l11 * l16) - (l12 * l15);
  4739. var l18 = (l10 * l16) - (l12 * l14);
  4740. var l19 = (l10 * l15) - (l11 * l14);
  4741. var l20 = (l9 * l16) - (l12 * l13);
  4742. var l21 = (l9 * l15) - (l11 * l13);
  4743. var l22 = (l9 * l14) - (l10 * l13);
  4744. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4745. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4746. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4747. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4748. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4749. var l28 = (l7 * l16) - (l8 * l15);
  4750. var l29 = (l6 * l16) - (l8 * l14);
  4751. var l30 = (l6 * l15) - (l7 * l14);
  4752. var l31 = (l5 * l16) - (l8 * l13);
  4753. var l32 = (l5 * l15) - (l7 * l13);
  4754. var l33 = (l5 * l14) - (l6 * l13);
  4755. var l34 = (l7 * l12) - (l8 * l11);
  4756. var l35 = (l6 * l12) - (l8 * l10);
  4757. var l36 = (l6 * l11) - (l7 * l10);
  4758. var l37 = (l5 * l12) - (l8 * l9);
  4759. var l38 = (l5 * l11) - (l7 * l9);
  4760. var l39 = (l5 * l10) - (l6 * l9);
  4761. other.m[0] = l23 * l27;
  4762. other.m[4] = l24 * l27;
  4763. other.m[8] = l25 * l27;
  4764. other.m[12] = l26 * l27;
  4765. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4766. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4767. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4768. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4769. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4770. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4771. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4772. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4773. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4774. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4775. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4776. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4777. other._markAsUpdated();
  4778. return this;
  4779. };
  4780. /**
  4781. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4782. * Returns the updated Matrix.
  4783. */
  4784. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4785. this.m[12] = x;
  4786. this.m[13] = y;
  4787. this.m[14] = z;
  4788. this._markAsUpdated();
  4789. return this;
  4790. };
  4791. /**
  4792. * Inserts the translation vector in the current Matrix.
  4793. * Returns the updated Matrix.
  4794. */
  4795. Matrix.prototype.setTranslation = function (vector3) {
  4796. this.m[12] = vector3.x;
  4797. this.m[13] = vector3.y;
  4798. this.m[14] = vector3.z;
  4799. this._markAsUpdated();
  4800. return this;
  4801. };
  4802. /**
  4803. * Returns a new Vector3 as the extracted translation from the Matrix.
  4804. */
  4805. Matrix.prototype.getTranslation = function () {
  4806. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4807. };
  4808. /**
  4809. * Fill a Vector3 with the extracted translation from the Matrix.
  4810. */
  4811. Matrix.prototype.getTranslationToRef = function (result) {
  4812. result.x = this.m[12];
  4813. result.y = this.m[13];
  4814. result.z = this.m[14];
  4815. return this;
  4816. };
  4817. /**
  4818. * Remove rotation and scaling part from the Matrix.
  4819. * Returns the updated Matrix.
  4820. */
  4821. Matrix.prototype.removeRotationAndScaling = function () {
  4822. this.setRowFromFloats(0, 1, 0, 0, 0);
  4823. this.setRowFromFloats(1, 0, 1, 0, 0);
  4824. this.setRowFromFloats(2, 0, 0, 1, 0);
  4825. return this;
  4826. };
  4827. /**
  4828. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4829. */
  4830. Matrix.prototype.multiply = function (other) {
  4831. var result = new Matrix();
  4832. this.multiplyToRef(other, result);
  4833. return result;
  4834. };
  4835. /**
  4836. * Updates the current Matrix from the passed one values.
  4837. * Returns the updated Matrix.
  4838. */
  4839. Matrix.prototype.copyFrom = function (other) {
  4840. for (var index = 0; index < 16; index++) {
  4841. this.m[index] = other.m[index];
  4842. }
  4843. this._markAsUpdated();
  4844. return this;
  4845. };
  4846. /**
  4847. * Populates the passed array from the starting index with the Matrix values.
  4848. * Returns the Matrix.
  4849. */
  4850. Matrix.prototype.copyToArray = function (array, offset) {
  4851. if (offset === void 0) { offset = 0; }
  4852. for (var index = 0; index < 16; index++) {
  4853. array[offset + index] = this.m[index];
  4854. }
  4855. return this;
  4856. };
  4857. /**
  4858. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4859. */
  4860. Matrix.prototype.multiplyToRef = function (other, result) {
  4861. this.multiplyToArray(other, result.m, 0);
  4862. result._markAsUpdated();
  4863. return this;
  4864. };
  4865. /**
  4866. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4867. */
  4868. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4869. var tm0 = this.m[0];
  4870. var tm1 = this.m[1];
  4871. var tm2 = this.m[2];
  4872. var tm3 = this.m[3];
  4873. var tm4 = this.m[4];
  4874. var tm5 = this.m[5];
  4875. var tm6 = this.m[6];
  4876. var tm7 = this.m[7];
  4877. var tm8 = this.m[8];
  4878. var tm9 = this.m[9];
  4879. var tm10 = this.m[10];
  4880. var tm11 = this.m[11];
  4881. var tm12 = this.m[12];
  4882. var tm13 = this.m[13];
  4883. var tm14 = this.m[14];
  4884. var tm15 = this.m[15];
  4885. var om0 = other.m[0];
  4886. var om1 = other.m[1];
  4887. var om2 = other.m[2];
  4888. var om3 = other.m[3];
  4889. var om4 = other.m[4];
  4890. var om5 = other.m[5];
  4891. var om6 = other.m[6];
  4892. var om7 = other.m[7];
  4893. var om8 = other.m[8];
  4894. var om9 = other.m[9];
  4895. var om10 = other.m[10];
  4896. var om11 = other.m[11];
  4897. var om12 = other.m[12];
  4898. var om13 = other.m[13];
  4899. var om14 = other.m[14];
  4900. var om15 = other.m[15];
  4901. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4902. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4903. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4904. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4905. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4906. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4907. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4908. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4909. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4910. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4911. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4912. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4913. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4914. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4915. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4916. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4917. return this;
  4918. };
  4919. /**
  4920. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4921. */
  4922. Matrix.prototype.equals = function (value) {
  4923. return value &&
  4924. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4925. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4926. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4927. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4928. };
  4929. /**
  4930. * Returns a new Matrix from the current Matrix.
  4931. */
  4932. Matrix.prototype.clone = function () {
  4933. 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]);
  4934. };
  4935. /**
  4936. * Returns the string "Matrix"
  4937. */
  4938. Matrix.prototype.getClassName = function () {
  4939. return "Matrix";
  4940. };
  4941. /**
  4942. * Returns the Matrix hash code.
  4943. */
  4944. Matrix.prototype.getHashCode = function () {
  4945. var hash = this.m[0] || 0;
  4946. for (var i = 1; i < 16; i++) {
  4947. hash = (hash * 397) ^ (this.m[i] || 0);
  4948. }
  4949. return hash;
  4950. };
  4951. /**
  4952. * Decomposes the current Matrix into :
  4953. * - a scale vector3 passed as a reference to update,
  4954. * - a rotation quaternion passed as a reference to update,
  4955. * - a translation vector3 passed as a reference to update.
  4956. * Returns the true if operation was successful.
  4957. */
  4958. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4959. translation.x = this.m[12];
  4960. translation.y = this.m[13];
  4961. translation.z = this.m[14];
  4962. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4963. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4964. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4965. if (this.determinant() <= 0) {
  4966. scale.y *= -1;
  4967. }
  4968. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4969. rotation.x = 0;
  4970. rotation.y = 0;
  4971. rotation.z = 0;
  4972. rotation.w = 1;
  4973. return false;
  4974. }
  4975. 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]);
  4976. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4977. return true;
  4978. };
  4979. /**
  4980. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  4981. * @param ref matrix to store the result
  4982. */
  4983. Matrix.prototype.toNormalMatrix = function (ref) {
  4984. this.invertToRef(ref);
  4985. ref.transpose();
  4986. var m = ref.m;
  4987. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  4988. };
  4989. /**
  4990. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4991. */
  4992. Matrix.prototype.getRotationMatrix = function () {
  4993. var result = Matrix.Identity();
  4994. this.getRotationMatrixToRef(result);
  4995. return result;
  4996. };
  4997. /**
  4998. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4999. * Returns the current Matrix.
  5000. */
  5001. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5002. var m = this.m;
  5003. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5004. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5005. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5006. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5007. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5008. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5009. 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);
  5010. return this;
  5011. };
  5012. // Statics
  5013. /**
  5014. * Returns a new Matrix set from the starting index of the passed array.
  5015. */
  5016. Matrix.FromArray = function (array, offset) {
  5017. var result = new Matrix();
  5018. if (!offset) {
  5019. offset = 0;
  5020. }
  5021. Matrix.FromArrayToRef(array, offset, result);
  5022. return result;
  5023. };
  5024. /**
  5025. * Sets the passed "result" matrix from the starting index of the passed array.
  5026. */
  5027. Matrix.FromArrayToRef = function (array, offset, result) {
  5028. for (var index = 0; index < 16; index++) {
  5029. result.m[index] = array[index + offset];
  5030. }
  5031. result._markAsUpdated();
  5032. };
  5033. /**
  5034. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5035. */
  5036. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5037. for (var index = 0; index < 16; index++) {
  5038. result.m[index] = array[index + offset] * scale;
  5039. }
  5040. result._markAsUpdated();
  5041. };
  5042. /**
  5043. * Sets the passed matrix "result" with the 16 passed floats.
  5044. */
  5045. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5046. result.m[0] = initialM11;
  5047. result.m[1] = initialM12;
  5048. result.m[2] = initialM13;
  5049. result.m[3] = initialM14;
  5050. result.m[4] = initialM21;
  5051. result.m[5] = initialM22;
  5052. result.m[6] = initialM23;
  5053. result.m[7] = initialM24;
  5054. result.m[8] = initialM31;
  5055. result.m[9] = initialM32;
  5056. result.m[10] = initialM33;
  5057. result.m[11] = initialM34;
  5058. result.m[12] = initialM41;
  5059. result.m[13] = initialM42;
  5060. result.m[14] = initialM43;
  5061. result.m[15] = initialM44;
  5062. result._markAsUpdated();
  5063. };
  5064. /**
  5065. * Returns the index-th row of the current matrix as a new Vector4.
  5066. */
  5067. Matrix.prototype.getRow = function (index) {
  5068. if (index < 0 || index > 3) {
  5069. return null;
  5070. }
  5071. var i = index * 4;
  5072. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5073. };
  5074. /**
  5075. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5076. * Returns the updated Matrix.
  5077. */
  5078. Matrix.prototype.setRow = function (index, row) {
  5079. if (index < 0 || index > 3) {
  5080. return this;
  5081. }
  5082. var i = index * 4;
  5083. this.m[i + 0] = row.x;
  5084. this.m[i + 1] = row.y;
  5085. this.m[i + 2] = row.z;
  5086. this.m[i + 3] = row.w;
  5087. this._markAsUpdated();
  5088. return this;
  5089. };
  5090. /**
  5091. * Compute the transpose of the matrix.
  5092. * Returns a new Matrix.
  5093. */
  5094. Matrix.prototype.transpose = function () {
  5095. return Matrix.Transpose(this);
  5096. };
  5097. /**
  5098. * Compute the transpose of the matrix.
  5099. * Returns the current matrix.
  5100. */
  5101. Matrix.prototype.transposeToRef = function (result) {
  5102. Matrix.TransposeToRef(this, result);
  5103. return this;
  5104. };
  5105. /**
  5106. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5107. * Returns the updated Matrix.
  5108. */
  5109. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5110. if (index < 0 || index > 3) {
  5111. return this;
  5112. }
  5113. var i = index * 4;
  5114. this.m[i + 0] = x;
  5115. this.m[i + 1] = y;
  5116. this.m[i + 2] = z;
  5117. this.m[i + 3] = w;
  5118. this._markAsUpdated();
  5119. return this;
  5120. };
  5121. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5122. /**
  5123. * Static identity matrix to be used as readonly matrix
  5124. * Must not be updated.
  5125. */
  5126. get: function () {
  5127. return Matrix._identityReadOnly;
  5128. },
  5129. enumerable: true,
  5130. configurable: true
  5131. });
  5132. /**
  5133. * Returns a new Matrix set from the 16 passed floats.
  5134. */
  5135. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5136. var result = new Matrix();
  5137. result.m[0] = initialM11;
  5138. result.m[1] = initialM12;
  5139. result.m[2] = initialM13;
  5140. result.m[3] = initialM14;
  5141. result.m[4] = initialM21;
  5142. result.m[5] = initialM22;
  5143. result.m[6] = initialM23;
  5144. result.m[7] = initialM24;
  5145. result.m[8] = initialM31;
  5146. result.m[9] = initialM32;
  5147. result.m[10] = initialM33;
  5148. result.m[11] = initialM34;
  5149. result.m[12] = initialM41;
  5150. result.m[13] = initialM42;
  5151. result.m[14] = initialM43;
  5152. result.m[15] = initialM44;
  5153. return result;
  5154. };
  5155. /**
  5156. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5157. */
  5158. Matrix.Compose = function (scale, rotation, translation) {
  5159. var result = Matrix.Identity();
  5160. Matrix.ComposeToRef(scale, rotation, translation, result);
  5161. return result;
  5162. };
  5163. /**
  5164. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5165. */
  5166. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5167. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5168. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5169. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5170. result.setTranslation(translation);
  5171. };
  5172. /**
  5173. * Returns a new indentity Matrix.
  5174. */
  5175. Matrix.Identity = function () {
  5176. 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);
  5177. };
  5178. /**
  5179. * Sets the passed "result" as an identity matrix.
  5180. */
  5181. Matrix.IdentityToRef = function (result) {
  5182. 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);
  5183. };
  5184. /**
  5185. * Returns a new zero Matrix.
  5186. */
  5187. Matrix.Zero = function () {
  5188. 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);
  5189. };
  5190. /**
  5191. * Returns a new rotation matrix for "angle" radians around the X axis.
  5192. */
  5193. Matrix.RotationX = function (angle) {
  5194. var result = new Matrix();
  5195. Matrix.RotationXToRef(angle, result);
  5196. return result;
  5197. };
  5198. /**
  5199. * Returns a new Matrix as the passed inverted one.
  5200. */
  5201. Matrix.Invert = function (source) {
  5202. var result = new Matrix();
  5203. source.invertToRef(result);
  5204. return result;
  5205. };
  5206. /**
  5207. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5208. */
  5209. Matrix.RotationXToRef = function (angle, result) {
  5210. var s = Math.sin(angle);
  5211. var c = Math.cos(angle);
  5212. result.m[0] = 1.0;
  5213. result.m[15] = 1.0;
  5214. result.m[5] = c;
  5215. result.m[10] = c;
  5216. result.m[9] = -s;
  5217. result.m[6] = s;
  5218. result.m[1] = 0.0;
  5219. result.m[2] = 0.0;
  5220. result.m[3] = 0.0;
  5221. result.m[4] = 0.0;
  5222. result.m[7] = 0.0;
  5223. result.m[8] = 0.0;
  5224. result.m[11] = 0.0;
  5225. result.m[12] = 0.0;
  5226. result.m[13] = 0.0;
  5227. result.m[14] = 0.0;
  5228. result._markAsUpdated();
  5229. };
  5230. /**
  5231. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5232. */
  5233. Matrix.RotationY = function (angle) {
  5234. var result = new Matrix();
  5235. Matrix.RotationYToRef(angle, result);
  5236. return result;
  5237. };
  5238. /**
  5239. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5240. */
  5241. Matrix.RotationYToRef = function (angle, result) {
  5242. var s = Math.sin(angle);
  5243. var c = Math.cos(angle);
  5244. result.m[5] = 1.0;
  5245. result.m[15] = 1.0;
  5246. result.m[0] = c;
  5247. result.m[2] = -s;
  5248. result.m[8] = s;
  5249. result.m[10] = c;
  5250. result.m[1] = 0.0;
  5251. result.m[3] = 0.0;
  5252. result.m[4] = 0.0;
  5253. result.m[6] = 0.0;
  5254. result.m[7] = 0.0;
  5255. result.m[9] = 0.0;
  5256. result.m[11] = 0.0;
  5257. result.m[12] = 0.0;
  5258. result.m[13] = 0.0;
  5259. result.m[14] = 0.0;
  5260. result._markAsUpdated();
  5261. };
  5262. /**
  5263. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5264. */
  5265. Matrix.RotationZ = function (angle) {
  5266. var result = new Matrix();
  5267. Matrix.RotationZToRef(angle, result);
  5268. return result;
  5269. };
  5270. /**
  5271. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5272. */
  5273. Matrix.RotationZToRef = function (angle, result) {
  5274. var s = Math.sin(angle);
  5275. var c = Math.cos(angle);
  5276. result.m[10] = 1.0;
  5277. result.m[15] = 1.0;
  5278. result.m[0] = c;
  5279. result.m[1] = s;
  5280. result.m[4] = -s;
  5281. result.m[5] = c;
  5282. result.m[2] = 0.0;
  5283. result.m[3] = 0.0;
  5284. result.m[6] = 0.0;
  5285. result.m[7] = 0.0;
  5286. result.m[8] = 0.0;
  5287. result.m[9] = 0.0;
  5288. result.m[11] = 0.0;
  5289. result.m[12] = 0.0;
  5290. result.m[13] = 0.0;
  5291. result.m[14] = 0.0;
  5292. result._markAsUpdated();
  5293. };
  5294. /**
  5295. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5296. */
  5297. Matrix.RotationAxis = function (axis, angle) {
  5298. var result = Matrix.Zero();
  5299. Matrix.RotationAxisToRef(axis, angle, result);
  5300. return result;
  5301. };
  5302. /**
  5303. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5304. */
  5305. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5306. var s = Math.sin(-angle);
  5307. var c = Math.cos(-angle);
  5308. var c1 = 1 - c;
  5309. axis.normalize();
  5310. result.m[0] = (axis.x * axis.x) * c1 + c;
  5311. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5312. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5313. result.m[3] = 0.0;
  5314. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5315. result.m[5] = (axis.y * axis.y) * c1 + c;
  5316. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5317. result.m[7] = 0.0;
  5318. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5319. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5320. result.m[10] = (axis.z * axis.z) * c1 + c;
  5321. result.m[11] = 0.0;
  5322. result.m[15] = 1.0;
  5323. result._markAsUpdated();
  5324. };
  5325. /**
  5326. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5327. */
  5328. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5329. var result = new Matrix();
  5330. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5331. return result;
  5332. };
  5333. /**
  5334. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5335. */
  5336. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5337. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5338. this._tempQuaternion.toRotationMatrix(result);
  5339. };
  5340. /**
  5341. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5342. */
  5343. Matrix.Scaling = function (x, y, z) {
  5344. var result = Matrix.Zero();
  5345. Matrix.ScalingToRef(x, y, z, result);
  5346. return result;
  5347. };
  5348. /**
  5349. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5350. */
  5351. Matrix.ScalingToRef = function (x, y, z, result) {
  5352. result.m[0] = x;
  5353. result.m[1] = 0.0;
  5354. result.m[2] = 0.0;
  5355. result.m[3] = 0.0;
  5356. result.m[4] = 0.0;
  5357. result.m[5] = y;
  5358. result.m[6] = 0.0;
  5359. result.m[7] = 0.0;
  5360. result.m[8] = 0.0;
  5361. result.m[9] = 0.0;
  5362. result.m[10] = z;
  5363. result.m[11] = 0.0;
  5364. result.m[12] = 0.0;
  5365. result.m[13] = 0.0;
  5366. result.m[14] = 0.0;
  5367. result.m[15] = 1.0;
  5368. result._markAsUpdated();
  5369. };
  5370. /**
  5371. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5372. */
  5373. Matrix.Translation = function (x, y, z) {
  5374. var result = Matrix.Identity();
  5375. Matrix.TranslationToRef(x, y, z, result);
  5376. return result;
  5377. };
  5378. /**
  5379. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5380. */
  5381. Matrix.TranslationToRef = function (x, y, z, result) {
  5382. 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);
  5383. };
  5384. /**
  5385. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5386. */
  5387. Matrix.Lerp = function (startValue, endValue, gradient) {
  5388. var result = Matrix.Zero();
  5389. for (var index = 0; index < 16; index++) {
  5390. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5391. }
  5392. result._markAsUpdated();
  5393. return result;
  5394. };
  5395. /**
  5396. * Returns a new Matrix whose values are computed by :
  5397. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5398. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5399. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5400. */
  5401. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5402. var startScale = new Vector3(0, 0, 0);
  5403. var startRotation = new Quaternion();
  5404. var startTranslation = new Vector3(0, 0, 0);
  5405. startValue.decompose(startScale, startRotation, startTranslation);
  5406. var endScale = new Vector3(0, 0, 0);
  5407. var endRotation = new Quaternion();
  5408. var endTranslation = new Vector3(0, 0, 0);
  5409. endValue.decompose(endScale, endRotation, endTranslation);
  5410. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5411. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5412. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5413. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5414. };
  5415. /**
  5416. * 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".
  5417. * This methods works for a Left-Handed system.
  5418. */
  5419. Matrix.LookAtLH = function (eye, target, up) {
  5420. var result = Matrix.Zero();
  5421. Matrix.LookAtLHToRef(eye, target, up, result);
  5422. return result;
  5423. };
  5424. /**
  5425. * 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".
  5426. * This methods works for a Left-Handed system.
  5427. */
  5428. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5429. // Z axis
  5430. target.subtractToRef(eye, this._zAxis);
  5431. this._zAxis.normalize();
  5432. // X axis
  5433. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5434. if (this._xAxis.lengthSquared() === 0) {
  5435. this._xAxis.x = 1.0;
  5436. }
  5437. else {
  5438. this._xAxis.normalize();
  5439. }
  5440. // Y axis
  5441. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5442. this._yAxis.normalize();
  5443. // Eye angles
  5444. var ex = -Vector3.Dot(this._xAxis, eye);
  5445. var ey = -Vector3.Dot(this._yAxis, eye);
  5446. var ez = -Vector3.Dot(this._zAxis, eye);
  5447. 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);
  5448. };
  5449. /**
  5450. * 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".
  5451. * This methods works for a Right-Handed system.
  5452. */
  5453. Matrix.LookAtRH = function (eye, target, up) {
  5454. var result = Matrix.Zero();
  5455. Matrix.LookAtRHToRef(eye, target, up, result);
  5456. return result;
  5457. };
  5458. /**
  5459. * 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".
  5460. * This methods works for a Left-Handed system.
  5461. */
  5462. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5463. // Z axis
  5464. eye.subtractToRef(target, this._zAxis);
  5465. this._zAxis.normalize();
  5466. // X axis
  5467. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5468. if (this._xAxis.lengthSquared() === 0) {
  5469. this._xAxis.x = 1.0;
  5470. }
  5471. else {
  5472. this._xAxis.normalize();
  5473. }
  5474. // Y axis
  5475. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5476. this._yAxis.normalize();
  5477. // Eye angles
  5478. var ex = -Vector3.Dot(this._xAxis, eye);
  5479. var ey = -Vector3.Dot(this._yAxis, eye);
  5480. var ez = -Vector3.Dot(this._zAxis, eye);
  5481. 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);
  5482. };
  5483. /**
  5484. * 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.
  5485. */
  5486. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5487. var matrix = Matrix.Zero();
  5488. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5489. return matrix;
  5490. };
  5491. /**
  5492. * 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.
  5493. */
  5494. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5495. var n = znear;
  5496. var f = zfar;
  5497. var a = 2.0 / width;
  5498. var b = 2.0 / height;
  5499. var c = 2.0 / (f - n);
  5500. var d = -(f + n) / (f - n);
  5501. 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);
  5502. };
  5503. /**
  5504. * 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.
  5505. */
  5506. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5507. var matrix = Matrix.Zero();
  5508. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5509. return matrix;
  5510. };
  5511. /**
  5512. * 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.
  5513. */
  5514. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5515. var n = znear;
  5516. var f = zfar;
  5517. var a = 2.0 / (right - left);
  5518. var b = 2.0 / (top - bottom);
  5519. var c = 2.0 / (f - n);
  5520. var d = -(f + n) / (f - n);
  5521. var i0 = (left + right) / (left - right);
  5522. var i1 = (top + bottom) / (bottom - top);
  5523. 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);
  5524. };
  5525. /**
  5526. * 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.
  5527. */
  5528. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5529. var matrix = Matrix.Zero();
  5530. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5531. return matrix;
  5532. };
  5533. /**
  5534. * 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.
  5535. */
  5536. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5537. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5538. result.m[10] *= -1.0;
  5539. };
  5540. /**
  5541. * 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.
  5542. */
  5543. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5544. var matrix = Matrix.Zero();
  5545. var n = znear;
  5546. var f = zfar;
  5547. var a = 2.0 * n / width;
  5548. var b = 2.0 * n / height;
  5549. var c = (f + n) / (f - n);
  5550. var d = -2.0 * f * n / (f - n);
  5551. 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);
  5552. return matrix;
  5553. };
  5554. /**
  5555. * 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.
  5556. */
  5557. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5558. var matrix = Matrix.Zero();
  5559. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5560. return matrix;
  5561. };
  5562. /**
  5563. * 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.
  5564. */
  5565. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5566. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5567. var n = znear;
  5568. var f = zfar;
  5569. var t = 1.0 / (Math.tan(fov * 0.5));
  5570. var a = isVerticalFovFixed ? (t / aspect) : t;
  5571. var b = isVerticalFovFixed ? t : (t * aspect);
  5572. var c = (f + n) / (f - n);
  5573. var d = -2.0 * f * n / (f - n);
  5574. 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);
  5575. };
  5576. /**
  5577. * 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.
  5578. */
  5579. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5580. var matrix = Matrix.Zero();
  5581. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5582. return matrix;
  5583. };
  5584. /**
  5585. * 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.
  5586. */
  5587. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5588. //alternatively this could be expressed as:
  5589. // m = PerspectiveFovLHToRef
  5590. // m[10] *= -1.0;
  5591. // m[11] *= -1.0;
  5592. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5593. var n = znear;
  5594. var f = zfar;
  5595. var t = 1.0 / (Math.tan(fov * 0.5));
  5596. var a = isVerticalFovFixed ? (t / aspect) : t;
  5597. var b = isVerticalFovFixed ? t : (t * aspect);
  5598. var c = -(f + n) / (f - n);
  5599. var d = -2 * f * n / (f - n);
  5600. 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);
  5601. };
  5602. /**
  5603. * 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.
  5604. */
  5605. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5606. if (rightHanded === void 0) { rightHanded = false; }
  5607. var rightHandedFactor = rightHanded ? -1 : 1;
  5608. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5609. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5610. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5611. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5612. var xScale = 2.0 / (leftTan + rightTan);
  5613. var yScale = 2.0 / (upTan + downTan);
  5614. result.m[0] = xScale;
  5615. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5616. result.m[5] = yScale;
  5617. result.m[6] = result.m[7] = 0.0;
  5618. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5619. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5620. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5621. result.m[10] = -zfar / (znear - zfar);
  5622. result.m[11] = 1.0 * rightHandedFactor;
  5623. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5624. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5625. // result.m[14] = (znear * zfar) / (znear - zfar);
  5626. result._markAsUpdated();
  5627. };
  5628. /**
  5629. * Returns the final transformation matrix : world * view * projection * viewport
  5630. */
  5631. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5632. var cw = viewport.width;
  5633. var ch = viewport.height;
  5634. var cx = viewport.x;
  5635. var cy = viewport.y;
  5636. 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);
  5637. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5638. };
  5639. /**
  5640. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5641. */
  5642. Matrix.GetAsMatrix2x2 = function (matrix) {
  5643. return new Float32Array([
  5644. matrix.m[0], matrix.m[1],
  5645. matrix.m[4], matrix.m[5]
  5646. ]);
  5647. };
  5648. /**
  5649. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5650. */
  5651. Matrix.GetAsMatrix3x3 = function (matrix) {
  5652. return new Float32Array([
  5653. matrix.m[0], matrix.m[1], matrix.m[2],
  5654. matrix.m[4], matrix.m[5], matrix.m[6],
  5655. matrix.m[8], matrix.m[9], matrix.m[10]
  5656. ]);
  5657. };
  5658. /**
  5659. * Compute the transpose of the passed Matrix.
  5660. * Returns a new Matrix.
  5661. */
  5662. Matrix.Transpose = function (matrix) {
  5663. var result = new Matrix();
  5664. Matrix.TransposeToRef(matrix, result);
  5665. return result;
  5666. };
  5667. /**
  5668. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5669. */
  5670. Matrix.TransposeToRef = function (matrix, result) {
  5671. result.m[0] = matrix.m[0];
  5672. result.m[1] = matrix.m[4];
  5673. result.m[2] = matrix.m[8];
  5674. result.m[3] = matrix.m[12];
  5675. result.m[4] = matrix.m[1];
  5676. result.m[5] = matrix.m[5];
  5677. result.m[6] = matrix.m[9];
  5678. result.m[7] = matrix.m[13];
  5679. result.m[8] = matrix.m[2];
  5680. result.m[9] = matrix.m[6];
  5681. result.m[10] = matrix.m[10];
  5682. result.m[11] = matrix.m[14];
  5683. result.m[12] = matrix.m[3];
  5684. result.m[13] = matrix.m[7];
  5685. result.m[14] = matrix.m[11];
  5686. result.m[15] = matrix.m[15];
  5687. };
  5688. /**
  5689. * Returns a new Matrix as the reflection matrix across the passed plane.
  5690. */
  5691. Matrix.Reflection = function (plane) {
  5692. var matrix = new Matrix();
  5693. Matrix.ReflectionToRef(plane, matrix);
  5694. return matrix;
  5695. };
  5696. /**
  5697. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5698. */
  5699. Matrix.ReflectionToRef = function (plane, result) {
  5700. plane.normalize();
  5701. var x = plane.normal.x;
  5702. var y = plane.normal.y;
  5703. var z = plane.normal.z;
  5704. var temp = -2 * x;
  5705. var temp2 = -2 * y;
  5706. var temp3 = -2 * z;
  5707. result.m[0] = (temp * x) + 1;
  5708. result.m[1] = temp2 * x;
  5709. result.m[2] = temp3 * x;
  5710. result.m[3] = 0.0;
  5711. result.m[4] = temp * y;
  5712. result.m[5] = (temp2 * y) + 1;
  5713. result.m[6] = temp3 * y;
  5714. result.m[7] = 0.0;
  5715. result.m[8] = temp * z;
  5716. result.m[9] = temp2 * z;
  5717. result.m[10] = (temp3 * z) + 1;
  5718. result.m[11] = 0.0;
  5719. result.m[12] = temp * plane.d;
  5720. result.m[13] = temp2 * plane.d;
  5721. result.m[14] = temp3 * plane.d;
  5722. result.m[15] = 1.0;
  5723. result._markAsUpdated();
  5724. };
  5725. /**
  5726. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5727. */
  5728. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5729. result.m[0] = xaxis.x;
  5730. result.m[1] = xaxis.y;
  5731. result.m[2] = xaxis.z;
  5732. result.m[3] = 0.0;
  5733. result.m[4] = yaxis.x;
  5734. result.m[5] = yaxis.y;
  5735. result.m[6] = yaxis.z;
  5736. result.m[7] = 0.0;
  5737. result.m[8] = zaxis.x;
  5738. result.m[9] = zaxis.y;
  5739. result.m[10] = zaxis.z;
  5740. result.m[11] = 0.0;
  5741. result.m[12] = 0.0;
  5742. result.m[13] = 0.0;
  5743. result.m[14] = 0.0;
  5744. result.m[15] = 1.0;
  5745. result._markAsUpdated();
  5746. };
  5747. /**
  5748. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5749. */
  5750. Matrix.FromQuaternionToRef = function (quat, result) {
  5751. var xx = quat.x * quat.x;
  5752. var yy = quat.y * quat.y;
  5753. var zz = quat.z * quat.z;
  5754. var xy = quat.x * quat.y;
  5755. var zw = quat.z * quat.w;
  5756. var zx = quat.z * quat.x;
  5757. var yw = quat.y * quat.w;
  5758. var yz = quat.y * quat.z;
  5759. var xw = quat.x * quat.w;
  5760. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5761. result.m[1] = 2.0 * (xy + zw);
  5762. result.m[2] = 2.0 * (zx - yw);
  5763. result.m[3] = 0.0;
  5764. result.m[4] = 2.0 * (xy - zw);
  5765. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5766. result.m[6] = 2.0 * (yz + xw);
  5767. result.m[7] = 0.0;
  5768. result.m[8] = 2.0 * (zx + yw);
  5769. result.m[9] = 2.0 * (yz - xw);
  5770. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5771. result.m[11] = 0.0;
  5772. result.m[12] = 0.0;
  5773. result.m[13] = 0.0;
  5774. result.m[14] = 0.0;
  5775. result.m[15] = 1.0;
  5776. result._markAsUpdated();
  5777. };
  5778. Matrix._tempQuaternion = new Quaternion();
  5779. Matrix._xAxis = Vector3.Zero();
  5780. Matrix._yAxis = Vector3.Zero();
  5781. Matrix._zAxis = Vector3.Zero();
  5782. Matrix._updateFlagSeed = 0;
  5783. Matrix._identityReadOnly = Matrix.Identity();
  5784. return Matrix;
  5785. }());
  5786. BABYLON.Matrix = Matrix;
  5787. var Plane = /** @class */ (function () {
  5788. /**
  5789. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5790. */
  5791. function Plane(a, b, c, d) {
  5792. this.normal = new Vector3(a, b, c);
  5793. this.d = d;
  5794. }
  5795. /**
  5796. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5797. */
  5798. Plane.prototype.asArray = function () {
  5799. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5800. };
  5801. // Methods
  5802. /**
  5803. * Returns a new plane copied from the current Plane.
  5804. */
  5805. Plane.prototype.clone = function () {
  5806. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5807. };
  5808. /**
  5809. * Returns the string "Plane".
  5810. */
  5811. Plane.prototype.getClassName = function () {
  5812. return "Plane";
  5813. };
  5814. /**
  5815. * Returns the Plane hash code.
  5816. */
  5817. Plane.prototype.getHashCode = function () {
  5818. var hash = this.normal.getHashCode();
  5819. hash = (hash * 397) ^ (this.d || 0);
  5820. return hash;
  5821. };
  5822. /**
  5823. * Normalize the current Plane in place.
  5824. * Returns the updated Plane.
  5825. */
  5826. Plane.prototype.normalize = function () {
  5827. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5828. var magnitude = 0.0;
  5829. if (norm !== 0) {
  5830. magnitude = 1.0 / norm;
  5831. }
  5832. this.normal.x *= magnitude;
  5833. this.normal.y *= magnitude;
  5834. this.normal.z *= magnitude;
  5835. this.d *= magnitude;
  5836. return this;
  5837. };
  5838. /**
  5839. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5840. */
  5841. Plane.prototype.transform = function (transformation) {
  5842. var transposedMatrix = Matrix.Transpose(transformation);
  5843. var x = this.normal.x;
  5844. var y = this.normal.y;
  5845. var z = this.normal.z;
  5846. var d = this.d;
  5847. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5848. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5849. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5850. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5851. return new Plane(normalX, normalY, normalZ, finalD);
  5852. };
  5853. /**
  5854. * Returns the dot product (float) of the point coordinates and the plane normal.
  5855. */
  5856. Plane.prototype.dotCoordinate = function (point) {
  5857. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5858. };
  5859. /**
  5860. * Updates the current Plane from the plane defined by the three passed points.
  5861. * Returns the updated Plane.
  5862. */
  5863. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5864. var x1 = point2.x - point1.x;
  5865. var y1 = point2.y - point1.y;
  5866. var z1 = point2.z - point1.z;
  5867. var x2 = point3.x - point1.x;
  5868. var y2 = point3.y - point1.y;
  5869. var z2 = point3.z - point1.z;
  5870. var yz = (y1 * z2) - (z1 * y2);
  5871. var xz = (z1 * x2) - (x1 * z2);
  5872. var xy = (x1 * y2) - (y1 * x2);
  5873. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5874. var invPyth;
  5875. if (pyth !== 0) {
  5876. invPyth = 1.0 / pyth;
  5877. }
  5878. else {
  5879. invPyth = 0.0;
  5880. }
  5881. this.normal.x = yz * invPyth;
  5882. this.normal.y = xz * invPyth;
  5883. this.normal.z = xy * invPyth;
  5884. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5885. return this;
  5886. };
  5887. /**
  5888. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5889. */
  5890. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5891. var dot = Vector3.Dot(this.normal, direction);
  5892. return (dot <= epsilon);
  5893. };
  5894. /**
  5895. * Returns the signed distance (float) from the passed point to the Plane.
  5896. */
  5897. Plane.prototype.signedDistanceTo = function (point) {
  5898. return Vector3.Dot(point, this.normal) + this.d;
  5899. };
  5900. // Statics
  5901. /**
  5902. * Returns a new Plane from the passed array.
  5903. */
  5904. Plane.FromArray = function (array) {
  5905. return new Plane(array[0], array[1], array[2], array[3]);
  5906. };
  5907. /**
  5908. * Returns a new Plane defined by the three passed points.
  5909. */
  5910. Plane.FromPoints = function (point1, point2, point3) {
  5911. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5912. result.copyFromPoints(point1, point2, point3);
  5913. return result;
  5914. };
  5915. /**
  5916. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5917. * Note : the vector "normal" is updated because normalized.
  5918. */
  5919. Plane.FromPositionAndNormal = function (origin, normal) {
  5920. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5921. normal.normalize();
  5922. result.normal = normal;
  5923. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5924. return result;
  5925. };
  5926. /**
  5927. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5928. */
  5929. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5930. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5931. return Vector3.Dot(point, normal) + d;
  5932. };
  5933. return Plane;
  5934. }());
  5935. BABYLON.Plane = Plane;
  5936. var Viewport = /** @class */ (function () {
  5937. /**
  5938. * Creates a Viewport object located at (x, y) and sized (width, height).
  5939. */
  5940. function Viewport(x, y, width, height) {
  5941. this.x = x;
  5942. this.y = y;
  5943. this.width = width;
  5944. this.height = height;
  5945. }
  5946. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5947. if (renderWidthOrEngine.getRenderWidth) {
  5948. var engine = renderWidthOrEngine;
  5949. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5950. }
  5951. var renderWidth = renderWidthOrEngine;
  5952. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5953. };
  5954. /**
  5955. * Returns a new Viewport copied from the current one.
  5956. */
  5957. Viewport.prototype.clone = function () {
  5958. return new Viewport(this.x, this.y, this.width, this.height);
  5959. };
  5960. return Viewport;
  5961. }());
  5962. BABYLON.Viewport = Viewport;
  5963. var Frustum = /** @class */ (function () {
  5964. function Frustum() {
  5965. }
  5966. /**
  5967. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5968. */
  5969. Frustum.GetPlanes = function (transform) {
  5970. var frustumPlanes = [];
  5971. for (var index = 0; index < 6; index++) {
  5972. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5973. }
  5974. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5975. return frustumPlanes;
  5976. };
  5977. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5978. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5979. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5980. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5981. frustumPlane.d = transform.m[15] + transform.m[14];
  5982. frustumPlane.normalize();
  5983. };
  5984. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5985. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5986. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5987. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5988. frustumPlane.d = transform.m[15] - transform.m[14];
  5989. frustumPlane.normalize();
  5990. };
  5991. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5992. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5993. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5994. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5995. frustumPlane.d = transform.m[15] + transform.m[12];
  5996. frustumPlane.normalize();
  5997. };
  5998. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5999. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6000. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6001. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6002. frustumPlane.d = transform.m[15] - transform.m[12];
  6003. frustumPlane.normalize();
  6004. };
  6005. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6006. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6007. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6008. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6009. frustumPlane.d = transform.m[15] - transform.m[13];
  6010. frustumPlane.normalize();
  6011. };
  6012. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6013. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6014. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6015. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6016. frustumPlane.d = transform.m[15] + transform.m[13];
  6017. frustumPlane.normalize();
  6018. };
  6019. /**
  6020. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6021. */
  6022. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6023. // Near
  6024. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6025. // Far
  6026. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6027. // Left
  6028. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6029. // Right
  6030. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6031. // Top
  6032. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6033. // Bottom
  6034. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6035. };
  6036. return Frustum;
  6037. }());
  6038. BABYLON.Frustum = Frustum;
  6039. var Space;
  6040. (function (Space) {
  6041. Space[Space["LOCAL"] = 0] = "LOCAL";
  6042. Space[Space["WORLD"] = 1] = "WORLD";
  6043. Space[Space["BONE"] = 2] = "BONE";
  6044. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6045. var Axis = /** @class */ (function () {
  6046. function Axis() {
  6047. }
  6048. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6049. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6050. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6051. return Axis;
  6052. }());
  6053. BABYLON.Axis = Axis;
  6054. ;
  6055. var BezierCurve = /** @class */ (function () {
  6056. function BezierCurve() {
  6057. }
  6058. /**
  6059. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6060. */
  6061. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6062. // Extract X (which is equal to time here)
  6063. var f0 = 1 - 3 * x2 + 3 * x1;
  6064. var f1 = 3 * x2 - 6 * x1;
  6065. var f2 = 3 * x1;
  6066. var refinedT = t;
  6067. for (var i = 0; i < 5; i++) {
  6068. var refinedT2 = refinedT * refinedT;
  6069. var refinedT3 = refinedT2 * refinedT;
  6070. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6071. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6072. refinedT -= (x - t) * slope;
  6073. refinedT = Math.min(1, Math.max(0, refinedT));
  6074. }
  6075. // Resolve cubic bezier for the given x
  6076. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6077. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6078. Math.pow(refinedT, 3);
  6079. };
  6080. return BezierCurve;
  6081. }());
  6082. BABYLON.BezierCurve = BezierCurve;
  6083. var Orientation;
  6084. (function (Orientation) {
  6085. Orientation[Orientation["CW"] = 0] = "CW";
  6086. Orientation[Orientation["CCW"] = 1] = "CCW";
  6087. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6088. var Angle = /** @class */ (function () {
  6089. /**
  6090. * Creates an Angle object of "radians" radians (float).
  6091. */
  6092. function Angle(radians) {
  6093. var _this = this;
  6094. /**
  6095. * Returns the Angle value in degrees (float).
  6096. */
  6097. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6098. /**
  6099. * Returns the Angle value in radians (float).
  6100. */
  6101. this.radians = function () { return _this._radians; };
  6102. this._radians = radians;
  6103. if (this._radians < 0.0)
  6104. this._radians += (2.0 * Math.PI);
  6105. }
  6106. /**
  6107. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6108. */
  6109. Angle.BetweenTwoPoints = function (a, b) {
  6110. var delta = b.subtract(a);
  6111. var theta = Math.atan2(delta.y, delta.x);
  6112. return new Angle(theta);
  6113. };
  6114. /**
  6115. * Returns a new Angle object from the passed float in radians.
  6116. */
  6117. Angle.FromRadians = function (radians) {
  6118. return new Angle(radians);
  6119. };
  6120. /**
  6121. * Returns a new Angle object from the passed float in degrees.
  6122. */
  6123. Angle.FromDegrees = function (degrees) {
  6124. return new Angle(degrees * Math.PI / 180.0);
  6125. };
  6126. return Angle;
  6127. }());
  6128. BABYLON.Angle = Angle;
  6129. var Arc2 = /** @class */ (function () {
  6130. /**
  6131. * Creates an Arc object from the three passed points : start, middle and end.
  6132. */
  6133. function Arc2(startPoint, midPoint, endPoint) {
  6134. this.startPoint = startPoint;
  6135. this.midPoint = midPoint;
  6136. this.endPoint = endPoint;
  6137. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6138. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6139. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6140. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6141. 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);
  6142. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6143. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6144. var a1 = this.startAngle.degrees();
  6145. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6146. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6147. // angles correction
  6148. if (a2 - a1 > +180.0)
  6149. a2 -= 360.0;
  6150. if (a2 - a1 < -180.0)
  6151. a2 += 360.0;
  6152. if (a3 - a2 > +180.0)
  6153. a3 -= 360.0;
  6154. if (a3 - a2 < -180.0)
  6155. a3 += 360.0;
  6156. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6157. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6158. }
  6159. return Arc2;
  6160. }());
  6161. BABYLON.Arc2 = Arc2;
  6162. var Path2 = /** @class */ (function () {
  6163. /**
  6164. * Creates a Path2 object from the starting 2D coordinates x and y.
  6165. */
  6166. function Path2(x, y) {
  6167. this._points = new Array();
  6168. this._length = 0.0;
  6169. this.closed = false;
  6170. this._points.push(new Vector2(x, y));
  6171. }
  6172. /**
  6173. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6174. * Returns the updated Path2.
  6175. */
  6176. Path2.prototype.addLineTo = function (x, y) {
  6177. if (this.closed) {
  6178. //Tools.Error("cannot add lines to closed paths");
  6179. return this;
  6180. }
  6181. var newPoint = new Vector2(x, y);
  6182. var previousPoint = this._points[this._points.length - 1];
  6183. this._points.push(newPoint);
  6184. this._length += newPoint.subtract(previousPoint).length();
  6185. return this;
  6186. };
  6187. /**
  6188. * 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.
  6189. * Returns the updated Path2.
  6190. */
  6191. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6192. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6193. if (this.closed) {
  6194. //Tools.Error("cannot add arcs to closed paths");
  6195. return this;
  6196. }
  6197. var startPoint = this._points[this._points.length - 1];
  6198. var midPoint = new Vector2(midX, midY);
  6199. var endPoint = new Vector2(endX, endY);
  6200. var arc = new Arc2(startPoint, midPoint, endPoint);
  6201. var increment = arc.angle.radians() / numberOfSegments;
  6202. if (arc.orientation === Orientation.CW)
  6203. increment *= -1;
  6204. var currentAngle = arc.startAngle.radians() + increment;
  6205. for (var i = 0; i < numberOfSegments; i++) {
  6206. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6207. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6208. this.addLineTo(x, y);
  6209. currentAngle += increment;
  6210. }
  6211. return this;
  6212. };
  6213. /**
  6214. * Closes the Path2.
  6215. * Returns the Path2.
  6216. */
  6217. Path2.prototype.close = function () {
  6218. this.closed = true;
  6219. return this;
  6220. };
  6221. /**
  6222. * Returns the Path2 total length (float).
  6223. */
  6224. Path2.prototype.length = function () {
  6225. var result = this._length;
  6226. if (!this.closed) {
  6227. var lastPoint = this._points[this._points.length - 1];
  6228. var firstPoint = this._points[0];
  6229. result += (firstPoint.subtract(lastPoint).length());
  6230. }
  6231. return result;
  6232. };
  6233. /**
  6234. * Returns the Path2 internal array of points.
  6235. */
  6236. Path2.prototype.getPoints = function () {
  6237. return this._points;
  6238. };
  6239. /**
  6240. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6241. */
  6242. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6243. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6244. //Tools.Error("normalized length position should be between 0 and 1.");
  6245. return Vector2.Zero();
  6246. }
  6247. var lengthPosition = normalizedLengthPosition * this.length();
  6248. var previousOffset = 0;
  6249. for (var i = 0; i < this._points.length; i++) {
  6250. var j = (i + 1) % this._points.length;
  6251. var a = this._points[i];
  6252. var b = this._points[j];
  6253. var bToA = b.subtract(a);
  6254. var nextOffset = (bToA.length() + previousOffset);
  6255. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6256. var dir = bToA.normalize();
  6257. var localOffset = lengthPosition - previousOffset;
  6258. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6259. }
  6260. previousOffset = nextOffset;
  6261. }
  6262. //Tools.Error("internal error");
  6263. return Vector2.Zero();
  6264. };
  6265. /**
  6266. * Returns a new Path2 starting at the coordinates (x, y).
  6267. */
  6268. Path2.StartingAt = function (x, y) {
  6269. return new Path2(x, y);
  6270. };
  6271. return Path2;
  6272. }());
  6273. BABYLON.Path2 = Path2;
  6274. var Path3D = /** @class */ (function () {
  6275. /**
  6276. * new Path3D(path, normal, raw)
  6277. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6278. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6279. * path : an array of Vector3, the curve axis of the Path3D
  6280. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6281. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6282. */
  6283. function Path3D(path, firstNormal, raw) {
  6284. if (firstNormal === void 0) { firstNormal = null; }
  6285. this.path = path;
  6286. this._curve = new Array();
  6287. this._distances = new Array();
  6288. this._tangents = new Array();
  6289. this._normals = new Array();
  6290. this._binormals = new Array();
  6291. for (var p = 0; p < path.length; p++) {
  6292. this._curve[p] = path[p].clone(); // hard copy
  6293. }
  6294. this._raw = raw || false;
  6295. this._compute(firstNormal);
  6296. }
  6297. /**
  6298. * Returns the Path3D array of successive Vector3 designing its curve.
  6299. */
  6300. Path3D.prototype.getCurve = function () {
  6301. return this._curve;
  6302. };
  6303. /**
  6304. * Returns an array populated with tangent vectors on each Path3D curve point.
  6305. */
  6306. Path3D.prototype.getTangents = function () {
  6307. return this._tangents;
  6308. };
  6309. /**
  6310. * Returns an array populated with normal vectors on each Path3D curve point.
  6311. */
  6312. Path3D.prototype.getNormals = function () {
  6313. return this._normals;
  6314. };
  6315. /**
  6316. * Returns an array populated with binormal vectors on each Path3D curve point.
  6317. */
  6318. Path3D.prototype.getBinormals = function () {
  6319. return this._binormals;
  6320. };
  6321. /**
  6322. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6323. */
  6324. Path3D.prototype.getDistances = function () {
  6325. return this._distances;
  6326. };
  6327. /**
  6328. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6329. * Returns the same object updated.
  6330. */
  6331. Path3D.prototype.update = function (path, firstNormal) {
  6332. if (firstNormal === void 0) { firstNormal = null; }
  6333. for (var p = 0; p < path.length; p++) {
  6334. this._curve[p].x = path[p].x;
  6335. this._curve[p].y = path[p].y;
  6336. this._curve[p].z = path[p].z;
  6337. }
  6338. this._compute(firstNormal);
  6339. return this;
  6340. };
  6341. // private function compute() : computes tangents, normals and binormals
  6342. Path3D.prototype._compute = function (firstNormal) {
  6343. var l = this._curve.length;
  6344. // first and last tangents
  6345. this._tangents[0] = this._getFirstNonNullVector(0);
  6346. if (!this._raw) {
  6347. this._tangents[0].normalize();
  6348. }
  6349. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6350. if (!this._raw) {
  6351. this._tangents[l - 1].normalize();
  6352. }
  6353. // normals and binormals at first point : arbitrary vector with _normalVector()
  6354. var tg0 = this._tangents[0];
  6355. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6356. this._normals[0] = pp0;
  6357. if (!this._raw) {
  6358. this._normals[0].normalize();
  6359. }
  6360. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6361. if (!this._raw) {
  6362. this._binormals[0].normalize();
  6363. }
  6364. this._distances[0] = 0.0;
  6365. // normals and binormals : next points
  6366. var prev; // previous vector (segment)
  6367. var cur; // current vector (segment)
  6368. var curTang; // current tangent
  6369. // previous normal
  6370. var prevBinor; // previous binormal
  6371. for (var i = 1; i < l; i++) {
  6372. // tangents
  6373. prev = this._getLastNonNullVector(i);
  6374. if (i < l - 1) {
  6375. cur = this._getFirstNonNullVector(i);
  6376. this._tangents[i] = prev.add(cur);
  6377. this._tangents[i].normalize();
  6378. }
  6379. this._distances[i] = this._distances[i - 1] + prev.length();
  6380. // normals and binormals
  6381. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6382. curTang = this._tangents[i];
  6383. prevBinor = this._binormals[i - 1];
  6384. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6385. if (!this._raw) {
  6386. this._normals[i].normalize();
  6387. }
  6388. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6389. if (!this._raw) {
  6390. this._binormals[i].normalize();
  6391. }
  6392. }
  6393. };
  6394. // private function getFirstNonNullVector(index)
  6395. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6396. Path3D.prototype._getFirstNonNullVector = function (index) {
  6397. var i = 1;
  6398. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6399. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6400. i++;
  6401. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6402. }
  6403. return nNVector;
  6404. };
  6405. // private function getLastNonNullVector(index)
  6406. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6407. Path3D.prototype._getLastNonNullVector = function (index) {
  6408. var i = 1;
  6409. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6410. while (nLVector.length() === 0 && index > i + 1) {
  6411. i++;
  6412. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6413. }
  6414. return nLVector;
  6415. };
  6416. // private function normalVector(v0, vt, va) :
  6417. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6418. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6419. Path3D.prototype._normalVector = function (v0, vt, va) {
  6420. var normal0;
  6421. var tgl = vt.length();
  6422. if (tgl === 0.0) {
  6423. tgl = 1.0;
  6424. }
  6425. if (va === undefined || va === null) {
  6426. var point;
  6427. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6428. point = new Vector3(0.0, -1.0, 0.0);
  6429. }
  6430. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6431. point = new Vector3(1.0, 0.0, 0.0);
  6432. }
  6433. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6434. point = new Vector3(0.0, 0.0, 1.0);
  6435. }
  6436. else {
  6437. point = Vector3.Zero();
  6438. }
  6439. normal0 = Vector3.Cross(vt, point);
  6440. }
  6441. else {
  6442. normal0 = Vector3.Cross(vt, va);
  6443. Vector3.CrossToRef(normal0, vt, normal0);
  6444. }
  6445. normal0.normalize();
  6446. return normal0;
  6447. };
  6448. return Path3D;
  6449. }());
  6450. BABYLON.Path3D = Path3D;
  6451. var Curve3 = /** @class */ (function () {
  6452. /**
  6453. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6454. * A Curve3 is designed from a series of successive Vector3.
  6455. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6456. */
  6457. function Curve3(points) {
  6458. this._length = 0.0;
  6459. this._points = points;
  6460. this._length = this._computeLength(points);
  6461. }
  6462. /**
  6463. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6464. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6465. * @param v1 (Vector3) the control point
  6466. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6467. * @param nbPoints (integer) the wanted number of points in the curve
  6468. */
  6469. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6470. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6471. var bez = new Array();
  6472. var equation = function (t, val0, val1, val2) {
  6473. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6474. return res;
  6475. };
  6476. for (var i = 0; i <= nbPoints; i++) {
  6477. 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)));
  6478. }
  6479. return new Curve3(bez);
  6480. };
  6481. /**
  6482. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6483. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6484. * @param v1 (Vector3) the first control point
  6485. * @param v2 (Vector3) the second control point
  6486. * @param v3 (Vector3) the end point of the Cubic Bezier
  6487. * @param nbPoints (integer) the wanted number of points in the curve
  6488. */
  6489. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6490. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6491. var bez = new Array();
  6492. var equation = function (t, val0, val1, val2, val3) {
  6493. 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;
  6494. return res;
  6495. };
  6496. for (var i = 0; i <= nbPoints; i++) {
  6497. 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)));
  6498. }
  6499. return new Curve3(bez);
  6500. };
  6501. /**
  6502. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6503. * @param p1 (Vector3) the origin point of the Hermite Spline
  6504. * @param t1 (Vector3) the tangent vector at the origin point
  6505. * @param p2 (Vector3) the end point of the Hermite Spline
  6506. * @param t2 (Vector3) the tangent vector at the end point
  6507. * @param nbPoints (integer) the wanted number of points in the curve
  6508. */
  6509. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6510. var hermite = new Array();
  6511. var step = 1.0 / nbPoints;
  6512. for (var i = 0; i <= nbPoints; i++) {
  6513. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6514. }
  6515. return new Curve3(hermite);
  6516. };
  6517. /**
  6518. * Returns a Curve3 object along a CatmullRom Spline curve :
  6519. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6520. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6521. */
  6522. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6523. var totalPoints = new Array();
  6524. totalPoints.push(points[0].clone());
  6525. Array.prototype.push.apply(totalPoints, points);
  6526. totalPoints.push(points[points.length - 1].clone());
  6527. var catmullRom = new Array();
  6528. var step = 1.0 / nbPoints;
  6529. var amount = 0.0;
  6530. for (var i = 0; i < totalPoints.length - 3; i++) {
  6531. amount = 0;
  6532. for (var c = 0; c < nbPoints; c++) {
  6533. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6534. amount += step;
  6535. }
  6536. }
  6537. i--;
  6538. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6539. return new Curve3(catmullRom);
  6540. };
  6541. /**
  6542. * Returns the Curve3 stored array of successive Vector3
  6543. */
  6544. Curve3.prototype.getPoints = function () {
  6545. return this._points;
  6546. };
  6547. /**
  6548. * Returns the computed length (float) of the curve.
  6549. */
  6550. Curve3.prototype.length = function () {
  6551. return this._length;
  6552. };
  6553. /**
  6554. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6555. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6556. * curveA and curveB keep unchanged.
  6557. */
  6558. Curve3.prototype.continue = function (curve) {
  6559. var lastPoint = this._points[this._points.length - 1];
  6560. var continuedPoints = this._points.slice();
  6561. var curvePoints = curve.getPoints();
  6562. for (var i = 1; i < curvePoints.length; i++) {
  6563. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6564. }
  6565. var continuedCurve = new Curve3(continuedPoints);
  6566. return continuedCurve;
  6567. };
  6568. Curve3.prototype._computeLength = function (path) {
  6569. var l = 0;
  6570. for (var i = 1; i < path.length; i++) {
  6571. l += (path[i].subtract(path[i - 1])).length();
  6572. }
  6573. return l;
  6574. };
  6575. return Curve3;
  6576. }());
  6577. BABYLON.Curve3 = Curve3;
  6578. // Vertex formats
  6579. var PositionNormalVertex = /** @class */ (function () {
  6580. function PositionNormalVertex(position, normal) {
  6581. if (position === void 0) { position = Vector3.Zero(); }
  6582. if (normal === void 0) { normal = Vector3.Up(); }
  6583. this.position = position;
  6584. this.normal = normal;
  6585. }
  6586. PositionNormalVertex.prototype.clone = function () {
  6587. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6588. };
  6589. return PositionNormalVertex;
  6590. }());
  6591. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6592. var PositionNormalTextureVertex = /** @class */ (function () {
  6593. function PositionNormalTextureVertex(position, normal, uv) {
  6594. if (position === void 0) { position = Vector3.Zero(); }
  6595. if (normal === void 0) { normal = Vector3.Up(); }
  6596. if (uv === void 0) { uv = Vector2.Zero(); }
  6597. this.position = position;
  6598. this.normal = normal;
  6599. this.uv = uv;
  6600. }
  6601. PositionNormalTextureVertex.prototype.clone = function () {
  6602. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6603. };
  6604. return PositionNormalTextureVertex;
  6605. }());
  6606. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6607. // Temporary pre-allocated objects for engine internal use
  6608. // usage in any internal function :
  6609. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6610. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6611. var Tmp = /** @class */ (function () {
  6612. function Tmp() {
  6613. }
  6614. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6615. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6616. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6617. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6618. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6619. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6620. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6621. Matrix.Zero(), Matrix.Zero(),
  6622. Matrix.Zero(), Matrix.Zero(),
  6623. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6624. return Tmp;
  6625. }());
  6626. BABYLON.Tmp = Tmp;
  6627. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6628. var MathTmp = /** @class */ (function () {
  6629. function MathTmp() {
  6630. }
  6631. MathTmp.Vector3 = [Vector3.Zero()];
  6632. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6633. MathTmp.Quaternion = [Quaternion.Zero()];
  6634. return MathTmp;
  6635. }());
  6636. })(BABYLON || (BABYLON = {}));
  6637. //# sourceMappingURL=babylon.math.js.map
  6638. var BABYLON;
  6639. (function (BABYLON) {
  6640. var Scalar = /** @class */ (function () {
  6641. function Scalar() {
  6642. }
  6643. /**
  6644. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6645. */
  6646. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6647. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6648. var num = a - b;
  6649. return -epsilon <= num && num <= epsilon;
  6650. };
  6651. /**
  6652. * Returns a string : the upper case translation of the number i to hexadecimal.
  6653. */
  6654. Scalar.ToHex = function (i) {
  6655. var str = i.toString(16);
  6656. if (i <= 15) {
  6657. return ("0" + str).toUpperCase();
  6658. }
  6659. return str.toUpperCase();
  6660. };
  6661. /**
  6662. * Returns -1 if value is negative and +1 is value is positive.
  6663. * Returns the value itself if it's equal to zero.
  6664. */
  6665. Scalar.Sign = function (value) {
  6666. value = +value; // convert to a number
  6667. if (value === 0 || isNaN(value))
  6668. return value;
  6669. return value > 0 ? 1 : -1;
  6670. };
  6671. /**
  6672. * Returns the value itself if it's between min and max.
  6673. * Returns min if the value is lower than min.
  6674. * Returns max if the value is greater than max.
  6675. */
  6676. Scalar.Clamp = function (value, min, max) {
  6677. if (min === void 0) { min = 0; }
  6678. if (max === void 0) { max = 1; }
  6679. return Math.min(max, Math.max(min, value));
  6680. };
  6681. /**
  6682. * Returns the log2 of value.
  6683. */
  6684. Scalar.Log2 = function (value) {
  6685. return Math.log(value) * Math.LOG2E;
  6686. };
  6687. /**
  6688. * Loops the value, so that it is never larger than length and never smaller than 0.
  6689. *
  6690. * This is similar to the modulo operator but it works with floating point numbers.
  6691. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6692. * With t = 5 and length = 2.5, the result would be 0.0.
  6693. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6694. */
  6695. Scalar.Repeat = function (value, length) {
  6696. return value - Math.floor(value / length) * length;
  6697. };
  6698. /**
  6699. * Normalize the value between 0.0 and 1.0 using min and max values
  6700. */
  6701. Scalar.Normalize = function (value, min, max) {
  6702. return (value - min) / (max - min);
  6703. };
  6704. /**
  6705. * Denormalize the value from 0.0 and 1.0 using min and max values
  6706. */
  6707. Scalar.Denormalize = function (normalized, min, max) {
  6708. return (normalized * (max - min) + min);
  6709. };
  6710. /**
  6711. * Calculates the shortest difference between two given angles given in degrees.
  6712. */
  6713. Scalar.DeltaAngle = function (current, target) {
  6714. var num = Scalar.Repeat(target - current, 360.0);
  6715. if (num > 180.0) {
  6716. num -= 360.0;
  6717. }
  6718. return num;
  6719. };
  6720. /**
  6721. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6722. *
  6723. * The returned value will move back and forth between 0 and length
  6724. */
  6725. Scalar.PingPong = function (tx, length) {
  6726. var t = Scalar.Repeat(tx, length * 2.0);
  6727. return length - Math.abs(t - length);
  6728. };
  6729. /**
  6730. * Interpolates between min and max with smoothing at the limits.
  6731. *
  6732. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6733. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6734. */
  6735. Scalar.SmoothStep = function (from, to, tx) {
  6736. var t = Scalar.Clamp(tx);
  6737. t = -2.0 * t * t * t + 3.0 * t * t;
  6738. return to * t + from * (1.0 - t);
  6739. };
  6740. /**
  6741. * Moves a value current towards target.
  6742. *
  6743. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6744. * Negative values of maxDelta pushes the value away from target.
  6745. */
  6746. Scalar.MoveTowards = function (current, target, maxDelta) {
  6747. var result = 0;
  6748. if (Math.abs(target - current) <= maxDelta) {
  6749. result = target;
  6750. }
  6751. else {
  6752. result = current + Scalar.Sign(target - current) * maxDelta;
  6753. }
  6754. return result;
  6755. };
  6756. /**
  6757. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6758. *
  6759. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6760. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6761. */
  6762. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6763. var num = Scalar.DeltaAngle(current, target);
  6764. var result = 0;
  6765. if (-maxDelta < num && num < maxDelta) {
  6766. result = target;
  6767. }
  6768. else {
  6769. target = current + num;
  6770. result = Scalar.MoveTowards(current, target, maxDelta);
  6771. }
  6772. return result;
  6773. };
  6774. /**
  6775. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6776. */
  6777. Scalar.Lerp = function (start, end, amount) {
  6778. return start + ((end - start) * amount);
  6779. };
  6780. /**
  6781. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6782. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6783. */
  6784. Scalar.LerpAngle = function (start, end, amount) {
  6785. var num = Scalar.Repeat(end - start, 360.0);
  6786. if (num > 180.0) {
  6787. num -= 360.0;
  6788. }
  6789. return start + num * Scalar.Clamp(amount);
  6790. };
  6791. /**
  6792. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6793. */
  6794. Scalar.InverseLerp = function (a, b, value) {
  6795. var result = 0;
  6796. if (a != b) {
  6797. result = Scalar.Clamp((value - a) / (b - a));
  6798. }
  6799. else {
  6800. result = 0.0;
  6801. }
  6802. return result;
  6803. };
  6804. /**
  6805. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6806. */
  6807. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6808. var squared = amount * amount;
  6809. var cubed = amount * squared;
  6810. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6811. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6812. var part3 = (cubed - (2.0 * squared)) + amount;
  6813. var part4 = cubed - squared;
  6814. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6815. };
  6816. /**
  6817. * Returns a random float number between and min and max values
  6818. */
  6819. Scalar.RandomRange = function (min, max) {
  6820. if (min === max)
  6821. return min;
  6822. return ((Math.random() * (max - min)) + min);
  6823. };
  6824. /**
  6825. * This function returns percentage of a number in a given range.
  6826. *
  6827. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6828. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6829. */
  6830. Scalar.RangeToPercent = function (number, min, max) {
  6831. return ((number - min) / (max - min));
  6832. };
  6833. /**
  6834. * This function returns number that corresponds to the percentage in a given range.
  6835. *
  6836. * PercentToRange(0.34,0,100) will return 34.
  6837. */
  6838. Scalar.PercentToRange = function (percent, min, max) {
  6839. return ((max - min) * percent + min);
  6840. };
  6841. /**
  6842. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6843. * @param angle The angle to normalize in radian.
  6844. * @return The converted angle.
  6845. */
  6846. Scalar.NormalizeRadians = function (angle) {
  6847. // More precise but slower version kept for reference.
  6848. // angle = angle % Tools.TwoPi;
  6849. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6850. //if (angle > Math.PI) {
  6851. // angle -= Tools.TwoPi;
  6852. //}
  6853. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6854. return angle;
  6855. };
  6856. /**
  6857. * Two pi constants convenient for computation.
  6858. */
  6859. Scalar.TwoPi = Math.PI * 2;
  6860. return Scalar;
  6861. }());
  6862. BABYLON.Scalar = Scalar;
  6863. })(BABYLON || (BABYLON = {}));
  6864. //# sourceMappingURL=babylon.math.scalar.js.map
  6865. //# sourceMappingURL=babylon.mixins.js.map
  6866. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6867. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6868. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6869. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6870. //# sourceMappingURL=babylon.webgl2.js.map
  6871. var BABYLON;
  6872. (function (BABYLON) {
  6873. var __decoratorInitialStore = {};
  6874. var __mergedStore = {};
  6875. var _copySource = function (creationFunction, source, instanciate) {
  6876. var destination = creationFunction();
  6877. // Tags
  6878. if (BABYLON.Tags) {
  6879. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6880. }
  6881. var classStore = getMergedStore(destination);
  6882. // Properties
  6883. for (var property in classStore) {
  6884. var propertyDescriptor = classStore[property];
  6885. var sourceProperty = source[property];
  6886. var propertyType = propertyDescriptor.type;
  6887. if (sourceProperty !== undefined && sourceProperty !== null) {
  6888. switch (propertyType) {
  6889. case 0: // Value
  6890. case 6:// Mesh reference
  6891. destination[property] = sourceProperty;
  6892. break;
  6893. case 1:// Texture
  6894. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6895. break;
  6896. case 2: // Color3
  6897. case 3: // FresnelParameters
  6898. case 4: // Vector2
  6899. case 5: // Vector3
  6900. case 7: // Color Curves
  6901. case 10:// Quaternion
  6902. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6903. break;
  6904. }
  6905. }
  6906. }
  6907. return destination;
  6908. };
  6909. function getDirectStore(target) {
  6910. var classKey = target.getClassName();
  6911. if (!__decoratorInitialStore[classKey]) {
  6912. __decoratorInitialStore[classKey] = {};
  6913. }
  6914. return __decoratorInitialStore[classKey];
  6915. }
  6916. /**
  6917. * Return the list of properties flagged as serializable
  6918. * @param target: host object
  6919. */
  6920. function getMergedStore(target) {
  6921. var classKey = target.getClassName();
  6922. if (__mergedStore[classKey]) {
  6923. return __mergedStore[classKey];
  6924. }
  6925. __mergedStore[classKey] = {};
  6926. var store = __mergedStore[classKey];
  6927. var currentTarget = target;
  6928. var currentKey = classKey;
  6929. while (currentKey) {
  6930. var initialStore = __decoratorInitialStore[currentKey];
  6931. for (var property in initialStore) {
  6932. store[property] = initialStore[property];
  6933. }
  6934. var parent_1 = void 0;
  6935. var done = false;
  6936. do {
  6937. parent_1 = Object.getPrototypeOf(currentTarget);
  6938. if (!parent_1.getClassName) {
  6939. done = true;
  6940. break;
  6941. }
  6942. if (parent_1.getClassName() !== currentKey) {
  6943. break;
  6944. }
  6945. currentTarget = parent_1;
  6946. } while (parent_1);
  6947. if (done) {
  6948. break;
  6949. }
  6950. currentKey = parent_1.getClassName();
  6951. currentTarget = parent_1;
  6952. }
  6953. return store;
  6954. }
  6955. function generateSerializableMember(type, sourceName) {
  6956. return function (target, propertyKey) {
  6957. var classStore = getDirectStore(target);
  6958. if (!classStore[propertyKey]) {
  6959. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6960. }
  6961. };
  6962. }
  6963. function generateExpandMember(setCallback, targetKey) {
  6964. if (targetKey === void 0) { targetKey = null; }
  6965. return function (target, propertyKey) {
  6966. var key = targetKey || ("_" + propertyKey);
  6967. Object.defineProperty(target, propertyKey, {
  6968. get: function () {
  6969. return this[key];
  6970. },
  6971. set: function (value) {
  6972. if (this[key] === value) {
  6973. return;
  6974. }
  6975. this[key] = value;
  6976. target[setCallback].apply(this);
  6977. },
  6978. enumerable: true,
  6979. configurable: true
  6980. });
  6981. };
  6982. }
  6983. function expandToProperty(callback, targetKey) {
  6984. if (targetKey === void 0) { targetKey = null; }
  6985. return generateExpandMember(callback, targetKey);
  6986. }
  6987. BABYLON.expandToProperty = expandToProperty;
  6988. function serialize(sourceName) {
  6989. return generateSerializableMember(0, sourceName); // value member
  6990. }
  6991. BABYLON.serialize = serialize;
  6992. function serializeAsTexture(sourceName) {
  6993. return generateSerializableMember(1, sourceName); // texture member
  6994. }
  6995. BABYLON.serializeAsTexture = serializeAsTexture;
  6996. function serializeAsColor3(sourceName) {
  6997. return generateSerializableMember(2, sourceName); // color3 member
  6998. }
  6999. BABYLON.serializeAsColor3 = serializeAsColor3;
  7000. function serializeAsFresnelParameters(sourceName) {
  7001. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7002. }
  7003. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7004. function serializeAsVector2(sourceName) {
  7005. return generateSerializableMember(4, sourceName); // vector2 member
  7006. }
  7007. BABYLON.serializeAsVector2 = serializeAsVector2;
  7008. function serializeAsVector3(sourceName) {
  7009. return generateSerializableMember(5, sourceName); // vector3 member
  7010. }
  7011. BABYLON.serializeAsVector3 = serializeAsVector3;
  7012. function serializeAsMeshReference(sourceName) {
  7013. return generateSerializableMember(6, sourceName); // mesh reference member
  7014. }
  7015. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7016. function serializeAsColorCurves(sourceName) {
  7017. return generateSerializableMember(7, sourceName); // color curves
  7018. }
  7019. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7020. function serializeAsColor4(sourceName) {
  7021. return generateSerializableMember(8, sourceName); // color 4
  7022. }
  7023. BABYLON.serializeAsColor4 = serializeAsColor4;
  7024. function serializeAsImageProcessingConfiguration(sourceName) {
  7025. return generateSerializableMember(9, sourceName); // image processing
  7026. }
  7027. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7028. function serializeAsQuaternion(sourceName) {
  7029. return generateSerializableMember(10, sourceName); // quaternion member
  7030. }
  7031. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7032. var SerializationHelper = /** @class */ (function () {
  7033. function SerializationHelper() {
  7034. }
  7035. SerializationHelper.Serialize = function (entity, serializationObject) {
  7036. if (!serializationObject) {
  7037. serializationObject = {};
  7038. }
  7039. // Tags
  7040. if (BABYLON.Tags) {
  7041. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7042. }
  7043. var serializedProperties = getMergedStore(entity);
  7044. // Properties
  7045. for (var property in serializedProperties) {
  7046. var propertyDescriptor = serializedProperties[property];
  7047. var targetPropertyName = propertyDescriptor.sourceName || property;
  7048. var propertyType = propertyDescriptor.type;
  7049. var sourceProperty = entity[property];
  7050. if (sourceProperty !== undefined && sourceProperty !== null) {
  7051. switch (propertyType) {
  7052. case 0:// Value
  7053. serializationObject[targetPropertyName] = sourceProperty;
  7054. break;
  7055. case 1:// Texture
  7056. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7057. break;
  7058. case 2:// Color3
  7059. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7060. break;
  7061. case 3:// FresnelParameters
  7062. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7063. break;
  7064. case 4:// Vector2
  7065. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7066. break;
  7067. case 5:// Vector3
  7068. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7069. break;
  7070. case 6:// Mesh reference
  7071. serializationObject[targetPropertyName] = sourceProperty.id;
  7072. break;
  7073. case 7:// Color Curves
  7074. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7075. break;
  7076. case 8:// Color 4
  7077. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7078. break;
  7079. case 9:// Image Processing
  7080. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7081. break;
  7082. }
  7083. }
  7084. }
  7085. return serializationObject;
  7086. };
  7087. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7088. if (rootUrl === void 0) { rootUrl = null; }
  7089. var destination = creationFunction();
  7090. if (!rootUrl) {
  7091. rootUrl = "";
  7092. }
  7093. // Tags
  7094. if (BABYLON.Tags) {
  7095. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7096. }
  7097. var classStore = getMergedStore(destination);
  7098. // Properties
  7099. for (var property in classStore) {
  7100. var propertyDescriptor = classStore[property];
  7101. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7102. var propertyType = propertyDescriptor.type;
  7103. if (sourceProperty !== undefined && sourceProperty !== null) {
  7104. var dest = destination;
  7105. switch (propertyType) {
  7106. case 0:// Value
  7107. dest[property] = sourceProperty;
  7108. break;
  7109. case 1:// Texture
  7110. if (scene) {
  7111. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7112. }
  7113. break;
  7114. case 2:// Color3
  7115. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7116. break;
  7117. case 3:// FresnelParameters
  7118. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7119. break;
  7120. case 4:// Vector2
  7121. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7122. break;
  7123. case 5:// Vector3
  7124. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7125. break;
  7126. case 6:// Mesh reference
  7127. if (scene) {
  7128. dest[property] = scene.getLastMeshByID(sourceProperty);
  7129. }
  7130. break;
  7131. case 7:// Color Curves
  7132. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7133. break;
  7134. case 8:// Color 4
  7135. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7136. break;
  7137. case 9:// Image Processing
  7138. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7139. break;
  7140. }
  7141. }
  7142. }
  7143. return destination;
  7144. };
  7145. SerializationHelper.Clone = function (creationFunction, source) {
  7146. return _copySource(creationFunction, source, false);
  7147. };
  7148. SerializationHelper.Instanciate = function (creationFunction, source) {
  7149. return _copySource(creationFunction, source, true);
  7150. };
  7151. return SerializationHelper;
  7152. }());
  7153. BABYLON.SerializationHelper = SerializationHelper;
  7154. })(BABYLON || (BABYLON = {}));
  7155. //# sourceMappingURL=babylon.decorators.js.map
  7156. var BABYLON;
  7157. (function (BABYLON) {
  7158. /**
  7159. * Wrapper class for promise with external resolve and reject.
  7160. */
  7161. var Deferred = /** @class */ (function () {
  7162. /**
  7163. * Constructor for this deferred object.
  7164. */
  7165. function Deferred() {
  7166. var _this = this;
  7167. this.promise = new Promise(function (resolve, reject) {
  7168. _this._resolve = resolve;
  7169. _this._reject = reject;
  7170. });
  7171. }
  7172. Object.defineProperty(Deferred.prototype, "resolve", {
  7173. /**
  7174. * The resolve method of the promise associated with this deferred object.
  7175. */
  7176. get: function () {
  7177. return this._resolve;
  7178. },
  7179. enumerable: true,
  7180. configurable: true
  7181. });
  7182. Object.defineProperty(Deferred.prototype, "reject", {
  7183. /**
  7184. * The reject method of the promise associated with this deferred object.
  7185. */
  7186. get: function () {
  7187. return this._reject;
  7188. },
  7189. enumerable: true,
  7190. configurable: true
  7191. });
  7192. return Deferred;
  7193. }());
  7194. BABYLON.Deferred = Deferred;
  7195. })(BABYLON || (BABYLON = {}));
  7196. //# sourceMappingURL=babylon.deferred.js.map
  7197. var BABYLON;
  7198. (function (BABYLON) {
  7199. /**
  7200. * A class serves as a medium between the observable and its observers
  7201. */
  7202. var EventState = /** @class */ (function () {
  7203. /**
  7204. * Create a new EventState
  7205. * @param mask defines the mask associated with this state
  7206. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7207. * @param target defines the original target of the state
  7208. * @param currentTarget defines the current target of the state
  7209. */
  7210. function EventState(mask, skipNextObservers, target, currentTarget) {
  7211. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7212. this.initalize(mask, skipNextObservers, target, currentTarget);
  7213. }
  7214. /**
  7215. * Initialize the current event state
  7216. * @param mask defines the mask associated with this state
  7217. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7218. * @param target defines the original target of the state
  7219. * @param currentTarget defines the current target of the state
  7220. * @returns the current event state
  7221. */
  7222. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7223. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7224. this.mask = mask;
  7225. this.skipNextObservers = skipNextObservers;
  7226. this.target = target;
  7227. this.currentTarget = currentTarget;
  7228. return this;
  7229. };
  7230. return EventState;
  7231. }());
  7232. BABYLON.EventState = EventState;
  7233. /**
  7234. * Represent an Observer registered to a given Observable object.
  7235. */
  7236. var Observer = /** @class */ (function () {
  7237. /**
  7238. * Creates a new observer
  7239. * @param callback defines the callback to call when the observer is notified
  7240. * @param mask defines the mask of the observer (used to filter notifications)
  7241. * @param scope defines the current scope used to restore the JS context
  7242. */
  7243. function Observer(
  7244. /**
  7245. * Defines the callback to call when the observer is notified
  7246. */
  7247. callback,
  7248. /**
  7249. * Defines the mask of the observer (used to filter notifications)
  7250. */
  7251. mask,
  7252. /**
  7253. * Defines the current scope used to restore the JS context
  7254. */
  7255. scope) {
  7256. if (scope === void 0) { scope = null; }
  7257. this.callback = callback;
  7258. this.mask = mask;
  7259. this.scope = scope;
  7260. /** @ignore */
  7261. this._willBeUnregistered = false;
  7262. /**
  7263. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7264. */
  7265. this.unregisterOnNextCall = false;
  7266. }
  7267. return Observer;
  7268. }());
  7269. BABYLON.Observer = Observer;
  7270. /**
  7271. * Represent a list of observers registered to multiple Observables object.
  7272. */
  7273. var MultiObserver = /** @class */ (function () {
  7274. function MultiObserver() {
  7275. }
  7276. /**
  7277. * Release associated resources
  7278. */
  7279. MultiObserver.prototype.dispose = function () {
  7280. if (this._observers && this._observables) {
  7281. for (var index = 0; index < this._observers.length; index++) {
  7282. this._observables[index].remove(this._observers[index]);
  7283. }
  7284. }
  7285. this._observers = null;
  7286. this._observables = null;
  7287. };
  7288. /**
  7289. * Raise a callback when one of the observable will notify
  7290. * @param observables defines a list of observables to watch
  7291. * @param callback defines the callback to call on notification
  7292. * @param mask defines the mask used to filter notifications
  7293. * @param scope defines the current scope used to restore the JS context
  7294. * @returns the new MultiObserver
  7295. */
  7296. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7297. if (mask === void 0) { mask = -1; }
  7298. if (scope === void 0) { scope = null; }
  7299. var result = new MultiObserver();
  7300. result._observers = new Array();
  7301. result._observables = observables;
  7302. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7303. var observable = observables_1[_i];
  7304. var observer = observable.add(callback, mask, false, scope);
  7305. if (observer) {
  7306. result._observers.push(observer);
  7307. }
  7308. }
  7309. return result;
  7310. };
  7311. return MultiObserver;
  7312. }());
  7313. BABYLON.MultiObserver = MultiObserver;
  7314. /**
  7315. * The Observable class is a simple implementation of the Observable pattern.
  7316. * 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.
  7317. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7318. * 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).
  7319. * 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.
  7320. */
  7321. var Observable = /** @class */ (function () {
  7322. /**
  7323. * Creates a new observable
  7324. * @param onObserverAdded defines a callback to call when a new observer is added
  7325. */
  7326. function Observable(onObserverAdded) {
  7327. this._observers = new Array();
  7328. this._eventState = new EventState(0);
  7329. if (onObserverAdded) {
  7330. this._onObserverAdded = onObserverAdded;
  7331. }
  7332. }
  7333. /**
  7334. * Create a new Observer with the specified callback
  7335. * @param callback the callback that will be executed for that Observer
  7336. * @param mask the mask used to filter observers
  7337. * @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.
  7338. * @param scope optional scope for the callback to be called from
  7339. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7340. * @returns the new observer created for the callback
  7341. */
  7342. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7343. if (mask === void 0) { mask = -1; }
  7344. if (insertFirst === void 0) { insertFirst = false; }
  7345. if (scope === void 0) { scope = null; }
  7346. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7347. if (!callback) {
  7348. return null;
  7349. }
  7350. var observer = new Observer(callback, mask, scope);
  7351. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7352. if (insertFirst) {
  7353. this._observers.unshift(observer);
  7354. }
  7355. else {
  7356. this._observers.push(observer);
  7357. }
  7358. if (this._onObserverAdded) {
  7359. this._onObserverAdded(observer);
  7360. }
  7361. return observer;
  7362. };
  7363. /**
  7364. * Remove an Observer from the Observable object
  7365. * @param observer the instance of the Observer to remove
  7366. * @returns false if it doesn't belong to this Observable
  7367. */
  7368. Observable.prototype.remove = function (observer) {
  7369. if (!observer) {
  7370. return false;
  7371. }
  7372. var index = this._observers.indexOf(observer);
  7373. if (index !== -1) {
  7374. this._observers.splice(index, 1);
  7375. return true;
  7376. }
  7377. return false;
  7378. };
  7379. /**
  7380. * Remove a callback from the Observable object
  7381. * @param callback the callback to remove
  7382. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7383. * @returns false if it doesn't belong to this Observable
  7384. */
  7385. Observable.prototype.removeCallback = function (callback, scope) {
  7386. for (var index = 0; index < this._observers.length; index++) {
  7387. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7388. this._observers.splice(index, 1);
  7389. return true;
  7390. }
  7391. }
  7392. return false;
  7393. };
  7394. Observable.prototype._deferUnregister = function (observer) {
  7395. var _this = this;
  7396. observer.unregisterOnNextCall = false;
  7397. observer._willBeUnregistered = true;
  7398. BABYLON.Tools.SetImmediate(function () {
  7399. _this.remove(observer);
  7400. });
  7401. };
  7402. /**
  7403. * Notify all Observers by calling their respective callback with the given data
  7404. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7405. * @param eventData defines the data to send to all observers
  7406. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7407. * @param target defines the original target of the state
  7408. * @param currentTarget defines the current target of the state
  7409. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7410. */
  7411. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7412. if (mask === void 0) { mask = -1; }
  7413. if (!this._observers.length) {
  7414. return true;
  7415. }
  7416. var state = this._eventState;
  7417. state.mask = mask;
  7418. state.target = target;
  7419. state.currentTarget = currentTarget;
  7420. state.skipNextObservers = false;
  7421. state.lastReturnValue = eventData;
  7422. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7423. var obs = _a[_i];
  7424. if (obs._willBeUnregistered) {
  7425. continue;
  7426. }
  7427. if (obs.mask & mask) {
  7428. if (obs.scope) {
  7429. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7430. }
  7431. else {
  7432. state.lastReturnValue = obs.callback(eventData, state);
  7433. }
  7434. if (obs.unregisterOnNextCall) {
  7435. this._deferUnregister(obs);
  7436. }
  7437. }
  7438. if (state.skipNextObservers) {
  7439. return false;
  7440. }
  7441. }
  7442. return true;
  7443. };
  7444. /**
  7445. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7446. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7447. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7448. * and it is crucial that all callbacks will be executed.
  7449. * The order of the callbacks is kept, callbacks are not executed parallel.
  7450. *
  7451. * @param eventData The data to be sent to each callback
  7452. * @param mask is used to filter observers defaults to -1
  7453. * @param target defines the callback target (see EventState)
  7454. * @param currentTarget defines he current object in the bubbling phase
  7455. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7456. */
  7457. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7458. var _this = this;
  7459. if (mask === void 0) { mask = -1; }
  7460. // create an empty promise
  7461. var p = Promise.resolve(eventData);
  7462. // no observers? return this promise.
  7463. if (!this._observers.length) {
  7464. return p;
  7465. }
  7466. var state = this._eventState;
  7467. state.mask = mask;
  7468. state.target = target;
  7469. state.currentTarget = currentTarget;
  7470. state.skipNextObservers = false;
  7471. // execute one callback after another (not using Promise.all, the order is important)
  7472. this._observers.forEach(function (obs) {
  7473. if (state.skipNextObservers) {
  7474. return;
  7475. }
  7476. if (obs._willBeUnregistered) {
  7477. return;
  7478. }
  7479. if (obs.mask & mask) {
  7480. if (obs.scope) {
  7481. p = p.then(function (lastReturnedValue) {
  7482. state.lastReturnValue = lastReturnedValue;
  7483. return obs.callback.apply(obs.scope, [eventData, state]);
  7484. });
  7485. }
  7486. else {
  7487. p = p.then(function (lastReturnedValue) {
  7488. state.lastReturnValue = lastReturnedValue;
  7489. return obs.callback(eventData, state);
  7490. });
  7491. }
  7492. if (obs.unregisterOnNextCall) {
  7493. _this._deferUnregister(obs);
  7494. }
  7495. }
  7496. });
  7497. // return the eventData
  7498. return p.then(function () { return eventData; });
  7499. };
  7500. /**
  7501. * Notify a specific observer
  7502. * @param observer defines the observer to notify
  7503. * @param eventData defines the data to be sent to each callback
  7504. * @param mask is used to filter observers defaults to -1
  7505. */
  7506. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7507. if (mask === void 0) { mask = -1; }
  7508. var state = this._eventState;
  7509. state.mask = mask;
  7510. state.skipNextObservers = false;
  7511. observer.callback(eventData, state);
  7512. };
  7513. /**
  7514. * Gets a boolean indicating if the observable has at least one observer
  7515. * @returns true is the Observable has at least one Observer registered
  7516. */
  7517. Observable.prototype.hasObservers = function () {
  7518. return this._observers.length > 0;
  7519. };
  7520. /**
  7521. * Clear the list of observers
  7522. */
  7523. Observable.prototype.clear = function () {
  7524. this._observers = new Array();
  7525. this._onObserverAdded = null;
  7526. };
  7527. /**
  7528. * Clone the current observable
  7529. * @returns a new observable
  7530. */
  7531. Observable.prototype.clone = function () {
  7532. var result = new Observable();
  7533. result._observers = this._observers.slice(0);
  7534. return result;
  7535. };
  7536. /**
  7537. * Does this observable handles observer registered with a given mask
  7538. * @param mask defines the mask to be tested
  7539. * @return whether or not one observer registered with the given mask is handeled
  7540. **/
  7541. Observable.prototype.hasSpecificMask = function (mask) {
  7542. if (mask === void 0) { mask = -1; }
  7543. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7544. var obs = _a[_i];
  7545. if (obs.mask & mask || obs.mask === mask) {
  7546. return true;
  7547. }
  7548. }
  7549. return false;
  7550. };
  7551. return Observable;
  7552. }());
  7553. BABYLON.Observable = Observable;
  7554. })(BABYLON || (BABYLON = {}));
  7555. //# sourceMappingURL=babylon.observable.js.map
  7556. var BABYLON;
  7557. (function (BABYLON) {
  7558. var SmartArray = /** @class */ (function () {
  7559. function SmartArray(capacity) {
  7560. this.length = 0;
  7561. this.data = new Array(capacity);
  7562. this._id = SmartArray._GlobalId++;
  7563. }
  7564. SmartArray.prototype.push = function (value) {
  7565. this.data[this.length++] = value;
  7566. if (this.length > this.data.length) {
  7567. this.data.length *= 2;
  7568. }
  7569. };
  7570. SmartArray.prototype.forEach = function (func) {
  7571. for (var index = 0; index < this.length; index++) {
  7572. func(this.data[index]);
  7573. }
  7574. };
  7575. SmartArray.prototype.sort = function (compareFn) {
  7576. this.data.sort(compareFn);
  7577. };
  7578. SmartArray.prototype.reset = function () {
  7579. this.length = 0;
  7580. };
  7581. SmartArray.prototype.dispose = function () {
  7582. this.reset();
  7583. if (this.data) {
  7584. this.data.length = 0;
  7585. this.data = [];
  7586. }
  7587. };
  7588. SmartArray.prototype.concat = function (array) {
  7589. if (array.length === 0) {
  7590. return;
  7591. }
  7592. if (this.length + array.length > this.data.length) {
  7593. this.data.length = (this.length + array.length) * 2;
  7594. }
  7595. for (var index = 0; index < array.length; index++) {
  7596. this.data[this.length++] = (array.data || array)[index];
  7597. }
  7598. };
  7599. SmartArray.prototype.indexOf = function (value) {
  7600. var position = this.data.indexOf(value);
  7601. if (position >= this.length) {
  7602. return -1;
  7603. }
  7604. return position;
  7605. };
  7606. SmartArray.prototype.contains = function (value) {
  7607. return this.data.indexOf(value) !== -1;
  7608. };
  7609. // Statics
  7610. SmartArray._GlobalId = 0;
  7611. return SmartArray;
  7612. }());
  7613. BABYLON.SmartArray = SmartArray;
  7614. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7615. __extends(SmartArrayNoDuplicate, _super);
  7616. function SmartArrayNoDuplicate() {
  7617. var _this = _super !== null && _super.apply(this, arguments) || this;
  7618. _this._duplicateId = 0;
  7619. return _this;
  7620. }
  7621. SmartArrayNoDuplicate.prototype.push = function (value) {
  7622. _super.prototype.push.call(this, value);
  7623. if (!value.__smartArrayFlags) {
  7624. value.__smartArrayFlags = {};
  7625. }
  7626. value.__smartArrayFlags[this._id] = this._duplicateId;
  7627. };
  7628. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7629. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7630. return false;
  7631. }
  7632. this.push(value);
  7633. return true;
  7634. };
  7635. SmartArrayNoDuplicate.prototype.reset = function () {
  7636. _super.prototype.reset.call(this);
  7637. this._duplicateId++;
  7638. };
  7639. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7640. if (array.length === 0) {
  7641. return;
  7642. }
  7643. if (this.length + array.length > this.data.length) {
  7644. this.data.length = (this.length + array.length) * 2;
  7645. }
  7646. for (var index = 0; index < array.length; index++) {
  7647. var item = (array.data || array)[index];
  7648. this.pushNoDuplicate(item);
  7649. }
  7650. };
  7651. return SmartArrayNoDuplicate;
  7652. }(SmartArray));
  7653. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7654. })(BABYLON || (BABYLON = {}));
  7655. //# sourceMappingURL=babylon.smartArray.js.map
  7656. var BABYLON;
  7657. (function (BABYLON) {
  7658. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7659. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7660. var LoadFileError = /** @class */ (function (_super) {
  7661. __extends(LoadFileError, _super);
  7662. function LoadFileError(message, request) {
  7663. var _this = _super.call(this, message) || this;
  7664. _this.request = request;
  7665. _this.name = "LoadFileError";
  7666. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7667. return _this;
  7668. }
  7669. // Polyfill for Object.setPrototypeOf if necessary.
  7670. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7671. return LoadFileError;
  7672. }(Error));
  7673. BABYLON.LoadFileError = LoadFileError;
  7674. var RetryStrategy = /** @class */ (function () {
  7675. function RetryStrategy() {
  7676. }
  7677. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7678. if (maxRetries === void 0) { maxRetries = 3; }
  7679. if (baseInterval === void 0) { baseInterval = 500; }
  7680. return function (url, request, retryIndex) {
  7681. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7682. return -1;
  7683. }
  7684. return Math.pow(2, retryIndex) * baseInterval;
  7685. };
  7686. };
  7687. return RetryStrategy;
  7688. }());
  7689. BABYLON.RetryStrategy = RetryStrategy;
  7690. // Screenshots
  7691. var screenshotCanvas;
  7692. var cloneValue = function (source, destinationObject) {
  7693. if (!source)
  7694. return null;
  7695. if (source instanceof BABYLON.Mesh) {
  7696. return null;
  7697. }
  7698. if (source instanceof BABYLON.SubMesh) {
  7699. return source.clone(destinationObject);
  7700. }
  7701. else if (source.clone) {
  7702. return source.clone();
  7703. }
  7704. return null;
  7705. };
  7706. var Tools = /** @class */ (function () {
  7707. function Tools() {
  7708. }
  7709. /**
  7710. * Interpolates between a and b via alpha
  7711. * @param a The lower value (returned when alpha = 0)
  7712. * @param b The upper value (returned when alpha = 1)
  7713. * @param alpha The interpolation-factor
  7714. * @return The mixed value
  7715. */
  7716. Tools.Mix = function (a, b, alpha) {
  7717. return a * (1 - alpha) + b * alpha;
  7718. };
  7719. Tools.Instantiate = function (className) {
  7720. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7721. return Tools.RegisteredExternalClasses[className];
  7722. }
  7723. var arr = className.split(".");
  7724. var fn = (window || this);
  7725. for (var i = 0, len = arr.length; i < len; i++) {
  7726. fn = fn[arr[i]];
  7727. }
  7728. if (typeof fn !== "function") {
  7729. return null;
  7730. }
  7731. return fn;
  7732. };
  7733. /**
  7734. * Provides a slice function that will work even on IE
  7735. * @param data defines the array to slice
  7736. * @returns the new sliced array
  7737. */
  7738. Tools.Slice = function (data) {
  7739. if (data.slice) {
  7740. return data.slice();
  7741. }
  7742. return Array.prototype.slice.call(data);
  7743. };
  7744. Tools.SetImmediate = function (action) {
  7745. if (window.setImmediate) {
  7746. window.setImmediate(action);
  7747. }
  7748. else {
  7749. setTimeout(action, 1);
  7750. }
  7751. };
  7752. Tools.IsExponentOfTwo = function (value) {
  7753. var count = 1;
  7754. do {
  7755. count *= 2;
  7756. } while (count < value);
  7757. return count === value;
  7758. };
  7759. /**
  7760. * Find the next highest power of two.
  7761. * @param x Number to start search from.
  7762. * @return Next highest power of two.
  7763. */
  7764. Tools.CeilingPOT = function (x) {
  7765. x--;
  7766. x |= x >> 1;
  7767. x |= x >> 2;
  7768. x |= x >> 4;
  7769. x |= x >> 8;
  7770. x |= x >> 16;
  7771. x++;
  7772. return x;
  7773. };
  7774. /**
  7775. * Find the next lowest power of two.
  7776. * @param x Number to start search from.
  7777. * @return Next lowest power of two.
  7778. */
  7779. Tools.FloorPOT = function (x) {
  7780. x = x | (x >> 1);
  7781. x = x | (x >> 2);
  7782. x = x | (x >> 4);
  7783. x = x | (x >> 8);
  7784. x = x | (x >> 16);
  7785. return x - (x >> 1);
  7786. };
  7787. /**
  7788. * Find the nearest power of two.
  7789. * @param x Number to start search from.
  7790. * @return Next nearest power of two.
  7791. */
  7792. Tools.NearestPOT = function (x) {
  7793. var c = Tools.CeilingPOT(x);
  7794. var f = Tools.FloorPOT(x);
  7795. return (c - x) > (x - f) ? f : c;
  7796. };
  7797. Tools.GetExponentOfTwo = function (value, max, mode) {
  7798. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7799. var pot;
  7800. switch (mode) {
  7801. case BABYLON.Engine.SCALEMODE_FLOOR:
  7802. pot = Tools.FloorPOT(value);
  7803. break;
  7804. case BABYLON.Engine.SCALEMODE_NEAREST:
  7805. pot = Tools.NearestPOT(value);
  7806. break;
  7807. case BABYLON.Engine.SCALEMODE_CEILING:
  7808. default:
  7809. pot = Tools.CeilingPOT(value);
  7810. break;
  7811. }
  7812. return Math.min(pot, max);
  7813. };
  7814. Tools.GetFilename = function (path) {
  7815. var index = path.lastIndexOf("/");
  7816. if (index < 0)
  7817. return path;
  7818. return path.substring(index + 1);
  7819. };
  7820. /**
  7821. * Extracts the "folder" part of a path (everything before the filename).
  7822. * @param uri The URI to extract the info from
  7823. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7824. * @returns The "folder" part of the path
  7825. */
  7826. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7827. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7828. var index = uri.lastIndexOf("/");
  7829. if (index < 0) {
  7830. if (returnUnchangedIfNoSlash) {
  7831. return uri;
  7832. }
  7833. return "";
  7834. }
  7835. return uri.substring(0, index + 1);
  7836. };
  7837. Tools.GetDOMTextContent = function (element) {
  7838. var result = "";
  7839. var child = element.firstChild;
  7840. while (child) {
  7841. if (child.nodeType === 3) {
  7842. result += child.textContent;
  7843. }
  7844. child = child.nextSibling;
  7845. }
  7846. return result;
  7847. };
  7848. Tools.ToDegrees = function (angle) {
  7849. return angle * 180 / Math.PI;
  7850. };
  7851. Tools.ToRadians = function (angle) {
  7852. return angle * Math.PI / 180;
  7853. };
  7854. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7855. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7856. var output = "";
  7857. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7858. var i = 0;
  7859. var bytes = new Uint8Array(buffer);
  7860. while (i < bytes.length) {
  7861. chr1 = bytes[i++];
  7862. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7863. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7864. enc1 = chr1 >> 2;
  7865. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7866. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7867. enc4 = chr3 & 63;
  7868. if (isNaN(chr2)) {
  7869. enc3 = enc4 = 64;
  7870. }
  7871. else if (isNaN(chr3)) {
  7872. enc4 = 64;
  7873. }
  7874. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7875. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7876. }
  7877. return "data:image/png;base64," + output;
  7878. };
  7879. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7880. if (bias === void 0) { bias = null; }
  7881. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7882. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7883. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7884. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7885. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7886. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7887. }
  7888. if (bias) {
  7889. minimum.x -= minimum.x * bias.x + bias.y;
  7890. minimum.y -= minimum.y * bias.x + bias.y;
  7891. minimum.z -= minimum.z * bias.x + bias.y;
  7892. maximum.x += maximum.x * bias.x + bias.y;
  7893. maximum.y += maximum.y * bias.x + bias.y;
  7894. maximum.z += maximum.z * bias.x + bias.y;
  7895. }
  7896. return {
  7897. minimum: minimum,
  7898. maximum: maximum
  7899. };
  7900. };
  7901. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7902. if (bias === void 0) { bias = null; }
  7903. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7904. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7905. if (!stride) {
  7906. stride = 3;
  7907. }
  7908. for (var index = start; index < start + count; index++) {
  7909. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7910. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7911. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7912. }
  7913. if (bias) {
  7914. minimum.x -= minimum.x * bias.x + bias.y;
  7915. minimum.y -= minimum.y * bias.x + bias.y;
  7916. minimum.z -= minimum.z * bias.x + bias.y;
  7917. maximum.x += maximum.x * bias.x + bias.y;
  7918. maximum.y += maximum.y * bias.x + bias.y;
  7919. maximum.z += maximum.z * bias.x + bias.y;
  7920. }
  7921. return {
  7922. minimum: minimum,
  7923. maximum: maximum
  7924. };
  7925. };
  7926. Tools.Vector2ArrayFeeder = function (array) {
  7927. return function (index) {
  7928. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7929. var length = isFloatArray ? array.length / 2 : array.length;
  7930. if (index >= length) {
  7931. return null;
  7932. }
  7933. if (isFloatArray) {
  7934. var fa = array;
  7935. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7936. }
  7937. var a = array;
  7938. return a[index];
  7939. };
  7940. };
  7941. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7942. if (bias === void 0) { bias = null; }
  7943. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7944. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7945. var i = 0;
  7946. var cur = feeder(i++);
  7947. while (cur) {
  7948. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7949. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7950. cur = feeder(i++);
  7951. }
  7952. if (bias) {
  7953. minimum.x -= minimum.x * bias.x + bias.y;
  7954. minimum.y -= minimum.y * bias.x + bias.y;
  7955. maximum.x += maximum.x * bias.x + bias.y;
  7956. maximum.y += maximum.y * bias.x + bias.y;
  7957. }
  7958. return {
  7959. minimum: minimum,
  7960. maximum: maximum
  7961. };
  7962. };
  7963. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7964. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7965. return null;
  7966. return Array.isArray(obj) ? obj : [obj];
  7967. };
  7968. // Misc.
  7969. Tools.GetPointerPrefix = function () {
  7970. var eventPrefix = "pointer";
  7971. // Check if pointer events are supported
  7972. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7973. eventPrefix = "mouse";
  7974. }
  7975. return eventPrefix;
  7976. };
  7977. /**
  7978. * @param func - the function to be called
  7979. * @param requester - the object that will request the next frame. Falls back to window.
  7980. */
  7981. Tools.QueueNewFrame = function (func, requester) {
  7982. if (!Tools.IsWindowObjectExist()) {
  7983. return setTimeout(func, 16);
  7984. }
  7985. if (!requester) {
  7986. requester = window;
  7987. }
  7988. if (requester.requestAnimationFrame) {
  7989. return requester.requestAnimationFrame(func);
  7990. }
  7991. else if (requester.msRequestAnimationFrame) {
  7992. return requester.msRequestAnimationFrame(func);
  7993. }
  7994. else if (requester.webkitRequestAnimationFrame) {
  7995. return requester.webkitRequestAnimationFrame(func);
  7996. }
  7997. else if (requester.mozRequestAnimationFrame) {
  7998. return requester.mozRequestAnimationFrame(func);
  7999. }
  8000. else if (requester.oRequestAnimationFrame) {
  8001. return requester.oRequestAnimationFrame(func);
  8002. }
  8003. else {
  8004. return window.setTimeout(func, 16);
  8005. }
  8006. };
  8007. Tools.RequestFullscreen = function (element) {
  8008. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8009. if (!requestFunction)
  8010. return;
  8011. requestFunction.call(element);
  8012. };
  8013. Tools.ExitFullscreen = function () {
  8014. if (document.exitFullscreen) {
  8015. document.exitFullscreen();
  8016. }
  8017. else if (document.mozCancelFullScreen) {
  8018. document.mozCancelFullScreen();
  8019. }
  8020. else if (document.webkitCancelFullScreen) {
  8021. document.webkitCancelFullScreen();
  8022. }
  8023. else if (document.msCancelFullScreen) {
  8024. document.msCancelFullScreen();
  8025. }
  8026. };
  8027. Tools.SetCorsBehavior = function (url, element) {
  8028. if (url && url.indexOf("data:") === 0) {
  8029. return;
  8030. }
  8031. if (Tools.CorsBehavior) {
  8032. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8033. element.crossOrigin = Tools.CorsBehavior;
  8034. }
  8035. else {
  8036. var result = Tools.CorsBehavior(url);
  8037. if (result) {
  8038. element.crossOrigin = result;
  8039. }
  8040. }
  8041. }
  8042. };
  8043. // External files
  8044. Tools.CleanUrl = function (url) {
  8045. url = url.replace(/#/mg, "%23");
  8046. return url;
  8047. };
  8048. Tools.LoadImage = function (url, onLoad, onError, database) {
  8049. if (url instanceof ArrayBuffer) {
  8050. url = Tools.EncodeArrayBufferTobase64(url);
  8051. }
  8052. url = Tools.CleanUrl(url);
  8053. url = Tools.PreprocessUrl(url);
  8054. var img = new Image();
  8055. Tools.SetCorsBehavior(url, img);
  8056. var loadHandler = function () {
  8057. img.removeEventListener("load", loadHandler);
  8058. img.removeEventListener("error", errorHandler);
  8059. onLoad(img);
  8060. };
  8061. var errorHandler = function (err) {
  8062. img.removeEventListener("load", loadHandler);
  8063. img.removeEventListener("error", errorHandler);
  8064. Tools.Error("Error while trying to load image: " + url);
  8065. if (onError) {
  8066. onError("Error while trying to load image: " + url, err);
  8067. }
  8068. };
  8069. img.addEventListener("load", loadHandler);
  8070. img.addEventListener("error", errorHandler);
  8071. var noIndexedDB = function () {
  8072. img.src = url;
  8073. };
  8074. var loadFromIndexedDB = function () {
  8075. if (database) {
  8076. database.loadImageFromDB(url, img);
  8077. }
  8078. };
  8079. //ANY database to do!
  8080. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8081. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8082. }
  8083. else {
  8084. if (url.indexOf("file:") !== -1) {
  8085. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8086. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8087. try {
  8088. var blobURL;
  8089. try {
  8090. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8091. }
  8092. catch (ex) {
  8093. // Chrome doesn't support oneTimeOnly parameter
  8094. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8095. }
  8096. img.src = blobURL;
  8097. }
  8098. catch (e) {
  8099. img.src = "";
  8100. }
  8101. return img;
  8102. }
  8103. }
  8104. noIndexedDB();
  8105. }
  8106. return img;
  8107. };
  8108. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8109. url = Tools.CleanUrl(url);
  8110. url = Tools.PreprocessUrl(url);
  8111. // If file and file input are set
  8112. if (url.indexOf("file:") !== -1) {
  8113. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8114. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8115. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8116. }
  8117. }
  8118. var loadUrl = Tools.BaseUrl + url;
  8119. var aborted = false;
  8120. var fileRequest = {
  8121. onCompleteObservable: new BABYLON.Observable(),
  8122. abort: function () { return aborted = true; },
  8123. };
  8124. var requestFile = function () {
  8125. var request = new XMLHttpRequest();
  8126. var retryHandle = null;
  8127. fileRequest.abort = function () {
  8128. aborted = true;
  8129. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8130. request.abort();
  8131. }
  8132. if (retryHandle !== null) {
  8133. clearTimeout(retryHandle);
  8134. retryHandle = null;
  8135. }
  8136. };
  8137. var retryLoop = function (retryIndex) {
  8138. request.open('GET', loadUrl, true);
  8139. if (useArrayBuffer) {
  8140. request.responseType = "arraybuffer";
  8141. }
  8142. if (onProgress) {
  8143. request.addEventListener("progress", onProgress);
  8144. }
  8145. var onLoadEnd = function () {
  8146. request.removeEventListener("loadend", onLoadEnd);
  8147. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8148. fileRequest.onCompleteObservable.clear();
  8149. };
  8150. request.addEventListener("loadend", onLoadEnd);
  8151. var onReadyStateChange = function () {
  8152. if (aborted) {
  8153. return;
  8154. }
  8155. // In case of undefined state in some browsers.
  8156. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8157. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8158. request.removeEventListener("readystatechange", onReadyStateChange);
  8159. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8160. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8161. return;
  8162. }
  8163. var retryStrategy = Tools.DefaultRetryStrategy;
  8164. if (retryStrategy) {
  8165. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8166. if (waitTime !== -1) {
  8167. // Prevent the request from completing for retry.
  8168. request.removeEventListener("loadend", onLoadEnd);
  8169. request = new XMLHttpRequest();
  8170. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8171. return;
  8172. }
  8173. }
  8174. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8175. if (onError) {
  8176. onError(request, e);
  8177. }
  8178. else {
  8179. throw e;
  8180. }
  8181. }
  8182. };
  8183. request.addEventListener("readystatechange", onReadyStateChange);
  8184. request.send();
  8185. };
  8186. retryLoop(0);
  8187. };
  8188. // Caching all files
  8189. if (database && database.enableSceneOffline) {
  8190. var noIndexedDB_1 = function () {
  8191. if (!aborted) {
  8192. requestFile();
  8193. }
  8194. };
  8195. var loadFromIndexedDB = function () {
  8196. // TODO: database needs to support aborting and should return a IFileRequest
  8197. if (aborted) {
  8198. return;
  8199. }
  8200. if (database) {
  8201. database.loadFileFromDB(url, function (data) {
  8202. if (!aborted) {
  8203. onSuccess(data);
  8204. }
  8205. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8206. }, onProgress ? function (event) {
  8207. if (!aborted) {
  8208. onProgress(event);
  8209. }
  8210. } : undefined, noIndexedDB_1, useArrayBuffer);
  8211. }
  8212. };
  8213. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8214. }
  8215. else {
  8216. requestFile();
  8217. }
  8218. return fileRequest;
  8219. };
  8220. /**
  8221. * Load a script (identified by an url). When the url returns, the
  8222. * content of this file is added into a new script element, attached to the DOM (body element)
  8223. */
  8224. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8225. var head = document.getElementsByTagName('head')[0];
  8226. var script = document.createElement('script');
  8227. script.type = 'text/javascript';
  8228. script.src = scriptUrl;
  8229. script.onload = function () {
  8230. if (onSuccess) {
  8231. onSuccess();
  8232. }
  8233. };
  8234. script.onerror = function (e) {
  8235. if (onError) {
  8236. onError("Unable to load script", e);
  8237. }
  8238. };
  8239. head.appendChild(script);
  8240. };
  8241. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8242. var reader = new FileReader();
  8243. var request = {
  8244. onCompleteObservable: new BABYLON.Observable(),
  8245. abort: function () { return reader.abort(); },
  8246. };
  8247. reader.onloadend = function (e) {
  8248. request.onCompleteObservable.notifyObservers(request);
  8249. };
  8250. reader.onload = function (e) {
  8251. //target doesn't have result from ts 1.3
  8252. callback(e.target['result']);
  8253. };
  8254. reader.onprogress = progressCallback;
  8255. reader.readAsDataURL(fileToLoad);
  8256. return request;
  8257. };
  8258. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8259. var reader = new FileReader();
  8260. var request = {
  8261. onCompleteObservable: new BABYLON.Observable(),
  8262. abort: function () { return reader.abort(); },
  8263. };
  8264. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8265. reader.onerror = function (e) {
  8266. Tools.Log("Error while reading file: " + fileToLoad.name);
  8267. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8268. };
  8269. reader.onload = function (e) {
  8270. //target doesn't have result from ts 1.3
  8271. callback(e.target['result']);
  8272. };
  8273. if (progressCallBack) {
  8274. reader.onprogress = progressCallBack;
  8275. }
  8276. if (!useArrayBuffer) {
  8277. // Asynchronous read
  8278. reader.readAsText(fileToLoad);
  8279. }
  8280. else {
  8281. reader.readAsArrayBuffer(fileToLoad);
  8282. }
  8283. return request;
  8284. };
  8285. //returns a downloadable url to a file content.
  8286. Tools.FileAsURL = function (content) {
  8287. var fileBlob = new Blob([content]);
  8288. var url = window.URL || window.webkitURL;
  8289. var link = url.createObjectURL(fileBlob);
  8290. return link;
  8291. };
  8292. // Misc.
  8293. Tools.Format = function (value, decimals) {
  8294. if (decimals === void 0) { decimals = 2; }
  8295. return value.toFixed(decimals);
  8296. };
  8297. Tools.CheckExtends = function (v, min, max) {
  8298. if (v.x < min.x)
  8299. min.x = v.x;
  8300. if (v.y < min.y)
  8301. min.y = v.y;
  8302. if (v.z < min.z)
  8303. min.z = v.z;
  8304. if (v.x > max.x)
  8305. max.x = v.x;
  8306. if (v.y > max.y)
  8307. max.y = v.y;
  8308. if (v.z > max.z)
  8309. max.z = v.z;
  8310. };
  8311. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8312. for (var prop in source) {
  8313. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8314. continue;
  8315. }
  8316. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8317. continue;
  8318. }
  8319. var sourceValue = source[prop];
  8320. var typeOfSourceValue = typeof sourceValue;
  8321. if (typeOfSourceValue === "function") {
  8322. continue;
  8323. }
  8324. if (typeOfSourceValue === "object") {
  8325. if (sourceValue instanceof Array) {
  8326. destination[prop] = [];
  8327. if (sourceValue.length > 0) {
  8328. if (typeof sourceValue[0] == "object") {
  8329. for (var index = 0; index < sourceValue.length; index++) {
  8330. var clonedValue = cloneValue(sourceValue[index], destination);
  8331. if (destination[prop].indexOf(clonedValue) === -1) {
  8332. destination[prop].push(clonedValue);
  8333. }
  8334. }
  8335. }
  8336. else {
  8337. destination[prop] = sourceValue.slice(0);
  8338. }
  8339. }
  8340. }
  8341. else {
  8342. destination[prop] = cloneValue(sourceValue, destination);
  8343. }
  8344. }
  8345. else {
  8346. destination[prop] = sourceValue;
  8347. }
  8348. }
  8349. };
  8350. Tools.IsEmpty = function (obj) {
  8351. for (var i in obj) {
  8352. if (obj.hasOwnProperty(i)) {
  8353. return false;
  8354. }
  8355. }
  8356. return true;
  8357. };
  8358. Tools.RegisterTopRootEvents = function (events) {
  8359. for (var index = 0; index < events.length; index++) {
  8360. var event = events[index];
  8361. window.addEventListener(event.name, event.handler, false);
  8362. try {
  8363. if (window.parent) {
  8364. window.parent.addEventListener(event.name, event.handler, false);
  8365. }
  8366. }
  8367. catch (e) {
  8368. // Silently fails...
  8369. }
  8370. }
  8371. };
  8372. Tools.UnregisterTopRootEvents = function (events) {
  8373. for (var index = 0; index < events.length; index++) {
  8374. var event = events[index];
  8375. window.removeEventListener(event.name, event.handler);
  8376. try {
  8377. if (window.parent) {
  8378. window.parent.removeEventListener(event.name, event.handler);
  8379. }
  8380. }
  8381. catch (e) {
  8382. // Silently fails...
  8383. }
  8384. }
  8385. };
  8386. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8387. if (mimeType === void 0) { mimeType = "image/png"; }
  8388. // Read the contents of the framebuffer
  8389. var numberOfChannelsByLine = width * 4;
  8390. var halfHeight = height / 2;
  8391. //Reading datas from WebGL
  8392. var data = engine.readPixels(0, 0, width, height);
  8393. //To flip image on Y axis.
  8394. for (var i = 0; i < halfHeight; i++) {
  8395. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8396. var currentCell = j + i * numberOfChannelsByLine;
  8397. var targetLine = height - i - 1;
  8398. var targetCell = j + targetLine * numberOfChannelsByLine;
  8399. var temp = data[currentCell];
  8400. data[currentCell] = data[targetCell];
  8401. data[targetCell] = temp;
  8402. }
  8403. }
  8404. // Create a 2D canvas to store the result
  8405. if (!screenshotCanvas) {
  8406. screenshotCanvas = document.createElement('canvas');
  8407. }
  8408. screenshotCanvas.width = width;
  8409. screenshotCanvas.height = height;
  8410. var context = screenshotCanvas.getContext('2d');
  8411. if (context) {
  8412. // Copy the pixels to a 2D canvas
  8413. var imageData = context.createImageData(width, height);
  8414. var castData = (imageData.data);
  8415. castData.set(data);
  8416. context.putImageData(imageData, 0, 0);
  8417. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8418. }
  8419. };
  8420. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8421. if (mimeType === void 0) { mimeType = "image/png"; }
  8422. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8423. if (successCallback) {
  8424. successCallback(base64Image);
  8425. }
  8426. else {
  8427. // We need HTMLCanvasElement.toBlob for HD screenshots
  8428. if (!screenshotCanvas.toBlob) {
  8429. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8430. screenshotCanvas.toBlob = function (callback, type, quality) {
  8431. var _this = this;
  8432. setTimeout(function () {
  8433. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8434. for (var i = 0; i < len; i++) {
  8435. arr[i] = binStr.charCodeAt(i);
  8436. }
  8437. callback(new Blob([arr], { type: type || 'image/png' }));
  8438. });
  8439. };
  8440. }
  8441. screenshotCanvas.toBlob(function (blob) {
  8442. var url = URL.createObjectURL(blob);
  8443. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8444. if (("download" in document.createElement("a"))) {
  8445. var a = window.document.createElement("a");
  8446. a.href = url;
  8447. if (fileName) {
  8448. a.setAttribute("download", fileName);
  8449. }
  8450. else {
  8451. var date = new Date();
  8452. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8453. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8454. }
  8455. window.document.body.appendChild(a);
  8456. a.addEventListener("click", function () {
  8457. if (a.parentElement) {
  8458. a.parentElement.removeChild(a);
  8459. }
  8460. });
  8461. a.click();
  8462. }
  8463. else {
  8464. var newWindow = window.open("");
  8465. if (!newWindow)
  8466. return;
  8467. var img = newWindow.document.createElement("img");
  8468. img.onload = function () {
  8469. // no longer need to read the blob so it's revoked
  8470. URL.revokeObjectURL(url);
  8471. };
  8472. img.src = url;
  8473. newWindow.document.body.appendChild(img);
  8474. }
  8475. });
  8476. }
  8477. };
  8478. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8479. if (mimeType === void 0) { mimeType = "image/png"; }
  8480. var width;
  8481. var height;
  8482. // If a precision value is specified
  8483. if (size.precision) {
  8484. width = Math.round(engine.getRenderWidth() * size.precision);
  8485. height = Math.round(width / engine.getAspectRatio(camera));
  8486. }
  8487. else if (size.width && size.height) {
  8488. width = size.width;
  8489. height = size.height;
  8490. }
  8491. else if (size.width && !size.height) {
  8492. width = size.width;
  8493. height = Math.round(width / engine.getAspectRatio(camera));
  8494. }
  8495. else if (size.height && !size.width) {
  8496. height = size.height;
  8497. width = Math.round(height * engine.getAspectRatio(camera));
  8498. }
  8499. else if (!isNaN(size)) {
  8500. height = size;
  8501. width = size;
  8502. }
  8503. else {
  8504. Tools.Error("Invalid 'size' parameter !");
  8505. return;
  8506. }
  8507. if (!screenshotCanvas) {
  8508. screenshotCanvas = document.createElement('canvas');
  8509. }
  8510. screenshotCanvas.width = width;
  8511. screenshotCanvas.height = height;
  8512. var renderContext = screenshotCanvas.getContext("2d");
  8513. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8514. var newWidth = width;
  8515. var newHeight = newWidth / ratio;
  8516. if (newHeight > height) {
  8517. newHeight = height;
  8518. newWidth = newHeight * ratio;
  8519. }
  8520. var offsetX = Math.max(0, width - newWidth) / 2;
  8521. var offsetY = Math.max(0, height - newHeight) / 2;
  8522. var renderingCanvas = engine.getRenderingCanvas();
  8523. if (renderContext && renderingCanvas) {
  8524. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8525. }
  8526. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8527. };
  8528. /**
  8529. * Generates an image screenshot from the specified camera.
  8530. *
  8531. * @param engine The engine to use for rendering
  8532. * @param camera The camera to use for rendering
  8533. * @param size This parameter can be set to a single number or to an object with the
  8534. * following (optional) properties: precision, width, height. If a single number is passed,
  8535. * it will be used for both width and height. If an object is passed, the screenshot size
  8536. * will be derived from the parameters. The precision property is a multiplier allowing
  8537. * rendering at a higher or lower resolution.
  8538. * @param successCallback The callback receives a single parameter which contains the
  8539. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8540. * src parameter of an <img> to display it.
  8541. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8542. * Check your browser for supported MIME types.
  8543. * @param samples Texture samples (default: 1)
  8544. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8545. * @param fileName A name for for the downloaded file.
  8546. * @constructor
  8547. */
  8548. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8549. if (mimeType === void 0) { mimeType = "image/png"; }
  8550. if (samples === void 0) { samples = 1; }
  8551. if (antialiasing === void 0) { antialiasing = false; }
  8552. var width;
  8553. var height;
  8554. //If a precision value is specified
  8555. if (size.precision) {
  8556. width = Math.round(engine.getRenderWidth() * size.precision);
  8557. height = Math.round(width / engine.getAspectRatio(camera));
  8558. size = { width: width, height: height };
  8559. }
  8560. else if (size.width && size.height) {
  8561. width = size.width;
  8562. height = size.height;
  8563. }
  8564. else if (size.width && !size.height) {
  8565. width = size.width;
  8566. height = Math.round(width / engine.getAspectRatio(camera));
  8567. size = { width: width, height: height };
  8568. }
  8569. else if (size.height && !size.width) {
  8570. height = size.height;
  8571. width = Math.round(height * engine.getAspectRatio(camera));
  8572. size = { width: width, height: height };
  8573. }
  8574. else if (!isNaN(size)) {
  8575. height = size;
  8576. width = size;
  8577. }
  8578. else {
  8579. Tools.Error("Invalid 'size' parameter !");
  8580. return;
  8581. }
  8582. var scene = camera.getScene();
  8583. var previousCamera = null;
  8584. if (scene.activeCamera !== camera) {
  8585. previousCamera = scene.activeCamera;
  8586. scene.activeCamera = camera;
  8587. }
  8588. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8589. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8590. texture.renderList = null;
  8591. texture.samples = samples;
  8592. if (antialiasing) {
  8593. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8594. }
  8595. texture.onAfterRenderObservable.add(function () {
  8596. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8597. });
  8598. scene.incrementRenderId();
  8599. scene.resetCachedMaterial();
  8600. texture.render(true);
  8601. texture.dispose();
  8602. if (previousCamera) {
  8603. scene.activeCamera = previousCamera;
  8604. }
  8605. camera.getProjectionMatrix(true); // Force cache refresh;
  8606. };
  8607. // XHR response validator for local file scenario
  8608. Tools.ValidateXHRData = function (xhr, dataType) {
  8609. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8610. if (dataType === void 0) { dataType = 7; }
  8611. try {
  8612. if (dataType & 1) {
  8613. if (xhr.responseText && xhr.responseText.length > 0) {
  8614. return true;
  8615. }
  8616. else if (dataType === 1) {
  8617. return false;
  8618. }
  8619. }
  8620. if (dataType & 2) {
  8621. // Check header width and height since there is no "TGA" magic number
  8622. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8623. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8624. return true;
  8625. }
  8626. else if (dataType === 2) {
  8627. return false;
  8628. }
  8629. }
  8630. if (dataType & 4) {
  8631. // Check for the "DDS" magic number
  8632. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8633. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8634. return true;
  8635. }
  8636. else {
  8637. return false;
  8638. }
  8639. }
  8640. }
  8641. catch (e) {
  8642. // Global protection
  8643. }
  8644. return false;
  8645. };
  8646. /**
  8647. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8648. * Be aware Math.random() could cause collisions, but:
  8649. * "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"
  8650. */
  8651. Tools.RandomId = function () {
  8652. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8653. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8654. return v.toString(16);
  8655. });
  8656. };
  8657. /**
  8658. * Test if the given uri is a base64 string.
  8659. * @param uri The uri to test
  8660. * @return True if the uri is a base64 string or false otherwise.
  8661. */
  8662. Tools.IsBase64 = function (uri) {
  8663. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8664. };
  8665. /**
  8666. * Decode the given base64 uri.
  8667. * @param uri The uri to decode
  8668. * @return The decoded base64 data.
  8669. */
  8670. Tools.DecodeBase64 = function (uri) {
  8671. var decodedString = atob(uri.split(",")[1]);
  8672. var bufferLength = decodedString.length;
  8673. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8674. for (var i = 0; i < bufferLength; i++) {
  8675. bufferView[i] = decodedString.charCodeAt(i);
  8676. }
  8677. return bufferView.buffer;
  8678. };
  8679. Object.defineProperty(Tools, "NoneLogLevel", {
  8680. get: function () {
  8681. return Tools._NoneLogLevel;
  8682. },
  8683. enumerable: true,
  8684. configurable: true
  8685. });
  8686. Object.defineProperty(Tools, "MessageLogLevel", {
  8687. get: function () {
  8688. return Tools._MessageLogLevel;
  8689. },
  8690. enumerable: true,
  8691. configurable: true
  8692. });
  8693. Object.defineProperty(Tools, "WarningLogLevel", {
  8694. get: function () {
  8695. return Tools._WarningLogLevel;
  8696. },
  8697. enumerable: true,
  8698. configurable: true
  8699. });
  8700. Object.defineProperty(Tools, "ErrorLogLevel", {
  8701. get: function () {
  8702. return Tools._ErrorLogLevel;
  8703. },
  8704. enumerable: true,
  8705. configurable: true
  8706. });
  8707. Object.defineProperty(Tools, "AllLogLevel", {
  8708. get: function () {
  8709. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8710. },
  8711. enumerable: true,
  8712. configurable: true
  8713. });
  8714. Tools._AddLogEntry = function (entry) {
  8715. Tools._LogCache = entry + Tools._LogCache;
  8716. if (Tools.OnNewCacheEntry) {
  8717. Tools.OnNewCacheEntry(entry);
  8718. }
  8719. };
  8720. Tools._FormatMessage = function (message) {
  8721. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8722. var date = new Date();
  8723. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8724. };
  8725. Tools._LogDisabled = function (message) {
  8726. // nothing to do
  8727. };
  8728. Tools._LogEnabled = function (message) {
  8729. var formattedMessage = Tools._FormatMessage(message);
  8730. console.log("BJS - " + formattedMessage);
  8731. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8732. Tools._AddLogEntry(entry);
  8733. };
  8734. Tools._WarnDisabled = function (message) {
  8735. // nothing to do
  8736. };
  8737. Tools._WarnEnabled = function (message) {
  8738. var formattedMessage = Tools._FormatMessage(message);
  8739. console.warn("BJS - " + formattedMessage);
  8740. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8741. Tools._AddLogEntry(entry);
  8742. };
  8743. Tools._ErrorDisabled = function (message) {
  8744. // nothing to do
  8745. };
  8746. Tools._ErrorEnabled = function (message) {
  8747. Tools.errorsCount++;
  8748. var formattedMessage = Tools._FormatMessage(message);
  8749. console.error("BJS - " + formattedMessage);
  8750. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8751. Tools._AddLogEntry(entry);
  8752. };
  8753. Object.defineProperty(Tools, "LogCache", {
  8754. get: function () {
  8755. return Tools._LogCache;
  8756. },
  8757. enumerable: true,
  8758. configurable: true
  8759. });
  8760. Tools.ClearLogCache = function () {
  8761. Tools._LogCache = "";
  8762. Tools.errorsCount = 0;
  8763. };
  8764. Object.defineProperty(Tools, "LogLevels", {
  8765. set: function (level) {
  8766. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8767. Tools.Log = Tools._LogEnabled;
  8768. }
  8769. else {
  8770. Tools.Log = Tools._LogDisabled;
  8771. }
  8772. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8773. Tools.Warn = Tools._WarnEnabled;
  8774. }
  8775. else {
  8776. Tools.Warn = Tools._WarnDisabled;
  8777. }
  8778. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8779. Tools.Error = Tools._ErrorEnabled;
  8780. }
  8781. else {
  8782. Tools.Error = Tools._ErrorDisabled;
  8783. }
  8784. },
  8785. enumerable: true,
  8786. configurable: true
  8787. });
  8788. Tools.IsWindowObjectExist = function () {
  8789. return (typeof window) !== "undefined";
  8790. };
  8791. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8792. get: function () {
  8793. return Tools._PerformanceNoneLogLevel;
  8794. },
  8795. enumerable: true,
  8796. configurable: true
  8797. });
  8798. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8799. get: function () {
  8800. return Tools._PerformanceUserMarkLogLevel;
  8801. },
  8802. enumerable: true,
  8803. configurable: true
  8804. });
  8805. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8806. get: function () {
  8807. return Tools._PerformanceConsoleLogLevel;
  8808. },
  8809. enumerable: true,
  8810. configurable: true
  8811. });
  8812. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8813. set: function (level) {
  8814. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8815. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8816. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8817. return;
  8818. }
  8819. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8820. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8821. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8822. return;
  8823. }
  8824. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8825. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8826. },
  8827. enumerable: true,
  8828. configurable: true
  8829. });
  8830. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8831. };
  8832. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8833. };
  8834. Tools._StartUserMark = function (counterName, condition) {
  8835. if (condition === void 0) { condition = true; }
  8836. if (!Tools._performance) {
  8837. if (!Tools.IsWindowObjectExist()) {
  8838. return;
  8839. }
  8840. Tools._performance = window.performance;
  8841. }
  8842. if (!condition || !Tools._performance.mark) {
  8843. return;
  8844. }
  8845. Tools._performance.mark(counterName + "-Begin");
  8846. };
  8847. Tools._EndUserMark = function (counterName, condition) {
  8848. if (condition === void 0) { condition = true; }
  8849. if (!condition || !Tools._performance.mark) {
  8850. return;
  8851. }
  8852. Tools._performance.mark(counterName + "-End");
  8853. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8854. };
  8855. Tools._StartPerformanceConsole = function (counterName, condition) {
  8856. if (condition === void 0) { condition = true; }
  8857. if (!condition) {
  8858. return;
  8859. }
  8860. Tools._StartUserMark(counterName, condition);
  8861. if (console.time) {
  8862. console.time(counterName);
  8863. }
  8864. };
  8865. Tools._EndPerformanceConsole = function (counterName, condition) {
  8866. if (condition === void 0) { condition = true; }
  8867. if (!condition) {
  8868. return;
  8869. }
  8870. Tools._EndUserMark(counterName, condition);
  8871. if (console.time) {
  8872. console.timeEnd(counterName);
  8873. }
  8874. };
  8875. Object.defineProperty(Tools, "Now", {
  8876. get: function () {
  8877. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8878. return window.performance.now();
  8879. }
  8880. return new Date().getTime();
  8881. },
  8882. enumerable: true,
  8883. configurable: true
  8884. });
  8885. /**
  8886. * This method will return the name of the class used to create the instance of the given object.
  8887. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8888. * @param object the object to get the class name from
  8889. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8890. */
  8891. Tools.GetClassName = function (object, isType) {
  8892. if (isType === void 0) { isType = false; }
  8893. var name = null;
  8894. if (!isType && object.getClassName) {
  8895. name = object.getClassName();
  8896. }
  8897. else {
  8898. if (object instanceof Object) {
  8899. var classObj = isType ? object : Object.getPrototypeOf(object);
  8900. name = classObj.constructor["__bjsclassName__"];
  8901. }
  8902. if (!name) {
  8903. name = typeof object;
  8904. }
  8905. }
  8906. return name;
  8907. };
  8908. Tools.First = function (array, predicate) {
  8909. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8910. var el = array_1[_i];
  8911. if (predicate(el)) {
  8912. return el;
  8913. }
  8914. }
  8915. return null;
  8916. };
  8917. /**
  8918. * This method will return the name of the full name of the class, including its owning module (if any).
  8919. * 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).
  8920. * @param object the object to get the class name from
  8921. * @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.
  8922. */
  8923. Tools.getFullClassName = function (object, isType) {
  8924. if (isType === void 0) { isType = false; }
  8925. var className = null;
  8926. var moduleName = null;
  8927. if (!isType && object.getClassName) {
  8928. className = object.getClassName();
  8929. }
  8930. else {
  8931. if (object instanceof Object) {
  8932. var classObj = isType ? object : Object.getPrototypeOf(object);
  8933. className = classObj.constructor["__bjsclassName__"];
  8934. moduleName = classObj.constructor["__bjsmoduleName__"];
  8935. }
  8936. if (!className) {
  8937. className = typeof object;
  8938. }
  8939. }
  8940. if (!className) {
  8941. return null;
  8942. }
  8943. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8944. };
  8945. /**
  8946. * 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.
  8947. * @param array
  8948. */
  8949. Tools.arrayOrStringFeeder = function (array) {
  8950. return function (index) {
  8951. if (index >= array.length) {
  8952. return null;
  8953. }
  8954. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8955. if (val && val.getHashCode) {
  8956. val = val.getHashCode();
  8957. }
  8958. if (typeof val === "string") {
  8959. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8960. }
  8961. return val;
  8962. };
  8963. };
  8964. /**
  8965. * Compute the hashCode of a stream of number
  8966. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8967. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8968. * @return the hash code computed
  8969. */
  8970. Tools.hashCodeFromStream = function (feeder) {
  8971. // Based from here: http://stackoverflow.com/a/7616484/802124
  8972. var hash = 0;
  8973. var index = 0;
  8974. var chr = feeder(index++);
  8975. while (chr != null) {
  8976. hash = ((hash << 5) - hash) + chr;
  8977. hash |= 0; // Convert to 32bit integer
  8978. chr = feeder(index++);
  8979. }
  8980. return hash;
  8981. };
  8982. /**
  8983. * Returns a promise that resolves after the given amount of time.
  8984. * @param delay Number of milliseconds to delay
  8985. * @returns Promise that resolves after the given amount of time
  8986. */
  8987. Tools.DelayAsync = function (delay) {
  8988. return new Promise(function (resolve) {
  8989. setTimeout(function () {
  8990. resolve();
  8991. }, delay);
  8992. });
  8993. };
  8994. Tools.BaseUrl = "";
  8995. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8996. /**
  8997. * Default behaviour for cors in the application.
  8998. * It can be a string if the expected behavior is identical in the entire app.
  8999. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9000. */
  9001. Tools.CorsBehavior = "anonymous";
  9002. Tools.UseFallbackTexture = true;
  9003. /**
  9004. * Use this object to register external classes like custom textures or material
  9005. * to allow the laoders to instantiate them
  9006. */
  9007. Tools.RegisteredExternalClasses = {};
  9008. // Used in case of a texture loading problem
  9009. 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";
  9010. Tools.PreprocessUrl = function (url) {
  9011. return url;
  9012. };
  9013. // Logs
  9014. Tools._NoneLogLevel = 0;
  9015. Tools._MessageLogLevel = 1;
  9016. Tools._WarningLogLevel = 2;
  9017. Tools._ErrorLogLevel = 4;
  9018. Tools._LogCache = "";
  9019. Tools.errorsCount = 0;
  9020. Tools.Log = Tools._LogEnabled;
  9021. Tools.Warn = Tools._WarnEnabled;
  9022. Tools.Error = Tools._ErrorEnabled;
  9023. // Performances
  9024. Tools._PerformanceNoneLogLevel = 0;
  9025. Tools._PerformanceUserMarkLogLevel = 1;
  9026. Tools._PerformanceConsoleLogLevel = 2;
  9027. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9028. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9029. return Tools;
  9030. }());
  9031. BABYLON.Tools = Tools;
  9032. /**
  9033. * This class is used to track a performance counter which is number based.
  9034. * The user has access to many properties which give statistics of different nature
  9035. *
  9036. * The implementer can track two kinds of Performance Counter: time and count
  9037. * 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.
  9038. * 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.
  9039. */
  9040. var PerfCounter = /** @class */ (function () {
  9041. function PerfCounter() {
  9042. this._startMonitoringTime = 0;
  9043. this._min = 0;
  9044. this._max = 0;
  9045. this._average = 0;
  9046. this._lastSecAverage = 0;
  9047. this._current = 0;
  9048. this._totalValueCount = 0;
  9049. this._totalAccumulated = 0;
  9050. this._lastSecAccumulated = 0;
  9051. this._lastSecTime = 0;
  9052. this._lastSecValueCount = 0;
  9053. }
  9054. Object.defineProperty(PerfCounter.prototype, "min", {
  9055. /**
  9056. * Returns the smallest value ever
  9057. */
  9058. get: function () {
  9059. return this._min;
  9060. },
  9061. enumerable: true,
  9062. configurable: true
  9063. });
  9064. Object.defineProperty(PerfCounter.prototype, "max", {
  9065. /**
  9066. * Returns the biggest value ever
  9067. */
  9068. get: function () {
  9069. return this._max;
  9070. },
  9071. enumerable: true,
  9072. configurable: true
  9073. });
  9074. Object.defineProperty(PerfCounter.prototype, "average", {
  9075. /**
  9076. * Returns the average value since the performance counter is running
  9077. */
  9078. get: function () {
  9079. return this._average;
  9080. },
  9081. enumerable: true,
  9082. configurable: true
  9083. });
  9084. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9085. /**
  9086. * Returns the average value of the last second the counter was monitored
  9087. */
  9088. get: function () {
  9089. return this._lastSecAverage;
  9090. },
  9091. enumerable: true,
  9092. configurable: true
  9093. });
  9094. Object.defineProperty(PerfCounter.prototype, "current", {
  9095. /**
  9096. * Returns the current value
  9097. */
  9098. get: function () {
  9099. return this._current;
  9100. },
  9101. enumerable: true,
  9102. configurable: true
  9103. });
  9104. Object.defineProperty(PerfCounter.prototype, "total", {
  9105. get: function () {
  9106. return this._totalAccumulated;
  9107. },
  9108. enumerable: true,
  9109. configurable: true
  9110. });
  9111. Object.defineProperty(PerfCounter.prototype, "count", {
  9112. get: function () {
  9113. return this._totalValueCount;
  9114. },
  9115. enumerable: true,
  9116. configurable: true
  9117. });
  9118. /**
  9119. * Call this method to start monitoring a new frame.
  9120. * 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.
  9121. */
  9122. PerfCounter.prototype.fetchNewFrame = function () {
  9123. this._totalValueCount++;
  9124. this._current = 0;
  9125. this._lastSecValueCount++;
  9126. };
  9127. /**
  9128. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9129. * @param newCount the count value to add to the monitored count
  9130. * @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.
  9131. */
  9132. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9133. if (!PerfCounter.Enabled) {
  9134. return;
  9135. }
  9136. this._current += newCount;
  9137. if (fetchResult) {
  9138. this._fetchResult();
  9139. }
  9140. };
  9141. /**
  9142. * Start monitoring this performance counter
  9143. */
  9144. PerfCounter.prototype.beginMonitoring = function () {
  9145. if (!PerfCounter.Enabled) {
  9146. return;
  9147. }
  9148. this._startMonitoringTime = Tools.Now;
  9149. };
  9150. /**
  9151. * Compute the time lapsed since the previous beginMonitoring() call.
  9152. * @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
  9153. */
  9154. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9155. if (newFrame === void 0) { newFrame = true; }
  9156. if (!PerfCounter.Enabled) {
  9157. return;
  9158. }
  9159. if (newFrame) {
  9160. this.fetchNewFrame();
  9161. }
  9162. var currentTime = Tools.Now;
  9163. this._current = currentTime - this._startMonitoringTime;
  9164. if (newFrame) {
  9165. this._fetchResult();
  9166. }
  9167. };
  9168. PerfCounter.prototype._fetchResult = function () {
  9169. this._totalAccumulated += this._current;
  9170. this._lastSecAccumulated += this._current;
  9171. // Min/Max update
  9172. this._min = Math.min(this._min, this._current);
  9173. this._max = Math.max(this._max, this._current);
  9174. this._average = this._totalAccumulated / this._totalValueCount;
  9175. // Reset last sec?
  9176. var now = Tools.Now;
  9177. if ((now - this._lastSecTime) > 1000) {
  9178. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9179. this._lastSecTime = now;
  9180. this._lastSecAccumulated = 0;
  9181. this._lastSecValueCount = 0;
  9182. }
  9183. };
  9184. PerfCounter.Enabled = true;
  9185. return PerfCounter;
  9186. }());
  9187. BABYLON.PerfCounter = PerfCounter;
  9188. /**
  9189. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9190. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9191. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9192. * @param name The name of the class, case should be preserved
  9193. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9194. */
  9195. function className(name, module) {
  9196. return function (target) {
  9197. target["__bjsclassName__"] = name;
  9198. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9199. };
  9200. }
  9201. BABYLON.className = className;
  9202. /**
  9203. * An implementation of a loop for asynchronous functions.
  9204. */
  9205. var AsyncLoop = /** @class */ (function () {
  9206. /**
  9207. * Constroctor.
  9208. * @param iterations the number of iterations.
  9209. * @param _fn the function to run each iteration
  9210. * @param _successCallback the callback that will be called upon succesful execution
  9211. * @param offset starting offset.
  9212. */
  9213. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9214. if (offset === void 0) { offset = 0; }
  9215. this.iterations = iterations;
  9216. this._fn = _fn;
  9217. this._successCallback = _successCallback;
  9218. this.index = offset - 1;
  9219. this._done = false;
  9220. }
  9221. /**
  9222. * Execute the next iteration. Must be called after the last iteration was finished.
  9223. */
  9224. AsyncLoop.prototype.executeNext = function () {
  9225. if (!this._done) {
  9226. if (this.index + 1 < this.iterations) {
  9227. ++this.index;
  9228. this._fn(this);
  9229. }
  9230. else {
  9231. this.breakLoop();
  9232. }
  9233. }
  9234. };
  9235. /**
  9236. * Break the loop and run the success callback.
  9237. */
  9238. AsyncLoop.prototype.breakLoop = function () {
  9239. this._done = true;
  9240. this._successCallback();
  9241. };
  9242. /**
  9243. * Helper function
  9244. */
  9245. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9246. if (offset === void 0) { offset = 0; }
  9247. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9248. loop.executeNext();
  9249. return loop;
  9250. };
  9251. /**
  9252. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9253. * @param iterations total number of iterations
  9254. * @param syncedIterations number of synchronous iterations in each async iteration.
  9255. * @param fn the function to call each iteration.
  9256. * @param callback a success call back that will be called when iterating stops.
  9257. * @param breakFunction a break condition (optional)
  9258. * @param timeout timeout settings for the setTimeout function. default - 0.
  9259. * @constructor
  9260. */
  9261. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9262. if (timeout === void 0) { timeout = 0; }
  9263. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9264. if (breakFunction && breakFunction())
  9265. loop.breakLoop();
  9266. else {
  9267. setTimeout(function () {
  9268. for (var i = 0; i < syncedIterations; ++i) {
  9269. var iteration = (loop.index * syncedIterations) + i;
  9270. if (iteration >= iterations)
  9271. break;
  9272. fn(iteration);
  9273. if (breakFunction && breakFunction()) {
  9274. loop.breakLoop();
  9275. break;
  9276. }
  9277. }
  9278. loop.executeNext();
  9279. }, timeout);
  9280. }
  9281. }, callback);
  9282. };
  9283. return AsyncLoop;
  9284. }());
  9285. BABYLON.AsyncLoop = AsyncLoop;
  9286. })(BABYLON || (BABYLON = {}));
  9287. //# sourceMappingURL=babylon.tools.js.map
  9288. var BABYLON;
  9289. (function (BABYLON) {
  9290. var PromiseStates;
  9291. (function (PromiseStates) {
  9292. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9293. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9294. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9295. })(PromiseStates || (PromiseStates = {}));
  9296. var FulFillmentAgregator = /** @class */ (function () {
  9297. function FulFillmentAgregator() {
  9298. this.count = 0;
  9299. this.target = 0;
  9300. this.results = [];
  9301. }
  9302. return FulFillmentAgregator;
  9303. }());
  9304. var InternalPromise = /** @class */ (function () {
  9305. function InternalPromise(resolver) {
  9306. var _this = this;
  9307. this._state = PromiseStates.Pending;
  9308. this._children = new Array();
  9309. this._rejectWasConsumed = false;
  9310. if (!resolver) {
  9311. return;
  9312. }
  9313. try {
  9314. resolver(function (value) {
  9315. _this._resolve(value);
  9316. }, function (reason) {
  9317. _this._reject(reason);
  9318. });
  9319. }
  9320. catch (e) {
  9321. this._reject(e);
  9322. }
  9323. }
  9324. InternalPromise.prototype.catch = function (onRejected) {
  9325. return this.then(undefined, onRejected);
  9326. };
  9327. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9328. var _this = this;
  9329. var newPromise = new InternalPromise();
  9330. newPromise._onFulfilled = onFulfilled;
  9331. newPromise._onRejected = onRejected;
  9332. // Composition
  9333. this._children.push(newPromise);
  9334. if (this._state !== PromiseStates.Pending) {
  9335. BABYLON.Tools.SetImmediate(function () {
  9336. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9337. var returnedValue = newPromise._resolve(_this._result);
  9338. if (returnedValue !== undefined && returnedValue !== null) {
  9339. if (returnedValue._state !== undefined) {
  9340. var returnedPromise = returnedValue;
  9341. newPromise._children.push(returnedPromise);
  9342. newPromise = returnedPromise;
  9343. }
  9344. else {
  9345. newPromise._result = returnedValue;
  9346. }
  9347. }
  9348. }
  9349. else {
  9350. newPromise._reject(_this._reason);
  9351. }
  9352. });
  9353. }
  9354. return newPromise;
  9355. };
  9356. InternalPromise.prototype._moveChildren = function (children) {
  9357. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9358. if (this._state === PromiseStates.Fulfilled) {
  9359. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9360. var child = _b[_i];
  9361. child._resolve(this._result);
  9362. }
  9363. }
  9364. else if (this._state === PromiseStates.Rejected) {
  9365. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9366. var child = _d[_c];
  9367. child._reject(this._reason);
  9368. }
  9369. }
  9370. var _a;
  9371. };
  9372. InternalPromise.prototype._resolve = function (value) {
  9373. try {
  9374. this._state = PromiseStates.Fulfilled;
  9375. this._result = value;
  9376. var returnedValue = null;
  9377. if (this._onFulfilled) {
  9378. returnedValue = this._onFulfilled(value);
  9379. }
  9380. if (returnedValue !== undefined && returnedValue !== null) {
  9381. if (returnedValue._state !== undefined) {
  9382. // Transmit children
  9383. var returnedPromise = returnedValue;
  9384. returnedPromise._moveChildren(this._children);
  9385. }
  9386. else {
  9387. value = returnedValue;
  9388. }
  9389. }
  9390. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9391. var child = _a[_i];
  9392. child._resolve(value);
  9393. }
  9394. this._children.length = 0;
  9395. delete this._onFulfilled;
  9396. delete this._onRejected;
  9397. return returnedValue;
  9398. }
  9399. catch (e) {
  9400. this._reject(e, true);
  9401. }
  9402. return null;
  9403. };
  9404. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9405. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9406. this._state = PromiseStates.Rejected;
  9407. this._reason = reason;
  9408. if (this._onRejected && !onLocalThrow) {
  9409. try {
  9410. this._onRejected(reason);
  9411. this._rejectWasConsumed = true;
  9412. }
  9413. catch (e) {
  9414. reason = e;
  9415. }
  9416. }
  9417. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9418. var child = _a[_i];
  9419. if (this._rejectWasConsumed) {
  9420. child._resolve(null);
  9421. }
  9422. else {
  9423. child._reject(reason);
  9424. }
  9425. }
  9426. this._children.length = 0;
  9427. delete this._onFulfilled;
  9428. delete this._onRejected;
  9429. };
  9430. InternalPromise.resolve = function (value) {
  9431. var newPromise = new InternalPromise();
  9432. newPromise._resolve(value);
  9433. return newPromise;
  9434. };
  9435. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9436. promise.then(function (value) {
  9437. agregator.results[index] = value;
  9438. agregator.count++;
  9439. if (agregator.count === agregator.target) {
  9440. agregator.rootPromise._resolve(agregator.results);
  9441. }
  9442. return null;
  9443. }, function (reason) {
  9444. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9445. agregator.rootPromise._reject(reason);
  9446. }
  9447. });
  9448. };
  9449. InternalPromise.all = function (promises) {
  9450. var newPromise = new InternalPromise();
  9451. var agregator = new FulFillmentAgregator();
  9452. agregator.target = promises.length;
  9453. agregator.rootPromise = newPromise;
  9454. if (promises.length) {
  9455. for (var index = 0; index < promises.length; index++) {
  9456. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9457. }
  9458. }
  9459. else {
  9460. newPromise._resolve([]);
  9461. }
  9462. return newPromise;
  9463. };
  9464. return InternalPromise;
  9465. }());
  9466. /**
  9467. * Helper class that provides a small promise polyfill
  9468. */
  9469. var PromisePolyfill = /** @class */ (function () {
  9470. function PromisePolyfill() {
  9471. }
  9472. /**
  9473. * Static function used to check if the polyfill is required
  9474. * If this is the case then the function will inject the polyfill to window.Promise
  9475. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9476. */
  9477. PromisePolyfill.Apply = function (force) {
  9478. if (force === void 0) { force = false; }
  9479. if (force || typeof Promise === 'undefined') {
  9480. var root = window;
  9481. root.Promise = InternalPromise;
  9482. }
  9483. };
  9484. return PromisePolyfill;
  9485. }());
  9486. BABYLON.PromisePolyfill = PromisePolyfill;
  9487. })(BABYLON || (BABYLON = {}));
  9488. //# sourceMappingURL=babylon.promise.js.map
  9489. var BABYLON;
  9490. (function (BABYLON) {
  9491. var _AlphaState = /** @class */ (function () {
  9492. /**
  9493. * Initializes the state.
  9494. */
  9495. function _AlphaState() {
  9496. this._isAlphaBlendDirty = false;
  9497. this._isBlendFunctionParametersDirty = false;
  9498. this._isBlendEquationParametersDirty = false;
  9499. this._isBlendConstantsDirty = false;
  9500. this._alphaBlend = false;
  9501. this._blendFunctionParameters = new Array(4);
  9502. this._blendEquationParameters = new Array(2);
  9503. this._blendConstants = new Array(4);
  9504. this.reset();
  9505. }
  9506. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9507. get: function () {
  9508. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9509. },
  9510. enumerable: true,
  9511. configurable: true
  9512. });
  9513. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9514. get: function () {
  9515. return this._alphaBlend;
  9516. },
  9517. set: function (value) {
  9518. if (this._alphaBlend === value) {
  9519. return;
  9520. }
  9521. this._alphaBlend = value;
  9522. this._isAlphaBlendDirty = true;
  9523. },
  9524. enumerable: true,
  9525. configurable: true
  9526. });
  9527. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9528. if (this._blendConstants[0] === r &&
  9529. this._blendConstants[1] === g &&
  9530. this._blendConstants[2] === b &&
  9531. this._blendConstants[3] === a) {
  9532. return;
  9533. }
  9534. this._blendConstants[0] = r;
  9535. this._blendConstants[1] = g;
  9536. this._blendConstants[2] = b;
  9537. this._blendConstants[3] = a;
  9538. this._isBlendConstantsDirty = true;
  9539. };
  9540. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9541. if (this._blendFunctionParameters[0] === value0 &&
  9542. this._blendFunctionParameters[1] === value1 &&
  9543. this._blendFunctionParameters[2] === value2 &&
  9544. this._blendFunctionParameters[3] === value3) {
  9545. return;
  9546. }
  9547. this._blendFunctionParameters[0] = value0;
  9548. this._blendFunctionParameters[1] = value1;
  9549. this._blendFunctionParameters[2] = value2;
  9550. this._blendFunctionParameters[3] = value3;
  9551. this._isBlendFunctionParametersDirty = true;
  9552. };
  9553. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9554. if (this._blendEquationParameters[0] === rgb &&
  9555. this._blendEquationParameters[1] === alpha) {
  9556. return;
  9557. }
  9558. this._blendEquationParameters[0] = rgb;
  9559. this._blendEquationParameters[1] = alpha;
  9560. this._isBlendEquationParametersDirty = true;
  9561. };
  9562. _AlphaState.prototype.reset = function () {
  9563. this._alphaBlend = false;
  9564. this._blendFunctionParameters[0] = null;
  9565. this._blendFunctionParameters[1] = null;
  9566. this._blendFunctionParameters[2] = null;
  9567. this._blendFunctionParameters[3] = null;
  9568. this._blendEquationParameters[0] = null;
  9569. this._blendEquationParameters[1] = null;
  9570. this._blendConstants[0] = null;
  9571. this._blendConstants[1] = null;
  9572. this._blendConstants[2] = null;
  9573. this._blendConstants[3] = null;
  9574. this._isAlphaBlendDirty = true;
  9575. this._isBlendFunctionParametersDirty = false;
  9576. this._isBlendEquationParametersDirty = false;
  9577. this._isBlendConstantsDirty = false;
  9578. };
  9579. _AlphaState.prototype.apply = function (gl) {
  9580. if (!this.isDirty) {
  9581. return;
  9582. }
  9583. // Alpha blend
  9584. if (this._isAlphaBlendDirty) {
  9585. if (this._alphaBlend) {
  9586. gl.enable(gl.BLEND);
  9587. }
  9588. else {
  9589. gl.disable(gl.BLEND);
  9590. }
  9591. this._isAlphaBlendDirty = false;
  9592. }
  9593. // Alpha function
  9594. if (this._isBlendFunctionParametersDirty) {
  9595. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9596. this._isBlendFunctionParametersDirty = false;
  9597. }
  9598. // Alpha equation
  9599. if (this._isBlendEquationParametersDirty) {
  9600. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9601. this._isBlendEquationParametersDirty = false;
  9602. }
  9603. // Constants
  9604. if (this._isBlendConstantsDirty) {
  9605. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9606. this._isBlendConstantsDirty = false;
  9607. }
  9608. };
  9609. return _AlphaState;
  9610. }());
  9611. BABYLON._AlphaState = _AlphaState;
  9612. })(BABYLON || (BABYLON = {}));
  9613. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9614. var BABYLON;
  9615. (function (BABYLON) {
  9616. var _DepthCullingState = /** @class */ (function () {
  9617. /**
  9618. * Initializes the state.
  9619. */
  9620. function _DepthCullingState() {
  9621. this._isDepthTestDirty = false;
  9622. this._isDepthMaskDirty = false;
  9623. this._isDepthFuncDirty = false;
  9624. this._isCullFaceDirty = false;
  9625. this._isCullDirty = false;
  9626. this._isZOffsetDirty = false;
  9627. this._isFrontFaceDirty = false;
  9628. this.reset();
  9629. }
  9630. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9631. get: function () {
  9632. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9633. },
  9634. enumerable: true,
  9635. configurable: true
  9636. });
  9637. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9638. get: function () {
  9639. return this._zOffset;
  9640. },
  9641. set: function (value) {
  9642. if (this._zOffset === value) {
  9643. return;
  9644. }
  9645. this._zOffset = value;
  9646. this._isZOffsetDirty = true;
  9647. },
  9648. enumerable: true,
  9649. configurable: true
  9650. });
  9651. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9652. get: function () {
  9653. return this._cullFace;
  9654. },
  9655. set: function (value) {
  9656. if (this._cullFace === value) {
  9657. return;
  9658. }
  9659. this._cullFace = value;
  9660. this._isCullFaceDirty = true;
  9661. },
  9662. enumerable: true,
  9663. configurable: true
  9664. });
  9665. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9666. get: function () {
  9667. return this._cull;
  9668. },
  9669. set: function (value) {
  9670. if (this._cull === value) {
  9671. return;
  9672. }
  9673. this._cull = value;
  9674. this._isCullDirty = true;
  9675. },
  9676. enumerable: true,
  9677. configurable: true
  9678. });
  9679. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9680. get: function () {
  9681. return this._depthFunc;
  9682. },
  9683. set: function (value) {
  9684. if (this._depthFunc === value) {
  9685. return;
  9686. }
  9687. this._depthFunc = value;
  9688. this._isDepthFuncDirty = true;
  9689. },
  9690. enumerable: true,
  9691. configurable: true
  9692. });
  9693. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9694. get: function () {
  9695. return this._depthMask;
  9696. },
  9697. set: function (value) {
  9698. if (this._depthMask === value) {
  9699. return;
  9700. }
  9701. this._depthMask = value;
  9702. this._isDepthMaskDirty = true;
  9703. },
  9704. enumerable: true,
  9705. configurable: true
  9706. });
  9707. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9708. get: function () {
  9709. return this._depthTest;
  9710. },
  9711. set: function (value) {
  9712. if (this._depthTest === value) {
  9713. return;
  9714. }
  9715. this._depthTest = value;
  9716. this._isDepthTestDirty = true;
  9717. },
  9718. enumerable: true,
  9719. configurable: true
  9720. });
  9721. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9722. get: function () {
  9723. return this._frontFace;
  9724. },
  9725. set: function (value) {
  9726. if (this._frontFace === value) {
  9727. return;
  9728. }
  9729. this._frontFace = value;
  9730. this._isFrontFaceDirty = true;
  9731. },
  9732. enumerable: true,
  9733. configurable: true
  9734. });
  9735. _DepthCullingState.prototype.reset = function () {
  9736. this._depthMask = true;
  9737. this._depthTest = true;
  9738. this._depthFunc = null;
  9739. this._cullFace = null;
  9740. this._cull = null;
  9741. this._zOffset = 0;
  9742. this._frontFace = null;
  9743. this._isDepthTestDirty = true;
  9744. this._isDepthMaskDirty = true;
  9745. this._isDepthFuncDirty = false;
  9746. this._isCullFaceDirty = false;
  9747. this._isCullDirty = false;
  9748. this._isZOffsetDirty = false;
  9749. this._isFrontFaceDirty = false;
  9750. };
  9751. _DepthCullingState.prototype.apply = function (gl) {
  9752. if (!this.isDirty) {
  9753. return;
  9754. }
  9755. // Cull
  9756. if (this._isCullDirty) {
  9757. if (this.cull) {
  9758. gl.enable(gl.CULL_FACE);
  9759. }
  9760. else {
  9761. gl.disable(gl.CULL_FACE);
  9762. }
  9763. this._isCullDirty = false;
  9764. }
  9765. // Cull face
  9766. if (this._isCullFaceDirty) {
  9767. gl.cullFace(this.cullFace);
  9768. this._isCullFaceDirty = false;
  9769. }
  9770. // Depth mask
  9771. if (this._isDepthMaskDirty) {
  9772. gl.depthMask(this.depthMask);
  9773. this._isDepthMaskDirty = false;
  9774. }
  9775. // Depth test
  9776. if (this._isDepthTestDirty) {
  9777. if (this.depthTest) {
  9778. gl.enable(gl.DEPTH_TEST);
  9779. }
  9780. else {
  9781. gl.disable(gl.DEPTH_TEST);
  9782. }
  9783. this._isDepthTestDirty = false;
  9784. }
  9785. // Depth func
  9786. if (this._isDepthFuncDirty) {
  9787. gl.depthFunc(this.depthFunc);
  9788. this._isDepthFuncDirty = false;
  9789. }
  9790. // zOffset
  9791. if (this._isZOffsetDirty) {
  9792. if (this.zOffset) {
  9793. gl.enable(gl.POLYGON_OFFSET_FILL);
  9794. gl.polygonOffset(this.zOffset, 0);
  9795. }
  9796. else {
  9797. gl.disable(gl.POLYGON_OFFSET_FILL);
  9798. }
  9799. this._isZOffsetDirty = false;
  9800. }
  9801. // Front face
  9802. if (this._isFrontFaceDirty) {
  9803. gl.frontFace(this.frontFace);
  9804. this._isFrontFaceDirty = false;
  9805. }
  9806. };
  9807. return _DepthCullingState;
  9808. }());
  9809. BABYLON._DepthCullingState = _DepthCullingState;
  9810. })(BABYLON || (BABYLON = {}));
  9811. //# sourceMappingURL=babylon.depthCullingState.js.map
  9812. var BABYLON;
  9813. (function (BABYLON) {
  9814. var _StencilState = /** @class */ (function () {
  9815. function _StencilState() {
  9816. this._isStencilTestDirty = false;
  9817. this._isStencilMaskDirty = false;
  9818. this._isStencilFuncDirty = false;
  9819. this._isStencilOpDirty = false;
  9820. this.reset();
  9821. }
  9822. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9823. get: function () {
  9824. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9825. },
  9826. enumerable: true,
  9827. configurable: true
  9828. });
  9829. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9830. get: function () {
  9831. return this._stencilFunc;
  9832. },
  9833. set: function (value) {
  9834. if (this._stencilFunc === value) {
  9835. return;
  9836. }
  9837. this._stencilFunc = value;
  9838. this._isStencilFuncDirty = true;
  9839. },
  9840. enumerable: true,
  9841. configurable: true
  9842. });
  9843. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9844. get: function () {
  9845. return this._stencilFuncRef;
  9846. },
  9847. set: function (value) {
  9848. if (this._stencilFuncRef === value) {
  9849. return;
  9850. }
  9851. this._stencilFuncRef = value;
  9852. this._isStencilFuncDirty = true;
  9853. },
  9854. enumerable: true,
  9855. configurable: true
  9856. });
  9857. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9858. get: function () {
  9859. return this._stencilFuncMask;
  9860. },
  9861. set: function (value) {
  9862. if (this._stencilFuncMask === value) {
  9863. return;
  9864. }
  9865. this._stencilFuncMask = value;
  9866. this._isStencilFuncDirty = true;
  9867. },
  9868. enumerable: true,
  9869. configurable: true
  9870. });
  9871. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9872. get: function () {
  9873. return this._stencilOpStencilFail;
  9874. },
  9875. set: function (value) {
  9876. if (this._stencilOpStencilFail === value) {
  9877. return;
  9878. }
  9879. this._stencilOpStencilFail = value;
  9880. this._isStencilOpDirty = true;
  9881. },
  9882. enumerable: true,
  9883. configurable: true
  9884. });
  9885. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9886. get: function () {
  9887. return this._stencilOpDepthFail;
  9888. },
  9889. set: function (value) {
  9890. if (this._stencilOpDepthFail === value) {
  9891. return;
  9892. }
  9893. this._stencilOpDepthFail = value;
  9894. this._isStencilOpDirty = true;
  9895. },
  9896. enumerable: true,
  9897. configurable: true
  9898. });
  9899. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9900. get: function () {
  9901. return this._stencilOpStencilDepthPass;
  9902. },
  9903. set: function (value) {
  9904. if (this._stencilOpStencilDepthPass === value) {
  9905. return;
  9906. }
  9907. this._stencilOpStencilDepthPass = value;
  9908. this._isStencilOpDirty = true;
  9909. },
  9910. enumerable: true,
  9911. configurable: true
  9912. });
  9913. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9914. get: function () {
  9915. return this._stencilMask;
  9916. },
  9917. set: function (value) {
  9918. if (this._stencilMask === value) {
  9919. return;
  9920. }
  9921. this._stencilMask = value;
  9922. this._isStencilMaskDirty = true;
  9923. },
  9924. enumerable: true,
  9925. configurable: true
  9926. });
  9927. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9928. get: function () {
  9929. return this._stencilTest;
  9930. },
  9931. set: function (value) {
  9932. if (this._stencilTest === value) {
  9933. return;
  9934. }
  9935. this._stencilTest = value;
  9936. this._isStencilTestDirty = true;
  9937. },
  9938. enumerable: true,
  9939. configurable: true
  9940. });
  9941. _StencilState.prototype.reset = function () {
  9942. this._stencilTest = false;
  9943. this._stencilMask = 0xFF;
  9944. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9945. this._stencilFuncRef = 1;
  9946. this._stencilFuncMask = 0xFF;
  9947. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9948. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9949. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9950. this._isStencilTestDirty = true;
  9951. this._isStencilMaskDirty = true;
  9952. this._isStencilFuncDirty = true;
  9953. this._isStencilOpDirty = true;
  9954. };
  9955. _StencilState.prototype.apply = function (gl) {
  9956. if (!this.isDirty) {
  9957. return;
  9958. }
  9959. // Stencil test
  9960. if (this._isStencilTestDirty) {
  9961. if (this.stencilTest) {
  9962. gl.enable(gl.STENCIL_TEST);
  9963. }
  9964. else {
  9965. gl.disable(gl.STENCIL_TEST);
  9966. }
  9967. this._isStencilTestDirty = false;
  9968. }
  9969. // Stencil mask
  9970. if (this._isStencilMaskDirty) {
  9971. gl.stencilMask(this.stencilMask);
  9972. this._isStencilMaskDirty = false;
  9973. }
  9974. // Stencil func
  9975. if (this._isStencilFuncDirty) {
  9976. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9977. this._isStencilFuncDirty = false;
  9978. }
  9979. // Stencil op
  9980. if (this._isStencilOpDirty) {
  9981. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9982. this._isStencilOpDirty = false;
  9983. }
  9984. };
  9985. return _StencilState;
  9986. }());
  9987. BABYLON._StencilState = _StencilState;
  9988. })(BABYLON || (BABYLON = {}));
  9989. //# sourceMappingURL=babylon.stencilState.js.map
  9990. var BABYLON;
  9991. (function (BABYLON) {
  9992. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9993. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9994. };
  9995. var compileRawShader = function (gl, source, type) {
  9996. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9997. gl.shaderSource(shader, source);
  9998. gl.compileShader(shader);
  9999. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10000. var log = gl.getShaderInfoLog(shader);
  10001. if (log) {
  10002. throw new Error(log);
  10003. }
  10004. }
  10005. if (!shader) {
  10006. throw new Error("Something went wrong while compile the shader.");
  10007. }
  10008. return shader;
  10009. };
  10010. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10011. var magFilter = gl.NEAREST;
  10012. var minFilter = gl.NEAREST;
  10013. switch (samplingMode) {
  10014. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10015. magFilter = gl.LINEAR;
  10016. if (generateMipMaps) {
  10017. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10018. }
  10019. else {
  10020. minFilter = gl.LINEAR;
  10021. }
  10022. break;
  10023. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10024. magFilter = gl.LINEAR;
  10025. if (generateMipMaps) {
  10026. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10027. }
  10028. else {
  10029. minFilter = gl.LINEAR;
  10030. }
  10031. break;
  10032. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10033. magFilter = gl.NEAREST;
  10034. if (generateMipMaps) {
  10035. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10036. }
  10037. else {
  10038. minFilter = gl.NEAREST;
  10039. }
  10040. break;
  10041. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10042. magFilter = gl.NEAREST;
  10043. if (generateMipMaps) {
  10044. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10045. }
  10046. else {
  10047. minFilter = gl.NEAREST;
  10048. }
  10049. break;
  10050. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10051. magFilter = gl.NEAREST;
  10052. if (generateMipMaps) {
  10053. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10054. }
  10055. else {
  10056. minFilter = gl.LINEAR;
  10057. }
  10058. break;
  10059. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10060. magFilter = gl.NEAREST;
  10061. if (generateMipMaps) {
  10062. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10063. }
  10064. else {
  10065. minFilter = gl.LINEAR;
  10066. }
  10067. break;
  10068. case BABYLON.Texture.NEAREST_LINEAR:
  10069. magFilter = gl.NEAREST;
  10070. minFilter = gl.LINEAR;
  10071. break;
  10072. case BABYLON.Texture.NEAREST_NEAREST:
  10073. magFilter = gl.NEAREST;
  10074. minFilter = gl.NEAREST;
  10075. break;
  10076. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10077. magFilter = gl.LINEAR;
  10078. if (generateMipMaps) {
  10079. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10080. }
  10081. else {
  10082. minFilter = gl.NEAREST;
  10083. }
  10084. break;
  10085. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10086. magFilter = gl.LINEAR;
  10087. if (generateMipMaps) {
  10088. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10089. }
  10090. else {
  10091. minFilter = gl.NEAREST;
  10092. }
  10093. break;
  10094. case BABYLON.Texture.LINEAR_LINEAR:
  10095. magFilter = gl.LINEAR;
  10096. minFilter = gl.LINEAR;
  10097. break;
  10098. case BABYLON.Texture.LINEAR_NEAREST:
  10099. magFilter = gl.LINEAR;
  10100. minFilter = gl.NEAREST;
  10101. break;
  10102. }
  10103. return {
  10104. min: minFilter,
  10105. mag: magFilter
  10106. };
  10107. };
  10108. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10109. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10110. var img;
  10111. var onload = function () {
  10112. loadedImages[index] = img;
  10113. loadedImages._internalCount++;
  10114. if (scene) {
  10115. scene._removePendingData(img);
  10116. }
  10117. if (loadedImages._internalCount === 6) {
  10118. onfinish(loadedImages);
  10119. }
  10120. };
  10121. var onerror = function (message, exception) {
  10122. if (scene) {
  10123. scene._removePendingData(img);
  10124. }
  10125. if (onErrorCallBack) {
  10126. onErrorCallBack(message, exception);
  10127. }
  10128. };
  10129. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10130. if (scene) {
  10131. scene._addPendingData(img);
  10132. }
  10133. };
  10134. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10135. if (onError === void 0) { onError = null; }
  10136. var loadedImages = [];
  10137. loadedImages._internalCount = 0;
  10138. for (var index = 0; index < 6; index++) {
  10139. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10140. }
  10141. };
  10142. var BufferPointer = /** @class */ (function () {
  10143. function BufferPointer() {
  10144. }
  10145. return BufferPointer;
  10146. }());
  10147. var InstancingAttributeInfo = /** @class */ (function () {
  10148. function InstancingAttributeInfo() {
  10149. }
  10150. return InstancingAttributeInfo;
  10151. }());
  10152. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10153. /**
  10154. * Define options used to create a render target texture
  10155. */
  10156. var RenderTargetCreationOptions = /** @class */ (function () {
  10157. function RenderTargetCreationOptions() {
  10158. }
  10159. return RenderTargetCreationOptions;
  10160. }());
  10161. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10162. /**
  10163. * Regroup several parameters relative to the browser in use
  10164. */
  10165. var EngineCapabilities = /** @class */ (function () {
  10166. function EngineCapabilities() {
  10167. }
  10168. return EngineCapabilities;
  10169. }());
  10170. BABYLON.EngineCapabilities = EngineCapabilities;
  10171. /**
  10172. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10173. */
  10174. var Engine = /** @class */ (function () {
  10175. /**
  10176. * @constructor
  10177. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10178. * @param antialias defines enable antialiasing (default: false)
  10179. * @param options defines further options to be sent to the getContext() function
  10180. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10181. */
  10182. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10183. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10184. var _this = this;
  10185. // Public members
  10186. this.forcePOTTextures = false;
  10187. this.isFullscreen = false;
  10188. this.isPointerLock = false;
  10189. this.cullBackFaces = true;
  10190. this.renderEvenInBackground = true;
  10191. this.preventCacheWipeBetweenFrames = false;
  10192. // To enable/disable IDB support and avoid XHR on .manifest
  10193. this.enableOfflineSupport = false;
  10194. this.scenes = new Array();
  10195. this.postProcesses = new Array();
  10196. // Observables
  10197. /**
  10198. * Observable event triggered each time the rendering canvas is resized
  10199. */
  10200. this.onResizeObservable = new BABYLON.Observable();
  10201. /**
  10202. * Observable event triggered each time the canvas loses focus
  10203. */
  10204. this.onCanvasBlurObservable = new BABYLON.Observable();
  10205. /**
  10206. * Observable event triggered each time the canvas gains focus
  10207. */
  10208. this.onCanvasFocusObservable = new BABYLON.Observable();
  10209. /**
  10210. * Observable event triggered each time the canvas receives pointerout event
  10211. */
  10212. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10213. /**
  10214. * Observable event triggered before each texture is initialized
  10215. */
  10216. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10217. //WebVR
  10218. this._vrDisplay = undefined;
  10219. this._vrSupported = false;
  10220. this._vrExclusivePointerMode = false;
  10221. // Uniform buffers list
  10222. this.disableUniformBuffers = false;
  10223. this._uniformBuffers = new Array();
  10224. // Observables
  10225. /**
  10226. * Observable raised when the engine begins a new frame
  10227. */
  10228. this.onBeginFrameObservable = new BABYLON.Observable();
  10229. /**
  10230. * Observable raised when the engine ends the current frame
  10231. */
  10232. this.onEndFrameObservable = new BABYLON.Observable();
  10233. /**
  10234. * Observable raised when the engine is about to compile a shader
  10235. */
  10236. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10237. /**
  10238. * Observable raised when the engine has jsut compiled a shader
  10239. */
  10240. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10241. this._windowIsBackground = false;
  10242. this._webGLVersion = 1.0;
  10243. this._badOS = false;
  10244. this._badDesktopOS = false;
  10245. /**
  10246. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10247. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10248. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10249. */
  10250. this.disableTextureBindingOptimization = false;
  10251. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10252. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10253. this.onVRRequestPresentStart = new BABYLON.Observable();
  10254. this._colorWrite = true;
  10255. this._drawCalls = new BABYLON.PerfCounter();
  10256. this._textureCollisions = new BABYLON.PerfCounter();
  10257. this._renderingQueueLaunched = false;
  10258. this._activeRenderLoops = new Array();
  10259. // Deterministic lockstepMaxSteps
  10260. this._deterministicLockstep = false;
  10261. this._lockstepMaxSteps = 4;
  10262. // Lost context
  10263. this.onContextLostObservable = new BABYLON.Observable();
  10264. this.onContextRestoredObservable = new BABYLON.Observable();
  10265. this._contextWasLost = false;
  10266. this._doNotHandleContextLost = false;
  10267. // FPS
  10268. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10269. this._fps = 60;
  10270. this._deltaTime = 0;
  10271. /**
  10272. * Turn this value on if you want to pause FPS computation when in background
  10273. */
  10274. this.disablePerformanceMonitorInBackground = false;
  10275. // States
  10276. this._depthCullingState = new BABYLON._DepthCullingState();
  10277. this._stencilState = new BABYLON._StencilState();
  10278. this._alphaState = new BABYLON._AlphaState();
  10279. this._alphaMode = Engine.ALPHA_DISABLE;
  10280. // Cache
  10281. this._internalTexturesCache = new Array();
  10282. this._activeChannel = 0;
  10283. this._currentTextureChannel = -1;
  10284. this._boundTexturesCache = {};
  10285. this._compiledEffects = {};
  10286. this._vertexAttribArraysEnabled = [];
  10287. this._uintIndicesCurrentlySet = false;
  10288. this._currentBoundBuffer = new Array();
  10289. this._currentBufferPointers = new Array();
  10290. this._currentInstanceLocations = new Array();
  10291. this._currentInstanceBuffers = new Array();
  10292. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10293. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10294. this._vaoRecordInProgress = false;
  10295. this._mustWipeVertexAttributes = false;
  10296. this._nextFreeTextureSlots = new Array();
  10297. this._maxSimultaneousTextures = 0;
  10298. this._activeRequests = new Array();
  10299. // Hardware supported Compressed Textures
  10300. this._texturesSupported = new Array();
  10301. this._onVRFullScreenTriggered = function () {
  10302. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10303. //get the old size before we change
  10304. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10305. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10306. //get the width and height, change the render size
  10307. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10308. _this.setHardwareScalingLevel(1);
  10309. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10310. }
  10311. else {
  10312. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10313. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10314. }
  10315. };
  10316. this._boundUniforms = {};
  10317. // Register promises
  10318. BABYLON.PromisePolyfill.Apply();
  10319. var canvas = null;
  10320. Engine.Instances.push(this);
  10321. if (!canvasOrContext) {
  10322. return;
  10323. }
  10324. options = options || {};
  10325. if (canvasOrContext.getContext) {
  10326. canvas = canvasOrContext;
  10327. this._renderingCanvas = canvas;
  10328. if (antialias != null) {
  10329. options.antialias = antialias;
  10330. }
  10331. if (options.deterministicLockstep === undefined) {
  10332. options.deterministicLockstep = false;
  10333. }
  10334. if (options.lockstepMaxSteps === undefined) {
  10335. options.lockstepMaxSteps = 4;
  10336. }
  10337. if (options.preserveDrawingBuffer === undefined) {
  10338. options.preserveDrawingBuffer = false;
  10339. }
  10340. if (options.audioEngine === undefined) {
  10341. options.audioEngine = true;
  10342. }
  10343. if (options.stencil === undefined) {
  10344. options.stencil = true;
  10345. }
  10346. this._deterministicLockstep = options.deterministicLockstep;
  10347. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10348. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10349. // Exceptions
  10350. if (navigator && navigator.userAgent) {
  10351. var ua = navigator.userAgent;
  10352. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10353. var exception = _a[_i];
  10354. var key = exception.key;
  10355. var targets = exception.targets;
  10356. if (ua.indexOf(key) > -1) {
  10357. if (exception.capture && exception.captureConstraint) {
  10358. var capture = exception.capture;
  10359. var constraint = exception.captureConstraint;
  10360. var regex = new RegExp(capture);
  10361. var matches = regex.exec(ua);
  10362. if (matches && matches.length > 0) {
  10363. var capturedValue = parseInt(matches[matches.length - 1]);
  10364. if (capturedValue >= constraint) {
  10365. continue;
  10366. }
  10367. }
  10368. }
  10369. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10370. var target = targets_1[_b];
  10371. switch (target) {
  10372. case "uniformBuffer":
  10373. this.disableUniformBuffers = true;
  10374. break;
  10375. case "textureBindingOptimization":
  10376. this.disableTextureBindingOptimization = true;
  10377. break;
  10378. }
  10379. }
  10380. break;
  10381. }
  10382. }
  10383. }
  10384. // GL
  10385. if (!options.disableWebGL2Support) {
  10386. try {
  10387. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10388. if (this._gl) {
  10389. this._webGLVersion = 2.0;
  10390. }
  10391. }
  10392. catch (e) {
  10393. // Do nothing
  10394. }
  10395. }
  10396. if (!this._gl) {
  10397. if (!canvas) {
  10398. throw new Error("The provided canvas is null or undefined.");
  10399. }
  10400. try {
  10401. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10402. }
  10403. catch (e) {
  10404. throw new Error("WebGL not supported");
  10405. }
  10406. }
  10407. if (!this._gl) {
  10408. throw new Error("WebGL not supported");
  10409. }
  10410. this._onCanvasFocus = function () {
  10411. _this.onCanvasFocusObservable.notifyObservers(_this);
  10412. };
  10413. this._onCanvasBlur = function () {
  10414. _this.onCanvasBlurObservable.notifyObservers(_this);
  10415. };
  10416. canvas.addEventListener("focus", this._onCanvasFocus);
  10417. canvas.addEventListener("blur", this._onCanvasBlur);
  10418. this._onBlur = function () {
  10419. if (_this.disablePerformanceMonitorInBackground) {
  10420. _this._performanceMonitor.disable();
  10421. }
  10422. _this._windowIsBackground = true;
  10423. };
  10424. this._onFocus = function () {
  10425. if (_this.disablePerformanceMonitorInBackground) {
  10426. _this._performanceMonitor.enable();
  10427. }
  10428. _this._windowIsBackground = false;
  10429. };
  10430. this._onCanvasPointerOut = function () {
  10431. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  10432. };
  10433. window.addEventListener("blur", this._onBlur);
  10434. window.addEventListener("focus", this._onFocus);
  10435. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10436. // Context lost
  10437. if (!this._doNotHandleContextLost) {
  10438. this._onContextLost = function (evt) {
  10439. evt.preventDefault();
  10440. _this._contextWasLost = true;
  10441. BABYLON.Tools.Warn("WebGL context lost.");
  10442. _this.onContextLostObservable.notifyObservers(_this);
  10443. };
  10444. this._onContextRestored = function (evt) {
  10445. // Adding a timeout to avoid race condition at browser level
  10446. setTimeout(function () {
  10447. // Rebuild gl context
  10448. _this._initGLContext();
  10449. // Rebuild effects
  10450. _this._rebuildEffects();
  10451. // Rebuild textures
  10452. _this._rebuildInternalTextures();
  10453. // Rebuild buffers
  10454. _this._rebuildBuffers();
  10455. // Cache
  10456. _this.wipeCaches(true);
  10457. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10458. _this.onContextRestoredObservable.notifyObservers(_this);
  10459. _this._contextWasLost = false;
  10460. }, 0);
  10461. };
  10462. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10463. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10464. }
  10465. }
  10466. else {
  10467. this._gl = canvasOrContext;
  10468. this._renderingCanvas = this._gl.canvas;
  10469. if (this._gl.renderbufferStorageMultisample) {
  10470. this._webGLVersion = 2.0;
  10471. }
  10472. options.stencil = this._gl.getContextAttributes().stencil;
  10473. }
  10474. // Viewport
  10475. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10476. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10477. this.resize();
  10478. this._isStencilEnable = options.stencil ? true : false;
  10479. this._initGLContext();
  10480. if (canvas) {
  10481. // Fullscreen
  10482. this._onFullscreenChange = function () {
  10483. if (document.fullscreen !== undefined) {
  10484. _this.isFullscreen = document.fullscreen;
  10485. }
  10486. else if (document.mozFullScreen !== undefined) {
  10487. _this.isFullscreen = document.mozFullScreen;
  10488. }
  10489. else if (document.webkitIsFullScreen !== undefined) {
  10490. _this.isFullscreen = document.webkitIsFullScreen;
  10491. }
  10492. else if (document.msIsFullScreen !== undefined) {
  10493. _this.isFullscreen = document.msIsFullScreen;
  10494. }
  10495. // Pointer lock
  10496. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10497. canvas.requestPointerLock = canvas.requestPointerLock ||
  10498. canvas.msRequestPointerLock ||
  10499. canvas.mozRequestPointerLock ||
  10500. canvas.webkitRequestPointerLock;
  10501. if (canvas.requestPointerLock) {
  10502. canvas.requestPointerLock();
  10503. }
  10504. }
  10505. };
  10506. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10507. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10508. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10509. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10510. // Pointer lock
  10511. this._onPointerLockChange = function () {
  10512. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10513. document.webkitPointerLockElement === canvas ||
  10514. document.msPointerLockElement === canvas ||
  10515. document.pointerLockElement === canvas);
  10516. };
  10517. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10518. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10519. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10520. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10521. this._onVRDisplayPointerRestricted = function () {
  10522. if (canvas) {
  10523. canvas.requestPointerLock();
  10524. }
  10525. };
  10526. this._onVRDisplayPointerUnrestricted = function () {
  10527. document.exitPointerLock();
  10528. };
  10529. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10530. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10531. }
  10532. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10533. Engine.audioEngine = new BABYLON.AudioEngine();
  10534. }
  10535. // Prepare buffer pointers
  10536. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10537. this._currentBufferPointers[i] = new BufferPointer();
  10538. }
  10539. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10540. // Load WebVR Devices
  10541. if (options.autoEnableWebVR) {
  10542. this.initWebVR();
  10543. }
  10544. // Detect if we are running on a faulty buggy OS.
  10545. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10546. // Detect if we are running on a faulty buggy desktop OS.
  10547. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10548. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10549. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10550. }
  10551. Object.defineProperty(Engine, "LastCreatedEngine", {
  10552. get: function () {
  10553. if (Engine.Instances.length === 0) {
  10554. return null;
  10555. }
  10556. return Engine.Instances[Engine.Instances.length - 1];
  10557. },
  10558. enumerable: true,
  10559. configurable: true
  10560. });
  10561. Object.defineProperty(Engine, "LastCreatedScene", {
  10562. get: function () {
  10563. var lastCreatedEngine = Engine.LastCreatedEngine;
  10564. if (!lastCreatedEngine) {
  10565. return null;
  10566. }
  10567. if (lastCreatedEngine.scenes.length === 0) {
  10568. return null;
  10569. }
  10570. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10571. },
  10572. enumerable: true,
  10573. configurable: true
  10574. });
  10575. /**
  10576. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10577. */
  10578. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10579. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10580. var engine = Engine.Instances[engineIndex];
  10581. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10582. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10583. }
  10584. }
  10585. };
  10586. Object.defineProperty(Engine, "NEVER", {
  10587. get: function () {
  10588. return Engine._NEVER;
  10589. },
  10590. enumerable: true,
  10591. configurable: true
  10592. });
  10593. Object.defineProperty(Engine, "ALWAYS", {
  10594. get: function () {
  10595. return Engine._ALWAYS;
  10596. },
  10597. enumerable: true,
  10598. configurable: true
  10599. });
  10600. Object.defineProperty(Engine, "LESS", {
  10601. get: function () {
  10602. return Engine._LESS;
  10603. },
  10604. enumerable: true,
  10605. configurable: true
  10606. });
  10607. Object.defineProperty(Engine, "EQUAL", {
  10608. get: function () {
  10609. return Engine._EQUAL;
  10610. },
  10611. enumerable: true,
  10612. configurable: true
  10613. });
  10614. Object.defineProperty(Engine, "LEQUAL", {
  10615. get: function () {
  10616. return Engine._LEQUAL;
  10617. },
  10618. enumerable: true,
  10619. configurable: true
  10620. });
  10621. Object.defineProperty(Engine, "GREATER", {
  10622. get: function () {
  10623. return Engine._GREATER;
  10624. },
  10625. enumerable: true,
  10626. configurable: true
  10627. });
  10628. Object.defineProperty(Engine, "GEQUAL", {
  10629. get: function () {
  10630. return Engine._GEQUAL;
  10631. },
  10632. enumerable: true,
  10633. configurable: true
  10634. });
  10635. Object.defineProperty(Engine, "NOTEQUAL", {
  10636. get: function () {
  10637. return Engine._NOTEQUAL;
  10638. },
  10639. enumerable: true,
  10640. configurable: true
  10641. });
  10642. Object.defineProperty(Engine, "KEEP", {
  10643. get: function () {
  10644. return Engine._KEEP;
  10645. },
  10646. enumerable: true,
  10647. configurable: true
  10648. });
  10649. Object.defineProperty(Engine, "REPLACE", {
  10650. get: function () {
  10651. return Engine._REPLACE;
  10652. },
  10653. enumerable: true,
  10654. configurable: true
  10655. });
  10656. Object.defineProperty(Engine, "INCR", {
  10657. get: function () {
  10658. return Engine._INCR;
  10659. },
  10660. enumerable: true,
  10661. configurable: true
  10662. });
  10663. Object.defineProperty(Engine, "DECR", {
  10664. get: function () {
  10665. return Engine._DECR;
  10666. },
  10667. enumerable: true,
  10668. configurable: true
  10669. });
  10670. Object.defineProperty(Engine, "INVERT", {
  10671. get: function () {
  10672. return Engine._INVERT;
  10673. },
  10674. enumerable: true,
  10675. configurable: true
  10676. });
  10677. Object.defineProperty(Engine, "INCR_WRAP", {
  10678. get: function () {
  10679. return Engine._INCR_WRAP;
  10680. },
  10681. enumerable: true,
  10682. configurable: true
  10683. });
  10684. Object.defineProperty(Engine, "DECR_WRAP", {
  10685. get: function () {
  10686. return Engine._DECR_WRAP;
  10687. },
  10688. enumerable: true,
  10689. configurable: true
  10690. });
  10691. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10692. get: function () {
  10693. return Engine._ALPHA_DISABLE;
  10694. },
  10695. enumerable: true,
  10696. configurable: true
  10697. });
  10698. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10699. get: function () {
  10700. return Engine._ALPHA_ONEONE;
  10701. },
  10702. enumerable: true,
  10703. configurable: true
  10704. });
  10705. Object.defineProperty(Engine, "ALPHA_ADD", {
  10706. get: function () {
  10707. return Engine._ALPHA_ADD;
  10708. },
  10709. enumerable: true,
  10710. configurable: true
  10711. });
  10712. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10713. get: function () {
  10714. return Engine._ALPHA_COMBINE;
  10715. },
  10716. enumerable: true,
  10717. configurable: true
  10718. });
  10719. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10720. get: function () {
  10721. return Engine._ALPHA_SUBTRACT;
  10722. },
  10723. enumerable: true,
  10724. configurable: true
  10725. });
  10726. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10727. get: function () {
  10728. return Engine._ALPHA_MULTIPLY;
  10729. },
  10730. enumerable: true,
  10731. configurable: true
  10732. });
  10733. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10734. get: function () {
  10735. return Engine._ALPHA_MAXIMIZED;
  10736. },
  10737. enumerable: true,
  10738. configurable: true
  10739. });
  10740. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10741. get: function () {
  10742. return Engine._ALPHA_PREMULTIPLIED;
  10743. },
  10744. enumerable: true,
  10745. configurable: true
  10746. });
  10747. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10748. get: function () {
  10749. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10750. },
  10751. enumerable: true,
  10752. configurable: true
  10753. });
  10754. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10755. get: function () {
  10756. return Engine._ALPHA_INTERPOLATE;
  10757. },
  10758. enumerable: true,
  10759. configurable: true
  10760. });
  10761. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10762. get: function () {
  10763. return Engine._ALPHA_SCREENMODE;
  10764. },
  10765. enumerable: true,
  10766. configurable: true
  10767. });
  10768. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10769. get: function () {
  10770. return Engine._DELAYLOADSTATE_NONE;
  10771. },
  10772. enumerable: true,
  10773. configurable: true
  10774. });
  10775. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10776. get: function () {
  10777. return Engine._DELAYLOADSTATE_LOADED;
  10778. },
  10779. enumerable: true,
  10780. configurable: true
  10781. });
  10782. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10783. get: function () {
  10784. return Engine._DELAYLOADSTATE_LOADING;
  10785. },
  10786. enumerable: true,
  10787. configurable: true
  10788. });
  10789. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10790. get: function () {
  10791. return Engine._DELAYLOADSTATE_NOTLOADED;
  10792. },
  10793. enumerable: true,
  10794. configurable: true
  10795. });
  10796. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10797. get: function () {
  10798. return Engine._TEXTUREFORMAT_ALPHA;
  10799. },
  10800. enumerable: true,
  10801. configurable: true
  10802. });
  10803. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10804. get: function () {
  10805. return Engine._TEXTUREFORMAT_LUMINANCE;
  10806. },
  10807. enumerable: true,
  10808. configurable: true
  10809. });
  10810. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10811. get: function () {
  10812. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10813. },
  10814. enumerable: true,
  10815. configurable: true
  10816. });
  10817. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10818. get: function () {
  10819. return Engine._TEXTUREFORMAT_RGB;
  10820. },
  10821. enumerable: true,
  10822. configurable: true
  10823. });
  10824. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10825. get: function () {
  10826. return Engine._TEXTUREFORMAT_RGBA;
  10827. },
  10828. enumerable: true,
  10829. configurable: true
  10830. });
  10831. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10832. get: function () {
  10833. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10834. },
  10835. enumerable: true,
  10836. configurable: true
  10837. });
  10838. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10839. get: function () {
  10840. return Engine._TEXTURETYPE_FLOAT;
  10841. },
  10842. enumerable: true,
  10843. configurable: true
  10844. });
  10845. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10846. get: function () {
  10847. return Engine._TEXTURETYPE_HALF_FLOAT;
  10848. },
  10849. enumerable: true,
  10850. configurable: true
  10851. });
  10852. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10853. get: function () {
  10854. return Engine._SCALEMODE_FLOOR;
  10855. },
  10856. enumerable: true,
  10857. configurable: true
  10858. });
  10859. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10860. get: function () {
  10861. return Engine._SCALEMODE_NEAREST;
  10862. },
  10863. enumerable: true,
  10864. configurable: true
  10865. });
  10866. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10867. get: function () {
  10868. return Engine._SCALEMODE_CEILING;
  10869. },
  10870. enumerable: true,
  10871. configurable: true
  10872. });
  10873. Object.defineProperty(Engine, "Version", {
  10874. get: function () {
  10875. return "3.2.0-alpha7";
  10876. },
  10877. enumerable: true,
  10878. configurable: true
  10879. });
  10880. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10881. get: function () {
  10882. return this._vrExclusivePointerMode;
  10883. },
  10884. enumerable: true,
  10885. configurable: true
  10886. });
  10887. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10888. get: function () {
  10889. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10890. },
  10891. enumerable: true,
  10892. configurable: true
  10893. });
  10894. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10895. get: function () {
  10896. return this._webGLVersion < 2 || this.forcePOTTextures;
  10897. },
  10898. enumerable: true,
  10899. configurable: true
  10900. });
  10901. Object.defineProperty(Engine.prototype, "badOS", {
  10902. get: function () {
  10903. return this._badOS;
  10904. },
  10905. enumerable: true,
  10906. configurable: true
  10907. });
  10908. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10909. get: function () {
  10910. return this._badDesktopOS;
  10911. },
  10912. enumerable: true,
  10913. configurable: true
  10914. });
  10915. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10916. get: function () {
  10917. return this._performanceMonitor;
  10918. },
  10919. enumerable: true,
  10920. configurable: true
  10921. });
  10922. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10923. get: function () {
  10924. return this._texturesSupported;
  10925. },
  10926. enumerable: true,
  10927. configurable: true
  10928. });
  10929. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10930. get: function () {
  10931. return this._textureFormatInUse;
  10932. },
  10933. enumerable: true,
  10934. configurable: true
  10935. });
  10936. Object.defineProperty(Engine.prototype, "currentViewport", {
  10937. get: function () {
  10938. return this._cachedViewport;
  10939. },
  10940. enumerable: true,
  10941. configurable: true
  10942. });
  10943. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10944. // Empty texture
  10945. get: function () {
  10946. if (!this._emptyTexture) {
  10947. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10948. }
  10949. return this._emptyTexture;
  10950. },
  10951. enumerable: true,
  10952. configurable: true
  10953. });
  10954. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10955. get: function () {
  10956. if (!this._emptyTexture3D) {
  10957. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10958. }
  10959. return this._emptyTexture3D;
  10960. },
  10961. enumerable: true,
  10962. configurable: true
  10963. });
  10964. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10965. get: function () {
  10966. if (!this._emptyCubeTexture) {
  10967. var faceData = new Uint8Array(4);
  10968. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10969. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10970. }
  10971. return this._emptyCubeTexture;
  10972. },
  10973. enumerable: true,
  10974. configurable: true
  10975. });
  10976. Engine.prototype._rebuildInternalTextures = function () {
  10977. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10978. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10979. var internalTexture = currentState_1[_i];
  10980. internalTexture._rebuild();
  10981. }
  10982. };
  10983. Engine.prototype._rebuildEffects = function () {
  10984. for (var key in this._compiledEffects) {
  10985. var effect = this._compiledEffects[key];
  10986. effect._prepareEffect();
  10987. }
  10988. BABYLON.Effect.ResetCache();
  10989. };
  10990. Engine.prototype._rebuildBuffers = function () {
  10991. // Index / Vertex
  10992. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10993. var scene = _a[_i];
  10994. scene.resetCachedMaterial();
  10995. scene._rebuildGeometries();
  10996. scene._rebuildTextures();
  10997. }
  10998. // Uniforms
  10999. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11000. var uniformBuffer = _c[_b];
  11001. uniformBuffer._rebuild();
  11002. }
  11003. };
  11004. Engine.prototype._initGLContext = function () {
  11005. // Caps
  11006. this._caps = new EngineCapabilities();
  11007. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11008. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11009. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11010. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11011. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11012. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11013. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11014. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11015. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11016. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11017. // Infos
  11018. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11019. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11020. if (rendererInfo != null) {
  11021. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11022. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11023. }
  11024. if (!this._glVendor) {
  11025. this._glVendor = "Unknown vendor";
  11026. }
  11027. if (!this._glRenderer) {
  11028. this._glRenderer = "Unknown renderer";
  11029. }
  11030. // Constants
  11031. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11032. if (this._gl.RGBA16F !== 0x881A) {
  11033. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11034. }
  11035. if (this._gl.RGBA32F !== 0x8814) {
  11036. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11037. }
  11038. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11039. this._gl.DEPTH24_STENCIL8 = 35056;
  11040. }
  11041. // Extensions
  11042. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11043. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11044. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11045. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11046. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11047. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11048. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11049. 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');
  11050. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11051. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11052. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11053. this._caps.highPrecisionShaderSupported = true;
  11054. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11055. if (this._caps.timerQuery) {
  11056. if (this._webGLVersion === 1) {
  11057. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11058. }
  11059. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11060. }
  11061. // Checks if some of the format renders first to allow the use of webgl inspector.
  11062. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11063. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11064. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11065. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11066. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11067. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11068. if (this._webGLVersion > 1) {
  11069. this._gl.HALF_FLOAT_OES = 0x140B;
  11070. }
  11071. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11072. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11073. // Draw buffers
  11074. if (this._webGLVersion > 1) {
  11075. this._caps.drawBuffersExtension = true;
  11076. }
  11077. else {
  11078. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11079. if (drawBuffersExtension !== null) {
  11080. this._caps.drawBuffersExtension = true;
  11081. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11082. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11083. for (var i = 0; i < 16; i++) {
  11084. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11085. }
  11086. }
  11087. else {
  11088. this._caps.drawBuffersExtension = false;
  11089. }
  11090. }
  11091. // Depth Texture
  11092. if (this._webGLVersion > 1) {
  11093. this._caps.depthTextureExtension = true;
  11094. }
  11095. else {
  11096. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11097. if (depthTextureExtension != null) {
  11098. this._caps.depthTextureExtension = true;
  11099. }
  11100. }
  11101. // Vertex array object
  11102. if (this._webGLVersion > 1) {
  11103. this._caps.vertexArrayObject = true;
  11104. }
  11105. else {
  11106. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11107. if (vertexArrayObjectExtension != null) {
  11108. this._caps.vertexArrayObject = true;
  11109. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11110. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11111. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11112. }
  11113. else {
  11114. this._caps.vertexArrayObject = false;
  11115. }
  11116. }
  11117. // Instances count
  11118. if (this._webGLVersion > 1) {
  11119. this._caps.instancedArrays = true;
  11120. }
  11121. else {
  11122. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11123. if (instanceExtension != null) {
  11124. this._caps.instancedArrays = true;
  11125. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11126. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11127. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11128. }
  11129. else {
  11130. this._caps.instancedArrays = false;
  11131. }
  11132. }
  11133. // Intelligently add supported compressed formats in order to check for.
  11134. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11135. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11136. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11137. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11138. if (this._caps.astc)
  11139. this.texturesSupported.push('-astc.ktx');
  11140. if (this._caps.s3tc)
  11141. this.texturesSupported.push('-dxt.ktx');
  11142. if (this._caps.pvrtc)
  11143. this.texturesSupported.push('-pvrtc.ktx');
  11144. if (this._caps.etc2)
  11145. this.texturesSupported.push('-etc2.ktx');
  11146. if (this._caps.etc1)
  11147. this.texturesSupported.push('-etc1.ktx');
  11148. if (this._gl.getShaderPrecisionFormat) {
  11149. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11150. if (highp) {
  11151. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11152. }
  11153. }
  11154. // Depth buffer
  11155. this.setDepthBuffer(true);
  11156. this.setDepthFunctionToLessOrEqual();
  11157. this.setDepthWrite(true);
  11158. // Texture maps
  11159. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11160. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11161. this._nextFreeTextureSlots.push(slot);
  11162. }
  11163. };
  11164. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11165. get: function () {
  11166. return this._webGLVersion;
  11167. },
  11168. enumerable: true,
  11169. configurable: true
  11170. });
  11171. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11172. /**
  11173. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11174. */
  11175. get: function () {
  11176. return this._isStencilEnable;
  11177. },
  11178. enumerable: true,
  11179. configurable: true
  11180. });
  11181. Engine.prototype._prepareWorkingCanvas = function () {
  11182. if (this._workingCanvas) {
  11183. return;
  11184. }
  11185. this._workingCanvas = document.createElement("canvas");
  11186. var context = this._workingCanvas.getContext("2d");
  11187. if (context) {
  11188. this._workingContext = context;
  11189. }
  11190. };
  11191. Engine.prototype.resetTextureCache = function () {
  11192. for (var key in this._boundTexturesCache) {
  11193. var boundTexture = this._boundTexturesCache[key];
  11194. if (boundTexture) {
  11195. this._removeDesignatedSlot(boundTexture);
  11196. }
  11197. this._boundTexturesCache[key] = null;
  11198. }
  11199. if (!this.disableTextureBindingOptimization) {
  11200. this._nextFreeTextureSlots = [];
  11201. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11202. this._nextFreeTextureSlots.push(slot);
  11203. }
  11204. }
  11205. this._currentTextureChannel = -1;
  11206. };
  11207. Engine.prototype.isDeterministicLockStep = function () {
  11208. return this._deterministicLockstep;
  11209. };
  11210. Engine.prototype.getLockstepMaxSteps = function () {
  11211. return this._lockstepMaxSteps;
  11212. };
  11213. Engine.prototype.getGlInfo = function () {
  11214. return {
  11215. vendor: this._glVendor,
  11216. renderer: this._glRenderer,
  11217. version: this._glVersion
  11218. };
  11219. };
  11220. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11221. if (useScreen === void 0) { useScreen = false; }
  11222. var viewport = camera.viewport;
  11223. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11224. };
  11225. Engine.prototype.getRenderWidth = function (useScreen) {
  11226. if (useScreen === void 0) { useScreen = false; }
  11227. if (!useScreen && this._currentRenderTarget) {
  11228. return this._currentRenderTarget.width;
  11229. }
  11230. return this._gl.drawingBufferWidth;
  11231. };
  11232. Engine.prototype.getRenderHeight = function (useScreen) {
  11233. if (useScreen === void 0) { useScreen = false; }
  11234. if (!useScreen && this._currentRenderTarget) {
  11235. return this._currentRenderTarget.height;
  11236. }
  11237. return this._gl.drawingBufferHeight;
  11238. };
  11239. Engine.prototype.getRenderingCanvas = function () {
  11240. return this._renderingCanvas;
  11241. };
  11242. Engine.prototype.getRenderingCanvasClientRect = function () {
  11243. if (!this._renderingCanvas) {
  11244. return null;
  11245. }
  11246. return this._renderingCanvas.getBoundingClientRect();
  11247. };
  11248. Engine.prototype.setHardwareScalingLevel = function (level) {
  11249. this._hardwareScalingLevel = level;
  11250. this.resize();
  11251. };
  11252. Engine.prototype.getHardwareScalingLevel = function () {
  11253. return this._hardwareScalingLevel;
  11254. };
  11255. Engine.prototype.getLoadedTexturesCache = function () {
  11256. return this._internalTexturesCache;
  11257. };
  11258. Engine.prototype.getCaps = function () {
  11259. return this._caps;
  11260. };
  11261. Object.defineProperty(Engine.prototype, "drawCalls", {
  11262. /** The number of draw calls submitted last frame */
  11263. get: function () {
  11264. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11265. return 0;
  11266. },
  11267. enumerable: true,
  11268. configurable: true
  11269. });
  11270. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11271. get: function () {
  11272. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11273. return null;
  11274. },
  11275. enumerable: true,
  11276. configurable: true
  11277. });
  11278. Engine.prototype.getDepthFunction = function () {
  11279. return this._depthCullingState.depthFunc;
  11280. };
  11281. Engine.prototype.setDepthFunction = function (depthFunc) {
  11282. this._depthCullingState.depthFunc = depthFunc;
  11283. };
  11284. Engine.prototype.setDepthFunctionToGreater = function () {
  11285. this._depthCullingState.depthFunc = this._gl.GREATER;
  11286. };
  11287. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11288. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11289. };
  11290. Engine.prototype.setDepthFunctionToLess = function () {
  11291. this._depthCullingState.depthFunc = this._gl.LESS;
  11292. };
  11293. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11294. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11295. };
  11296. Engine.prototype.getStencilBuffer = function () {
  11297. return this._stencilState.stencilTest;
  11298. };
  11299. Engine.prototype.setStencilBuffer = function (enable) {
  11300. this._stencilState.stencilTest = enable;
  11301. };
  11302. Engine.prototype.getStencilMask = function () {
  11303. return this._stencilState.stencilMask;
  11304. };
  11305. Engine.prototype.setStencilMask = function (mask) {
  11306. this._stencilState.stencilMask = mask;
  11307. };
  11308. Engine.prototype.getStencilFunction = function () {
  11309. return this._stencilState.stencilFunc;
  11310. };
  11311. Engine.prototype.getStencilFunctionReference = function () {
  11312. return this._stencilState.stencilFuncRef;
  11313. };
  11314. Engine.prototype.getStencilFunctionMask = function () {
  11315. return this._stencilState.stencilFuncMask;
  11316. };
  11317. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11318. this._stencilState.stencilFunc = stencilFunc;
  11319. };
  11320. Engine.prototype.setStencilFunctionReference = function (reference) {
  11321. this._stencilState.stencilFuncRef = reference;
  11322. };
  11323. Engine.prototype.setStencilFunctionMask = function (mask) {
  11324. this._stencilState.stencilFuncMask = mask;
  11325. };
  11326. Engine.prototype.getStencilOperationFail = function () {
  11327. return this._stencilState.stencilOpStencilFail;
  11328. };
  11329. Engine.prototype.getStencilOperationDepthFail = function () {
  11330. return this._stencilState.stencilOpDepthFail;
  11331. };
  11332. Engine.prototype.getStencilOperationPass = function () {
  11333. return this._stencilState.stencilOpStencilDepthPass;
  11334. };
  11335. Engine.prototype.setStencilOperationFail = function (operation) {
  11336. this._stencilState.stencilOpStencilFail = operation;
  11337. };
  11338. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11339. this._stencilState.stencilOpDepthFail = operation;
  11340. };
  11341. Engine.prototype.setStencilOperationPass = function (operation) {
  11342. this._stencilState.stencilOpStencilDepthPass = operation;
  11343. };
  11344. Engine.prototype.setDitheringState = function (value) {
  11345. if (value) {
  11346. this._gl.enable(this._gl.DITHER);
  11347. }
  11348. else {
  11349. this._gl.disable(this._gl.DITHER);
  11350. }
  11351. };
  11352. Engine.prototype.setRasterizerState = function (value) {
  11353. if (value) {
  11354. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11355. }
  11356. else {
  11357. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11358. }
  11359. };
  11360. /**
  11361. * stop executing a render loop function and remove it from the execution array
  11362. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11363. */
  11364. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11365. if (!renderFunction) {
  11366. this._activeRenderLoops = [];
  11367. return;
  11368. }
  11369. var index = this._activeRenderLoops.indexOf(renderFunction);
  11370. if (index >= 0) {
  11371. this._activeRenderLoops.splice(index, 1);
  11372. }
  11373. };
  11374. Engine.prototype._renderLoop = function () {
  11375. if (!this._contextWasLost) {
  11376. var shouldRender = true;
  11377. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11378. shouldRender = false;
  11379. }
  11380. if (shouldRender) {
  11381. // Start new frame
  11382. this.beginFrame();
  11383. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11384. var renderFunction = this._activeRenderLoops[index];
  11385. renderFunction();
  11386. }
  11387. // Present
  11388. this.endFrame();
  11389. }
  11390. }
  11391. if (this._activeRenderLoops.length > 0) {
  11392. // Register new frame
  11393. var requester = null;
  11394. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11395. requester = this._vrDisplay;
  11396. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11397. }
  11398. else {
  11399. this._renderingQueueLaunched = false;
  11400. }
  11401. };
  11402. /**
  11403. * Register and execute a render loop. The engine can have more than one render function.
  11404. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11405. * @example
  11406. * engine.runRenderLoop(function () {
  11407. * scene.render()
  11408. * })
  11409. */
  11410. Engine.prototype.runRenderLoop = function (renderFunction) {
  11411. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11412. return;
  11413. }
  11414. this._activeRenderLoops.push(renderFunction);
  11415. if (!this._renderingQueueLaunched) {
  11416. this._renderingQueueLaunched = true;
  11417. this._bindedRenderFunction = this._renderLoop.bind(this);
  11418. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11419. }
  11420. };
  11421. /**
  11422. * Toggle full screen mode.
  11423. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11424. * @param {any} options - an options object to be sent to the requestFullscreen function
  11425. */
  11426. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11427. if (this.isFullscreen) {
  11428. BABYLON.Tools.ExitFullscreen();
  11429. }
  11430. else {
  11431. this._pointerLockRequested = requestPointerLock;
  11432. if (this._renderingCanvas) {
  11433. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11434. }
  11435. }
  11436. };
  11437. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11438. if (stencil === void 0) { stencil = false; }
  11439. this.applyStates();
  11440. var mode = 0;
  11441. if (backBuffer && color) {
  11442. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11443. mode |= this._gl.COLOR_BUFFER_BIT;
  11444. }
  11445. if (depth) {
  11446. this._gl.clearDepth(1.0);
  11447. mode |= this._gl.DEPTH_BUFFER_BIT;
  11448. }
  11449. if (stencil) {
  11450. this._gl.clearStencil(0);
  11451. mode |= this._gl.STENCIL_BUFFER_BIT;
  11452. }
  11453. this._gl.clear(mode);
  11454. };
  11455. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11456. var gl = this._gl;
  11457. // Save state
  11458. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11459. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11460. // Change state
  11461. gl.enable(gl.SCISSOR_TEST);
  11462. gl.scissor(x, y, width, height);
  11463. // Clear
  11464. this.clear(clearColor, true, true, true);
  11465. // Restore state
  11466. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11467. if (curScissor === true) {
  11468. gl.enable(gl.SCISSOR_TEST);
  11469. }
  11470. else {
  11471. gl.disable(gl.SCISSOR_TEST);
  11472. }
  11473. };
  11474. /**
  11475. * Set the WebGL's viewport
  11476. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11477. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11478. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11479. */
  11480. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11481. var width = requiredWidth || this.getRenderWidth();
  11482. var height = requiredHeight || this.getRenderHeight();
  11483. var x = viewport.x || 0;
  11484. var y = viewport.y || 0;
  11485. this._cachedViewport = viewport;
  11486. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11487. };
  11488. /**
  11489. * Directly set the WebGL Viewport
  11490. * The x, y, width & height are directly passed to the WebGL call
  11491. * @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.
  11492. */
  11493. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11494. var currentViewport = this._cachedViewport;
  11495. this._cachedViewport = null;
  11496. this._gl.viewport(x, y, width, height);
  11497. return currentViewport;
  11498. };
  11499. Engine.prototype.beginFrame = function () {
  11500. this.onBeginFrameObservable.notifyObservers(this);
  11501. this._measureFps();
  11502. };
  11503. Engine.prototype.endFrame = function () {
  11504. //force a flush in case we are using a bad OS.
  11505. if (this._badOS) {
  11506. this.flushFramebuffer();
  11507. }
  11508. //submit frame to the vr device, if enabled
  11509. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11510. // TODO: We should only submit the frame if we read frameData successfully.
  11511. this._vrDisplay.submitFrame();
  11512. }
  11513. this.onEndFrameObservable.notifyObservers(this);
  11514. };
  11515. /**
  11516. * resize the view according to the canvas' size.
  11517. * @example
  11518. * window.addEventListener("resize", function () {
  11519. * engine.resize();
  11520. * });
  11521. */
  11522. Engine.prototype.resize = function () {
  11523. // We're not resizing the size of the canvas while in VR mode & presenting
  11524. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11525. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11526. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11527. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11528. }
  11529. };
  11530. /**
  11531. * force a specific size of the canvas
  11532. * @param {number} width - the new canvas' width
  11533. * @param {number} height - the new canvas' height
  11534. */
  11535. Engine.prototype.setSize = function (width, height) {
  11536. if (!this._renderingCanvas) {
  11537. return;
  11538. }
  11539. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11540. return;
  11541. }
  11542. this._renderingCanvas.width = width;
  11543. this._renderingCanvas.height = height;
  11544. for (var index = 0; index < this.scenes.length; index++) {
  11545. var scene = this.scenes[index];
  11546. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11547. var cam = scene.cameras[camIndex];
  11548. cam._currentRenderId = 0;
  11549. }
  11550. }
  11551. if (this.onResizeObservable.hasObservers) {
  11552. this.onResizeObservable.notifyObservers(this);
  11553. }
  11554. };
  11555. // WebVR functions
  11556. Engine.prototype.isVRDevicePresent = function () {
  11557. return !!this._vrDisplay;
  11558. };
  11559. Engine.prototype.getVRDevice = function () {
  11560. return this._vrDisplay;
  11561. };
  11562. Engine.prototype.initWebVR = function () {
  11563. var _this = this;
  11564. var notifyObservers = function () {
  11565. var eventArgs = {
  11566. vrDisplay: _this._vrDisplay,
  11567. vrSupported: _this._vrSupported
  11568. };
  11569. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11570. };
  11571. if (!this._onVrDisplayConnect) {
  11572. this._onVrDisplayConnect = function (event) {
  11573. _this._vrDisplay = event.display;
  11574. notifyObservers();
  11575. };
  11576. this._onVrDisplayDisconnect = function () {
  11577. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11578. _this._vrDisplay = undefined;
  11579. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11580. notifyObservers();
  11581. };
  11582. this._onVrDisplayPresentChange = function () {
  11583. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11584. };
  11585. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11586. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11587. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11588. }
  11589. this._getVRDisplays(notifyObservers);
  11590. return this.onVRDisplayChangedObservable;
  11591. };
  11592. Engine.prototype.enableVR = function () {
  11593. var _this = this;
  11594. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11595. var onResolved = function () {
  11596. _this.onVRRequestPresentComplete.notifyObservers(true);
  11597. _this._onVRFullScreenTriggered();
  11598. };
  11599. var onRejected = function () {
  11600. _this.onVRRequestPresentComplete.notifyObservers(false);
  11601. };
  11602. this.onVRRequestPresentStart.notifyObservers(this);
  11603. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11604. }
  11605. };
  11606. Engine.prototype.disableVR = function () {
  11607. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11608. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11609. }
  11610. };
  11611. Engine.prototype._getVRDisplays = function (callback) {
  11612. var _this = this;
  11613. var getWebVRDevices = function (devices) {
  11614. _this._vrSupported = true;
  11615. // note that devices may actually be an empty array. This is fine;
  11616. // we expect this._vrDisplay to be undefined in this case.
  11617. return _this._vrDisplay = devices[0];
  11618. };
  11619. if (navigator.getVRDisplays) {
  11620. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  11621. // TODO: System CANNOT support WebVR, despite API presence.
  11622. _this._vrSupported = false;
  11623. callback();
  11624. });
  11625. }
  11626. else {
  11627. // TODO: Browser does not support WebVR
  11628. this._vrDisplay = undefined;
  11629. this._vrSupported = false;
  11630. callback();
  11631. }
  11632. };
  11633. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  11634. if (this._currentRenderTarget) {
  11635. this.unBindFramebuffer(this._currentRenderTarget);
  11636. }
  11637. this._currentRenderTarget = texture;
  11638. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11639. var gl = this._gl;
  11640. if (texture.isCube) {
  11641. if (faceIndex === undefined) {
  11642. faceIndex = 0;
  11643. }
  11644. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11645. }
  11646. if (this._cachedViewport && !forceFullscreenViewport) {
  11647. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11648. }
  11649. else {
  11650. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11651. }
  11652. this.wipeCaches();
  11653. };
  11654. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11655. if (this._currentFramebuffer !== framebuffer) {
  11656. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11657. this._currentFramebuffer = framebuffer;
  11658. }
  11659. };
  11660. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11661. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11662. this._currentRenderTarget = null;
  11663. // If MSAA, we need to bitblt back to main texture
  11664. var gl = this._gl;
  11665. if (texture._MSAAFramebuffer) {
  11666. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11667. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11668. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11669. }
  11670. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11671. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11672. gl.generateMipmap(gl.TEXTURE_2D);
  11673. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11674. }
  11675. if (onBeforeUnbind) {
  11676. if (texture._MSAAFramebuffer) {
  11677. // Bind the correct framebuffer
  11678. this.bindUnboundFramebuffer(texture._framebuffer);
  11679. }
  11680. onBeforeUnbind();
  11681. }
  11682. this.bindUnboundFramebuffer(null);
  11683. };
  11684. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11685. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11686. this._currentRenderTarget = null;
  11687. // If MSAA, we need to bitblt back to main texture
  11688. var gl = this._gl;
  11689. if (textures[0]._MSAAFramebuffer) {
  11690. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11691. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11692. var attachments = textures[0]._attachments;
  11693. if (!attachments) {
  11694. attachments = new Array(textures.length);
  11695. textures[0]._attachments = attachments;
  11696. }
  11697. for (var i = 0; i < textures.length; i++) {
  11698. var texture = textures[i];
  11699. for (var j = 0; j < attachments.length; j++) {
  11700. attachments[j] = gl.NONE;
  11701. }
  11702. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11703. gl.readBuffer(attachments[i]);
  11704. gl.drawBuffers(attachments);
  11705. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11706. }
  11707. for (var i = 0; i < attachments.length; i++) {
  11708. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11709. }
  11710. gl.drawBuffers(attachments);
  11711. }
  11712. for (var i = 0; i < textures.length; i++) {
  11713. var texture = textures[i];
  11714. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11715. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11716. gl.generateMipmap(gl.TEXTURE_2D);
  11717. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11718. }
  11719. }
  11720. if (onBeforeUnbind) {
  11721. if (textures[0]._MSAAFramebuffer) {
  11722. // Bind the correct framebuffer
  11723. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11724. }
  11725. onBeforeUnbind();
  11726. }
  11727. this.bindUnboundFramebuffer(null);
  11728. };
  11729. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11730. if (texture.generateMipMaps) {
  11731. var gl = this._gl;
  11732. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11733. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11734. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11735. }
  11736. };
  11737. Engine.prototype.flushFramebuffer = function () {
  11738. this._gl.flush();
  11739. };
  11740. Engine.prototype.restoreDefaultFramebuffer = function () {
  11741. if (this._currentRenderTarget) {
  11742. this.unBindFramebuffer(this._currentRenderTarget);
  11743. }
  11744. else {
  11745. this.bindUnboundFramebuffer(null);
  11746. }
  11747. if (this._cachedViewport) {
  11748. this.setViewport(this._cachedViewport);
  11749. }
  11750. this.wipeCaches();
  11751. };
  11752. // UBOs
  11753. Engine.prototype.createUniformBuffer = function (elements) {
  11754. var ubo = this._gl.createBuffer();
  11755. if (!ubo) {
  11756. throw new Error("Unable to create uniform buffer");
  11757. }
  11758. this.bindUniformBuffer(ubo);
  11759. if (elements instanceof Float32Array) {
  11760. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11761. }
  11762. else {
  11763. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11764. }
  11765. this.bindUniformBuffer(null);
  11766. ubo.references = 1;
  11767. return ubo;
  11768. };
  11769. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11770. var ubo = this._gl.createBuffer();
  11771. if (!ubo) {
  11772. throw new Error("Unable to create dynamic uniform buffer");
  11773. }
  11774. this.bindUniformBuffer(ubo);
  11775. if (elements instanceof Float32Array) {
  11776. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11777. }
  11778. else {
  11779. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11780. }
  11781. this.bindUniformBuffer(null);
  11782. ubo.references = 1;
  11783. return ubo;
  11784. };
  11785. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11786. this.bindUniformBuffer(uniformBuffer);
  11787. if (offset === undefined) {
  11788. offset = 0;
  11789. }
  11790. if (count === undefined) {
  11791. if (elements instanceof Float32Array) {
  11792. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11793. }
  11794. else {
  11795. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11796. }
  11797. }
  11798. else {
  11799. if (elements instanceof Float32Array) {
  11800. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11801. }
  11802. else {
  11803. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11804. }
  11805. }
  11806. this.bindUniformBuffer(null);
  11807. };
  11808. // VBOs
  11809. Engine.prototype._resetVertexBufferBinding = function () {
  11810. this.bindArrayBuffer(null);
  11811. this._cachedVertexBuffers = null;
  11812. };
  11813. Engine.prototype.createVertexBuffer = function (vertices) {
  11814. var vbo = this._gl.createBuffer();
  11815. if (!vbo) {
  11816. throw new Error("Unable to create vertex buffer");
  11817. }
  11818. this.bindArrayBuffer(vbo);
  11819. if (vertices instanceof Float32Array) {
  11820. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11821. }
  11822. else {
  11823. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11824. }
  11825. this._resetVertexBufferBinding();
  11826. vbo.references = 1;
  11827. return vbo;
  11828. };
  11829. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11830. var vbo = this._gl.createBuffer();
  11831. if (!vbo) {
  11832. throw new Error("Unable to create dynamic vertex buffer");
  11833. }
  11834. this.bindArrayBuffer(vbo);
  11835. if (vertices instanceof Float32Array) {
  11836. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11837. }
  11838. else {
  11839. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11840. }
  11841. this._resetVertexBufferBinding();
  11842. vbo.references = 1;
  11843. return vbo;
  11844. };
  11845. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11846. if (offset === void 0) { offset = 0; }
  11847. // Force cache update
  11848. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11849. this.bindIndexBuffer(indexBuffer);
  11850. var arrayBuffer;
  11851. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11852. arrayBuffer = indices;
  11853. }
  11854. else {
  11855. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11856. }
  11857. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11858. this._resetIndexBufferBinding();
  11859. };
  11860. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11861. this.bindArrayBuffer(vertexBuffer);
  11862. if (offset === undefined) {
  11863. offset = 0;
  11864. }
  11865. if (count === undefined) {
  11866. if (vertices instanceof Float32Array) {
  11867. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11868. }
  11869. else {
  11870. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11871. }
  11872. }
  11873. else {
  11874. if (vertices instanceof Float32Array) {
  11875. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11876. }
  11877. else {
  11878. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11879. }
  11880. }
  11881. this._resetVertexBufferBinding();
  11882. };
  11883. Engine.prototype._resetIndexBufferBinding = function () {
  11884. this.bindIndexBuffer(null);
  11885. this._cachedIndexBuffer = null;
  11886. };
  11887. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11888. var vbo = this._gl.createBuffer();
  11889. if (!vbo) {
  11890. throw new Error("Unable to create index buffer");
  11891. }
  11892. this.bindIndexBuffer(vbo);
  11893. // Check for 32 bits indices
  11894. var arrayBuffer;
  11895. var need32Bits = false;
  11896. if (indices instanceof Uint16Array) {
  11897. arrayBuffer = indices;
  11898. }
  11899. else {
  11900. //check 32 bit support
  11901. if (this._caps.uintIndices) {
  11902. if (indices instanceof Uint32Array) {
  11903. arrayBuffer = indices;
  11904. need32Bits = true;
  11905. }
  11906. else {
  11907. //number[] or Int32Array, check if 32 bit is necessary
  11908. for (var index = 0; index < indices.length; index++) {
  11909. if (indices[index] > 65535) {
  11910. need32Bits = true;
  11911. break;
  11912. }
  11913. }
  11914. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11915. }
  11916. }
  11917. else {
  11918. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11919. arrayBuffer = new Uint16Array(indices);
  11920. }
  11921. }
  11922. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11923. this._resetIndexBufferBinding();
  11924. vbo.references = 1;
  11925. vbo.is32Bits = need32Bits;
  11926. return vbo;
  11927. };
  11928. Engine.prototype.bindArrayBuffer = function (buffer) {
  11929. if (!this._vaoRecordInProgress) {
  11930. this._unbindVertexArrayObject();
  11931. }
  11932. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11933. };
  11934. Engine.prototype.bindUniformBuffer = function (buffer) {
  11935. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11936. };
  11937. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11938. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11939. };
  11940. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11941. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11942. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11943. };
  11944. ;
  11945. Engine.prototype.bindIndexBuffer = function (buffer) {
  11946. if (!this._vaoRecordInProgress) {
  11947. this._unbindVertexArrayObject();
  11948. }
  11949. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11950. };
  11951. Engine.prototype.bindBuffer = function (buffer, target) {
  11952. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11953. this._gl.bindBuffer(target, buffer);
  11954. this._currentBoundBuffer[target] = buffer;
  11955. }
  11956. };
  11957. Engine.prototype.updateArrayBuffer = function (data) {
  11958. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11959. };
  11960. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11961. var pointer = this._currentBufferPointers[indx];
  11962. var changed = false;
  11963. if (!pointer.active) {
  11964. changed = true;
  11965. pointer.active = true;
  11966. pointer.index = indx;
  11967. pointer.size = size;
  11968. pointer.type = type;
  11969. pointer.normalized = normalized;
  11970. pointer.stride = stride;
  11971. pointer.offset = offset;
  11972. pointer.buffer = buffer;
  11973. }
  11974. else {
  11975. if (pointer.buffer !== buffer) {
  11976. pointer.buffer = buffer;
  11977. changed = true;
  11978. }
  11979. if (pointer.size !== size) {
  11980. pointer.size = size;
  11981. changed = true;
  11982. }
  11983. if (pointer.type !== type) {
  11984. pointer.type = type;
  11985. changed = true;
  11986. }
  11987. if (pointer.normalized !== normalized) {
  11988. pointer.normalized = normalized;
  11989. changed = true;
  11990. }
  11991. if (pointer.stride !== stride) {
  11992. pointer.stride = stride;
  11993. changed = true;
  11994. }
  11995. if (pointer.offset !== offset) {
  11996. pointer.offset = offset;
  11997. changed = true;
  11998. }
  11999. }
  12000. if (changed || this._vaoRecordInProgress) {
  12001. this.bindArrayBuffer(buffer);
  12002. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12003. }
  12004. };
  12005. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12006. if (indexBuffer == null) {
  12007. return;
  12008. }
  12009. if (this._cachedIndexBuffer !== indexBuffer) {
  12010. this._cachedIndexBuffer = indexBuffer;
  12011. this.bindIndexBuffer(indexBuffer);
  12012. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12013. }
  12014. };
  12015. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12016. var attributes = effect.getAttributesNames();
  12017. if (!this._vaoRecordInProgress) {
  12018. this._unbindVertexArrayObject();
  12019. }
  12020. this.unbindAllAttributes();
  12021. for (var index = 0; index < attributes.length; index++) {
  12022. var order = effect.getAttributeLocation(index);
  12023. if (order >= 0) {
  12024. var vertexBuffer = vertexBuffers[attributes[index]];
  12025. if (!vertexBuffer) {
  12026. continue;
  12027. }
  12028. this._gl.enableVertexAttribArray(order);
  12029. if (!this._vaoRecordInProgress) {
  12030. this._vertexAttribArraysEnabled[order] = true;
  12031. }
  12032. var buffer = vertexBuffer.getBuffer();
  12033. if (buffer) {
  12034. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12035. if (vertexBuffer.getIsInstanced()) {
  12036. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12037. if (!this._vaoRecordInProgress) {
  12038. this._currentInstanceLocations.push(order);
  12039. this._currentInstanceBuffers.push(buffer);
  12040. }
  12041. }
  12042. }
  12043. }
  12044. }
  12045. };
  12046. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12047. var vao = this._gl.createVertexArray();
  12048. this._vaoRecordInProgress = true;
  12049. this._gl.bindVertexArray(vao);
  12050. this._mustWipeVertexAttributes = true;
  12051. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12052. this.bindIndexBuffer(indexBuffer);
  12053. this._vaoRecordInProgress = false;
  12054. this._gl.bindVertexArray(null);
  12055. return vao;
  12056. };
  12057. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12058. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12059. this._cachedVertexArrayObject = vertexArrayObject;
  12060. this._gl.bindVertexArray(vertexArrayObject);
  12061. this._cachedVertexBuffers = null;
  12062. this._cachedIndexBuffer = null;
  12063. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12064. this._mustWipeVertexAttributes = true;
  12065. }
  12066. };
  12067. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12068. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12069. this._cachedVertexBuffers = vertexBuffer;
  12070. this._cachedEffectForVertexBuffers = effect;
  12071. var attributesCount = effect.getAttributesCount();
  12072. this._unbindVertexArrayObject();
  12073. this.unbindAllAttributes();
  12074. var offset = 0;
  12075. for (var index = 0; index < attributesCount; index++) {
  12076. if (index < vertexDeclaration.length) {
  12077. var order = effect.getAttributeLocation(index);
  12078. if (order >= 0) {
  12079. this._gl.enableVertexAttribArray(order);
  12080. this._vertexAttribArraysEnabled[order] = true;
  12081. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12082. }
  12083. offset += vertexDeclaration[index] * 4;
  12084. }
  12085. }
  12086. }
  12087. this._bindIndexBufferWithCache(indexBuffer);
  12088. };
  12089. Engine.prototype._unbindVertexArrayObject = function () {
  12090. if (!this._cachedVertexArrayObject) {
  12091. return;
  12092. }
  12093. this._cachedVertexArrayObject = null;
  12094. this._gl.bindVertexArray(null);
  12095. };
  12096. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12097. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12098. this._cachedVertexBuffers = vertexBuffers;
  12099. this._cachedEffectForVertexBuffers = effect;
  12100. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12101. }
  12102. this._bindIndexBufferWithCache(indexBuffer);
  12103. };
  12104. Engine.prototype.unbindInstanceAttributes = function () {
  12105. var boundBuffer;
  12106. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12107. var instancesBuffer = this._currentInstanceBuffers[i];
  12108. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12109. boundBuffer = instancesBuffer;
  12110. this.bindArrayBuffer(instancesBuffer);
  12111. }
  12112. var offsetLocation = this._currentInstanceLocations[i];
  12113. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12114. }
  12115. this._currentInstanceBuffers.length = 0;
  12116. this._currentInstanceLocations.length = 0;
  12117. };
  12118. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12119. this._gl.deleteVertexArray(vao);
  12120. };
  12121. Engine.prototype._releaseBuffer = function (buffer) {
  12122. buffer.references--;
  12123. if (buffer.references === 0) {
  12124. this._gl.deleteBuffer(buffer);
  12125. return true;
  12126. }
  12127. return false;
  12128. };
  12129. Engine.prototype.createInstancesBuffer = function (capacity) {
  12130. var buffer = this._gl.createBuffer();
  12131. if (!buffer) {
  12132. throw new Error("Unable to create instance buffer");
  12133. }
  12134. buffer.capacity = capacity;
  12135. this.bindArrayBuffer(buffer);
  12136. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12137. return buffer;
  12138. };
  12139. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12140. this._gl.deleteBuffer(buffer);
  12141. };
  12142. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12143. this.bindArrayBuffer(instancesBuffer);
  12144. if (data) {
  12145. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12146. }
  12147. if (offsetLocations[0].index !== undefined) {
  12148. var stride = 0;
  12149. for (var i = 0; i < offsetLocations.length; i++) {
  12150. var ai = offsetLocations[i];
  12151. stride += ai.attributeSize * 4;
  12152. }
  12153. for (var i = 0; i < offsetLocations.length; i++) {
  12154. var ai = offsetLocations[i];
  12155. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12156. this._gl.enableVertexAttribArray(ai.index);
  12157. this._vertexAttribArraysEnabled[ai.index] = true;
  12158. }
  12159. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12160. this._gl.vertexAttribDivisor(ai.index, 1);
  12161. this._currentInstanceLocations.push(ai.index);
  12162. this._currentInstanceBuffers.push(instancesBuffer);
  12163. }
  12164. }
  12165. else {
  12166. for (var index = 0; index < 4; index++) {
  12167. var offsetLocation = offsetLocations[index];
  12168. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12169. this._gl.enableVertexAttribArray(offsetLocation);
  12170. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12171. }
  12172. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12173. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12174. this._currentInstanceLocations.push(offsetLocation);
  12175. this._currentInstanceBuffers.push(instancesBuffer);
  12176. }
  12177. }
  12178. };
  12179. Engine.prototype.applyStates = function () {
  12180. this._depthCullingState.apply(this._gl);
  12181. this._stencilState.apply(this._gl);
  12182. this._alphaState.apply(this._gl);
  12183. };
  12184. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12185. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12186. };
  12187. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12188. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12189. };
  12190. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12191. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12192. };
  12193. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12194. // Apply states
  12195. this.applyStates();
  12196. this._drawCalls.addCount(1, false);
  12197. // Render
  12198. var drawMode = this.DrawMode(fillMode);
  12199. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12200. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12201. if (instancesCount) {
  12202. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12203. }
  12204. else {
  12205. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12206. }
  12207. };
  12208. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12209. // Apply states
  12210. this.applyStates();
  12211. this._drawCalls.addCount(1, false);
  12212. var drawMode = this.DrawMode(fillMode);
  12213. if (instancesCount) {
  12214. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12215. }
  12216. else {
  12217. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12218. }
  12219. };
  12220. Engine.prototype.DrawMode = function (fillMode) {
  12221. switch (fillMode) {
  12222. // Triangle views
  12223. case BABYLON.Material.TriangleFillMode:
  12224. return this._gl.TRIANGLES;
  12225. case BABYLON.Material.PointFillMode:
  12226. return this._gl.POINTS;
  12227. case BABYLON.Material.WireFrameFillMode:
  12228. return this._gl.LINES;
  12229. // Draw modes
  12230. case BABYLON.Material.PointListDrawMode:
  12231. return this._gl.POINTS;
  12232. case BABYLON.Material.LineListDrawMode:
  12233. return this._gl.LINES;
  12234. case BABYLON.Material.LineLoopDrawMode:
  12235. return this._gl.LINE_LOOP;
  12236. case BABYLON.Material.LineStripDrawMode:
  12237. return this._gl.LINE_STRIP;
  12238. case BABYLON.Material.TriangleStripDrawMode:
  12239. return this._gl.TRIANGLE_STRIP;
  12240. case BABYLON.Material.TriangleFanDrawMode:
  12241. return this._gl.TRIANGLE_FAN;
  12242. default:
  12243. return this._gl.TRIANGLES;
  12244. }
  12245. };
  12246. // Shaders
  12247. Engine.prototype._releaseEffect = function (effect) {
  12248. if (this._compiledEffects[effect._key]) {
  12249. delete this._compiledEffects[effect._key];
  12250. this._deleteProgram(effect.getProgram());
  12251. }
  12252. };
  12253. Engine.prototype._deleteProgram = function (program) {
  12254. if (program) {
  12255. program.__SPECTOR_rebuildProgram = null;
  12256. if (program.transformFeedback) {
  12257. this.deleteTransformFeedback(program.transformFeedback);
  12258. program.transformFeedback = null;
  12259. }
  12260. this._gl.deleteProgram(program);
  12261. }
  12262. };
  12263. /**
  12264. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12265. * @param samplers An array of string used to represent textures
  12266. */
  12267. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12268. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12269. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12270. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12271. if (this._compiledEffects[name]) {
  12272. var compiledEffect = this._compiledEffects[name];
  12273. if (onCompiled && compiledEffect.isReady()) {
  12274. onCompiled(compiledEffect);
  12275. }
  12276. return compiledEffect;
  12277. }
  12278. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12279. effect._key = name;
  12280. this._compiledEffects[name] = effect;
  12281. return effect;
  12282. };
  12283. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12284. if (uniformsNames === void 0) { uniformsNames = []; }
  12285. if (samplers === void 0) { samplers = []; }
  12286. if (defines === void 0) { defines = ""; }
  12287. return this.createEffect({
  12288. vertex: "particles",
  12289. fragmentElement: fragmentName
  12290. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12291. };
  12292. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12293. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12294. context = context || this._gl;
  12295. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12296. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12297. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12298. };
  12299. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12300. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12301. context = context || this._gl;
  12302. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12303. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12304. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12305. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12306. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12307. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12308. return program;
  12309. };
  12310. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12311. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12312. var shaderProgram = context.createProgram();
  12313. if (!shaderProgram) {
  12314. throw new Error("Unable to create program");
  12315. }
  12316. context.attachShader(shaderProgram, vertexShader);
  12317. context.attachShader(shaderProgram, fragmentShader);
  12318. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12319. var transformFeedback = this.createTransformFeedback();
  12320. this.bindTransformFeedback(transformFeedback);
  12321. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12322. shaderProgram.transformFeedback = transformFeedback;
  12323. }
  12324. context.linkProgram(shaderProgram);
  12325. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12326. this.bindTransformFeedback(null);
  12327. }
  12328. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12329. if (!linked) {
  12330. context.validateProgram(shaderProgram);
  12331. var error = context.getProgramInfoLog(shaderProgram);
  12332. if (error) {
  12333. throw new Error(error);
  12334. }
  12335. }
  12336. context.deleteShader(vertexShader);
  12337. context.deleteShader(fragmentShader);
  12338. return shaderProgram;
  12339. };
  12340. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12341. var results = new Array();
  12342. for (var index = 0; index < uniformsNames.length; index++) {
  12343. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12344. }
  12345. return results;
  12346. };
  12347. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12348. var results = [];
  12349. for (var index = 0; index < attributesNames.length; index++) {
  12350. try {
  12351. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12352. }
  12353. catch (e) {
  12354. results.push(-1);
  12355. }
  12356. }
  12357. return results;
  12358. };
  12359. Engine.prototype.enableEffect = function (effect) {
  12360. if (!effect) {
  12361. return;
  12362. }
  12363. // Use program
  12364. this.bindSamplers(effect);
  12365. this._currentEffect = effect;
  12366. if (effect.onBind) {
  12367. effect.onBind(effect);
  12368. }
  12369. effect.onBindObservable.notifyObservers(effect);
  12370. };
  12371. Engine.prototype.setIntArray = function (uniform, array) {
  12372. if (!uniform)
  12373. return;
  12374. this._gl.uniform1iv(uniform, array);
  12375. };
  12376. Engine.prototype.setIntArray2 = function (uniform, array) {
  12377. if (!uniform || array.length % 2 !== 0)
  12378. return;
  12379. this._gl.uniform2iv(uniform, array);
  12380. };
  12381. Engine.prototype.setIntArray3 = function (uniform, array) {
  12382. if (!uniform || array.length % 3 !== 0)
  12383. return;
  12384. this._gl.uniform3iv(uniform, array);
  12385. };
  12386. Engine.prototype.setIntArray4 = function (uniform, array) {
  12387. if (!uniform || array.length % 4 !== 0)
  12388. return;
  12389. this._gl.uniform4iv(uniform, array);
  12390. };
  12391. Engine.prototype.setFloatArray = function (uniform, array) {
  12392. if (!uniform)
  12393. return;
  12394. this._gl.uniform1fv(uniform, array);
  12395. };
  12396. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12397. if (!uniform || array.length % 2 !== 0)
  12398. return;
  12399. this._gl.uniform2fv(uniform, array);
  12400. };
  12401. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12402. if (!uniform || array.length % 3 !== 0)
  12403. return;
  12404. this._gl.uniform3fv(uniform, array);
  12405. };
  12406. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12407. if (!uniform || array.length % 4 !== 0)
  12408. return;
  12409. this._gl.uniform4fv(uniform, array);
  12410. };
  12411. Engine.prototype.setArray = function (uniform, array) {
  12412. if (!uniform)
  12413. return;
  12414. this._gl.uniform1fv(uniform, array);
  12415. };
  12416. Engine.prototype.setArray2 = function (uniform, array) {
  12417. if (!uniform || array.length % 2 !== 0)
  12418. return;
  12419. this._gl.uniform2fv(uniform, array);
  12420. };
  12421. Engine.prototype.setArray3 = function (uniform, array) {
  12422. if (!uniform || array.length % 3 !== 0)
  12423. return;
  12424. this._gl.uniform3fv(uniform, array);
  12425. };
  12426. Engine.prototype.setArray4 = function (uniform, array) {
  12427. if (!uniform || array.length % 4 !== 0)
  12428. return;
  12429. this._gl.uniform4fv(uniform, array);
  12430. };
  12431. Engine.prototype.setMatrices = function (uniform, matrices) {
  12432. if (!uniform)
  12433. return;
  12434. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12435. };
  12436. Engine.prototype.setMatrix = function (uniform, matrix) {
  12437. if (!uniform)
  12438. return;
  12439. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12440. };
  12441. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12442. if (!uniform)
  12443. return;
  12444. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12445. };
  12446. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12447. if (!uniform)
  12448. return;
  12449. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12450. };
  12451. Engine.prototype.setInt = function (uniform, value) {
  12452. if (!uniform)
  12453. return;
  12454. this._gl.uniform1i(uniform, value);
  12455. };
  12456. Engine.prototype.setFloat = function (uniform, value) {
  12457. if (!uniform)
  12458. return;
  12459. this._gl.uniform1f(uniform, value);
  12460. };
  12461. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12462. if (!uniform)
  12463. return;
  12464. this._gl.uniform2f(uniform, x, y);
  12465. };
  12466. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12467. if (!uniform)
  12468. return;
  12469. this._gl.uniform3f(uniform, x, y, z);
  12470. };
  12471. Engine.prototype.setBool = function (uniform, bool) {
  12472. if (!uniform)
  12473. return;
  12474. this._gl.uniform1i(uniform, bool);
  12475. };
  12476. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12477. if (!uniform)
  12478. return;
  12479. this._gl.uniform4f(uniform, x, y, z, w);
  12480. };
  12481. Engine.prototype.setColor3 = function (uniform, color3) {
  12482. if (!uniform)
  12483. return;
  12484. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12485. };
  12486. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12487. if (!uniform)
  12488. return;
  12489. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12490. };
  12491. // States
  12492. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12493. if (zOffset === void 0) { zOffset = 0; }
  12494. if (reverseSide === void 0) { reverseSide = false; }
  12495. // Culling
  12496. if (this._depthCullingState.cull !== culling || force) {
  12497. this._depthCullingState.cull = culling;
  12498. }
  12499. // Cull face
  12500. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12501. if (this._depthCullingState.cullFace !== cullFace || force) {
  12502. this._depthCullingState.cullFace = cullFace;
  12503. }
  12504. // Z offset
  12505. this.setZOffset(zOffset);
  12506. // Front face
  12507. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12508. if (this._depthCullingState.frontFace !== frontFace || force) {
  12509. this._depthCullingState.frontFace = frontFace;
  12510. }
  12511. };
  12512. Engine.prototype.setZOffset = function (value) {
  12513. this._depthCullingState.zOffset = value;
  12514. };
  12515. Engine.prototype.getZOffset = function () {
  12516. return this._depthCullingState.zOffset;
  12517. };
  12518. Engine.prototype.setDepthBuffer = function (enable) {
  12519. this._depthCullingState.depthTest = enable;
  12520. };
  12521. Engine.prototype.getDepthWrite = function () {
  12522. return this._depthCullingState.depthMask;
  12523. };
  12524. Engine.prototype.setDepthWrite = function (enable) {
  12525. this._depthCullingState.depthMask = enable;
  12526. };
  12527. Engine.prototype.setColorWrite = function (enable) {
  12528. this._gl.colorMask(enable, enable, enable, enable);
  12529. this._colorWrite = enable;
  12530. };
  12531. Engine.prototype.getColorWrite = function () {
  12532. return this._colorWrite;
  12533. };
  12534. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12535. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12536. };
  12537. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12538. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12539. if (this._alphaMode === mode) {
  12540. return;
  12541. }
  12542. switch (mode) {
  12543. case Engine.ALPHA_DISABLE:
  12544. this._alphaState.alphaBlend = false;
  12545. break;
  12546. case Engine.ALPHA_PREMULTIPLIED:
  12547. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12548. this._alphaState.alphaBlend = true;
  12549. break;
  12550. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12551. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12552. this._alphaState.alphaBlend = true;
  12553. break;
  12554. case Engine.ALPHA_COMBINE:
  12555. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12556. this._alphaState.alphaBlend = true;
  12557. break;
  12558. case Engine.ALPHA_ONEONE:
  12559. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12560. this._alphaState.alphaBlend = true;
  12561. break;
  12562. case Engine.ALPHA_ADD:
  12563. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12564. this._alphaState.alphaBlend = true;
  12565. break;
  12566. case Engine.ALPHA_SUBTRACT:
  12567. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12568. this._alphaState.alphaBlend = true;
  12569. break;
  12570. case Engine.ALPHA_MULTIPLY:
  12571. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12572. this._alphaState.alphaBlend = true;
  12573. break;
  12574. case Engine.ALPHA_MAXIMIZED:
  12575. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12576. this._alphaState.alphaBlend = true;
  12577. break;
  12578. case Engine.ALPHA_INTERPOLATE:
  12579. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12580. this._alphaState.alphaBlend = true;
  12581. break;
  12582. case Engine.ALPHA_SCREENMODE:
  12583. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12584. this._alphaState.alphaBlend = true;
  12585. break;
  12586. }
  12587. if (!noDepthWriteChange) {
  12588. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12589. }
  12590. this._alphaMode = mode;
  12591. };
  12592. Engine.prototype.getAlphaMode = function () {
  12593. return this._alphaMode;
  12594. };
  12595. // Textures
  12596. Engine.prototype.wipeCaches = function (bruteForce) {
  12597. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12598. return;
  12599. }
  12600. this._currentEffect = null;
  12601. // 6/8/2017: deltakosh: Should not be required anymore.
  12602. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12603. if (bruteForce) {
  12604. this.resetTextureCache();
  12605. this._currentProgram = null;
  12606. this._stencilState.reset();
  12607. this._depthCullingState.reset();
  12608. this.setDepthFunctionToLessOrEqual();
  12609. this._alphaState.reset();
  12610. }
  12611. this._resetVertexBufferBinding();
  12612. this._cachedIndexBuffer = null;
  12613. this._cachedEffectForVertexBuffers = null;
  12614. this._unbindVertexArrayObject();
  12615. this.bindIndexBuffer(null);
  12616. };
  12617. /**
  12618. * Set the compressed texture format to use, based on the formats you have, and the formats
  12619. * supported by the hardware / browser.
  12620. *
  12621. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12622. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12623. * to API arguments needed to compressed textures. This puts the burden on the container
  12624. * generator to house the arcane code for determining these for current & future formats.
  12625. *
  12626. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12627. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12628. *
  12629. * Note: The result of this call is not taken into account when a texture is base64.
  12630. *
  12631. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12632. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12633. *
  12634. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12635. * @returns The extension selected.
  12636. */
  12637. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12638. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12639. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12640. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12641. return this._textureFormatInUse = this._texturesSupported[i];
  12642. }
  12643. }
  12644. }
  12645. // actively set format to nothing, to allow this to be called more than once
  12646. // and possibly fail the 2nd time
  12647. this._textureFormatInUse = null;
  12648. return null;
  12649. };
  12650. Engine.prototype._createTexture = function () {
  12651. var texture = this._gl.createTexture();
  12652. if (!texture) {
  12653. throw new Error("Unable to create texture");
  12654. }
  12655. return texture;
  12656. };
  12657. /**
  12658. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12659. * @param {string} urlArg- This contains one of the following:
  12660. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12661. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12662. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12663. *
  12664. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12665. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12666. * @param {Scene} scene- Needed for loading to the correct scene.
  12667. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12668. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12669. * @param {callback} onError- Optional callback to be called upon failure.
  12670. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12671. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12672. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12673. *
  12674. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12675. */
  12676. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12677. var _this = this;
  12678. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12679. if (onLoad === void 0) { onLoad = null; }
  12680. if (onError === void 0) { onError = null; }
  12681. if (buffer === void 0) { buffer = null; }
  12682. if (fallBack === void 0) { fallBack = null; }
  12683. if (format === void 0) { format = null; }
  12684. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12685. var fromData = url.substr(0, 5) === "data:";
  12686. var fromBlob = url.substr(0, 5) === "blob:";
  12687. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12688. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12689. // establish the file extension, if possible
  12690. var lastDot = url.lastIndexOf('.');
  12691. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12692. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12693. var isTGA = (extension.indexOf(".tga") === 0);
  12694. // determine if a ktx file should be substituted
  12695. var isKTX = false;
  12696. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12697. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12698. isKTX = true;
  12699. }
  12700. if (scene) {
  12701. scene._addPendingData(texture);
  12702. }
  12703. texture.url = url;
  12704. texture.generateMipMaps = !noMipmap;
  12705. texture.samplingMode = samplingMode;
  12706. texture.invertY = invertY;
  12707. if (!this._doNotHandleContextLost) {
  12708. // Keep a link to the buffer only if we plan to handle context lost
  12709. texture._buffer = buffer;
  12710. }
  12711. var onLoadObserver = null;
  12712. if (onLoad && !fallBack) {
  12713. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12714. }
  12715. if (!fallBack)
  12716. this._internalTexturesCache.push(texture);
  12717. var onerror = function (message, exception) {
  12718. if (scene) {
  12719. scene._removePendingData(texture);
  12720. }
  12721. if (onLoadObserver) {
  12722. texture.onLoadedObservable.remove(onLoadObserver);
  12723. }
  12724. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12725. if (isKTX) {
  12726. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12727. }
  12728. else if (BABYLON.Tools.UseFallbackTexture) {
  12729. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12730. }
  12731. if (onError) {
  12732. onError(message || "Unknown error", exception);
  12733. }
  12734. };
  12735. var callback = null;
  12736. // processing for non-image formats
  12737. if (isKTX || isTGA || isDDS) {
  12738. if (isKTX) {
  12739. callback = function (data) {
  12740. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12741. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12742. ktx.uploadLevels(_this._gl, !noMipmap);
  12743. return false;
  12744. }, samplingMode);
  12745. };
  12746. }
  12747. else if (isTGA) {
  12748. callback = function (arrayBuffer) {
  12749. var data = new Uint8Array(arrayBuffer);
  12750. var header = BABYLON.TGATools.GetTGAHeader(data);
  12751. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12752. BABYLON.TGATools.UploadContent(_this._gl, data);
  12753. return false;
  12754. }, samplingMode);
  12755. };
  12756. }
  12757. else if (isDDS) {
  12758. callback = function (data) {
  12759. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12760. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12761. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12762. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12763. return false;
  12764. }, samplingMode);
  12765. };
  12766. }
  12767. if (!buffer) {
  12768. this._loadFile(url, function (data) {
  12769. if (callback) {
  12770. callback(data);
  12771. }
  12772. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12773. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12774. });
  12775. }
  12776. else {
  12777. if (callback) {
  12778. callback(buffer);
  12779. }
  12780. }
  12781. // image format processing
  12782. }
  12783. else {
  12784. var onload = function (img) {
  12785. if (fromBlob && !_this._doNotHandleContextLost) {
  12786. // We need to store the image if we need to rebuild the texture
  12787. // in case of a webgl context lost
  12788. texture._buffer = img;
  12789. }
  12790. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12791. var gl = _this._gl;
  12792. var isPot = (img.width === potWidth && img.height === potHeight);
  12793. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12794. if (isPot) {
  12795. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12796. return false;
  12797. }
  12798. // Using shaders to rescale because canvas.drawImage is lossy
  12799. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12800. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12801. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12802. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12803. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12804. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12805. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12806. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12807. _this._releaseTexture(source);
  12808. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12809. continuationCallback();
  12810. });
  12811. return true;
  12812. }, samplingMode);
  12813. };
  12814. if (!fromData || isBase64)
  12815. if (buffer instanceof HTMLImageElement) {
  12816. onload(buffer);
  12817. }
  12818. else {
  12819. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12820. }
  12821. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12822. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12823. else
  12824. onload(buffer);
  12825. }
  12826. return texture;
  12827. };
  12828. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12829. var _this = this;
  12830. var rtt = this.createRenderTargetTexture({
  12831. width: destination.width,
  12832. height: destination.height,
  12833. }, {
  12834. generateMipMaps: false,
  12835. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12836. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12837. generateDepthBuffer: false,
  12838. generateStencilBuffer: false
  12839. });
  12840. if (!this._rescalePostProcess) {
  12841. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12842. }
  12843. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12844. _this._rescalePostProcess.onApply = function (effect) {
  12845. effect._bindTexture("textureSampler", source);
  12846. };
  12847. var hostingScene = scene;
  12848. if (!hostingScene) {
  12849. hostingScene = _this.scenes[_this.scenes.length - 1];
  12850. }
  12851. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12852. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12853. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12854. _this.unBindFramebuffer(rtt);
  12855. _this._releaseTexture(rtt);
  12856. if (onComplete) {
  12857. onComplete();
  12858. }
  12859. });
  12860. };
  12861. Engine.prototype._getInternalFormat = function (format) {
  12862. var internalFormat = this._gl.RGBA;
  12863. switch (format) {
  12864. case Engine.TEXTUREFORMAT_ALPHA:
  12865. internalFormat = this._gl.ALPHA;
  12866. break;
  12867. case Engine.TEXTUREFORMAT_LUMINANCE:
  12868. internalFormat = this._gl.LUMINANCE;
  12869. break;
  12870. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12871. internalFormat = this._gl.LUMINANCE_ALPHA;
  12872. break;
  12873. case Engine.TEXTUREFORMAT_RGB:
  12874. internalFormat = this._gl.RGB;
  12875. break;
  12876. case Engine.TEXTUREFORMAT_RGBA:
  12877. internalFormat = this._gl.RGBA;
  12878. break;
  12879. }
  12880. return internalFormat;
  12881. };
  12882. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12883. if (compression === void 0) { compression = null; }
  12884. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12885. if (!texture) {
  12886. return;
  12887. }
  12888. var internalFormat = this._getInternalFormat(format);
  12889. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12890. var textureType = this._getWebGLTextureType(type);
  12891. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12892. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12893. if (!this._doNotHandleContextLost) {
  12894. texture._bufferView = data;
  12895. texture.format = format;
  12896. texture.type = type;
  12897. texture.invertY = invertY;
  12898. texture._compression = compression;
  12899. }
  12900. if (texture.width % 4 !== 0) {
  12901. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12902. }
  12903. if (compression && data) {
  12904. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12905. }
  12906. else {
  12907. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12908. }
  12909. if (texture.generateMipMaps) {
  12910. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12911. }
  12912. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12913. // this.resetTextureCache();
  12914. texture.isReady = true;
  12915. };
  12916. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12917. if (compression === void 0) { compression = null; }
  12918. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12919. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12920. texture.baseWidth = width;
  12921. texture.baseHeight = height;
  12922. texture.width = width;
  12923. texture.height = height;
  12924. texture.format = format;
  12925. texture.generateMipMaps = generateMipMaps;
  12926. texture.samplingMode = samplingMode;
  12927. texture.invertY = invertY;
  12928. texture._compression = compression;
  12929. texture.type = type;
  12930. if (!this._doNotHandleContextLost) {
  12931. texture._bufferView = data;
  12932. }
  12933. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12934. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12935. // Filters
  12936. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12937. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12938. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12939. if (generateMipMaps) {
  12940. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12941. }
  12942. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12943. this._internalTexturesCache.push(texture);
  12944. return texture;
  12945. };
  12946. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12947. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12948. texture.baseWidth = width;
  12949. texture.baseHeight = height;
  12950. if (generateMipMaps) {
  12951. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12952. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12953. }
  12954. // this.resetTextureCache();
  12955. texture.width = width;
  12956. texture.height = height;
  12957. texture.isReady = false;
  12958. texture.generateMipMaps = generateMipMaps;
  12959. texture.samplingMode = samplingMode;
  12960. this.updateTextureSamplingMode(samplingMode, texture);
  12961. this._internalTexturesCache.push(texture);
  12962. return texture;
  12963. };
  12964. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12965. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12966. if (texture.isCube) {
  12967. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12968. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12969. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12970. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12971. }
  12972. else if (texture.is3D) {
  12973. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12974. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12975. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12976. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12977. }
  12978. else {
  12979. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12980. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12981. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12982. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12983. }
  12984. texture.samplingMode = samplingMode;
  12985. };
  12986. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12987. if (premulAlpha === void 0) { premulAlpha = false; }
  12988. if (!texture) {
  12989. return;
  12990. }
  12991. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12992. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12993. if (premulAlpha) {
  12994. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12995. }
  12996. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12997. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12998. if (texture.generateMipMaps) {
  12999. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13000. }
  13001. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13002. if (premulAlpha) {
  13003. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13004. }
  13005. texture.isReady = true;
  13006. };
  13007. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13008. if (!texture || texture._isDisabled) {
  13009. return;
  13010. }
  13011. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13012. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13013. try {
  13014. // Testing video texture support
  13015. if (this._videoTextureSupported === undefined) {
  13016. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13017. if (this._gl.getError() !== 0) {
  13018. this._videoTextureSupported = false;
  13019. }
  13020. else {
  13021. this._videoTextureSupported = true;
  13022. }
  13023. }
  13024. // Copy video through the current working canvas if video texture is not supported
  13025. if (!this._videoTextureSupported) {
  13026. if (!texture._workingCanvas) {
  13027. texture._workingCanvas = document.createElement("canvas");
  13028. var context = texture._workingCanvas.getContext("2d");
  13029. if (!context) {
  13030. throw new Error("Unable to get 2d context");
  13031. }
  13032. texture._workingContext = context;
  13033. texture._workingCanvas.width = texture.width;
  13034. texture._workingCanvas.height = texture.height;
  13035. }
  13036. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13037. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13038. }
  13039. else {
  13040. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13041. }
  13042. if (texture.generateMipMaps) {
  13043. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13044. }
  13045. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13046. // this.resetTextureCache();
  13047. texture.isReady = true;
  13048. }
  13049. catch (ex) {
  13050. // Something unexpected
  13051. // Let's disable the texture
  13052. texture._isDisabled = true;
  13053. }
  13054. };
  13055. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13056. var fullOptions = new RenderTargetCreationOptions();
  13057. if (options !== undefined && typeof options === "object") {
  13058. fullOptions.generateMipMaps = options.generateMipMaps;
  13059. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13060. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13061. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13062. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13063. }
  13064. else {
  13065. fullOptions.generateMipMaps = options;
  13066. fullOptions.generateDepthBuffer = true;
  13067. fullOptions.generateStencilBuffer = false;
  13068. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13069. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13070. }
  13071. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13072. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13073. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13074. }
  13075. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13076. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13077. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13078. }
  13079. var gl = this._gl;
  13080. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13081. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13082. var width = size.width || size;
  13083. var height = size.height || size;
  13084. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13085. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13086. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13087. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13088. }
  13089. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13090. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13091. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13092. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13093. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13094. // Create the framebuffer
  13095. var framebuffer = gl.createFramebuffer();
  13096. this.bindUnboundFramebuffer(framebuffer);
  13097. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13098. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13099. if (fullOptions.generateMipMaps) {
  13100. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13101. }
  13102. // Unbind
  13103. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13104. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13105. this.bindUnboundFramebuffer(null);
  13106. texture._framebuffer = framebuffer;
  13107. texture.baseWidth = width;
  13108. texture.baseHeight = height;
  13109. texture.width = width;
  13110. texture.height = height;
  13111. texture.isReady = true;
  13112. texture.samples = 1;
  13113. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13114. texture.samplingMode = fullOptions.samplingMode;
  13115. texture.type = fullOptions.type;
  13116. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13117. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13118. // this.resetTextureCache();
  13119. this._internalTexturesCache.push(texture);
  13120. return texture;
  13121. };
  13122. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13123. var generateMipMaps = false;
  13124. var generateDepthBuffer = true;
  13125. var generateStencilBuffer = false;
  13126. var generateDepthTexture = false;
  13127. var textureCount = 1;
  13128. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13129. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13130. var types = [], samplingModes = [];
  13131. if (options !== undefined) {
  13132. generateMipMaps = options.generateMipMaps;
  13133. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13134. generateStencilBuffer = options.generateStencilBuffer;
  13135. generateDepthTexture = options.generateDepthTexture;
  13136. textureCount = options.textureCount || 1;
  13137. if (options.types) {
  13138. types = options.types;
  13139. }
  13140. if (options.samplingModes) {
  13141. samplingModes = options.samplingModes;
  13142. }
  13143. }
  13144. var gl = this._gl;
  13145. // Create the framebuffer
  13146. var framebuffer = gl.createFramebuffer();
  13147. this.bindUnboundFramebuffer(framebuffer);
  13148. var width = size.width || size;
  13149. var height = size.height || size;
  13150. var textures = [];
  13151. var attachments = [];
  13152. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13153. for (var i = 0; i < textureCount; i++) {
  13154. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13155. var type = types[i] || defaultType;
  13156. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13157. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13158. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13159. }
  13160. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13161. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13162. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13163. }
  13164. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13165. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13166. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13167. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13168. }
  13169. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13170. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13171. textures.push(texture);
  13172. attachments.push(attachment);
  13173. gl.activeTexture(gl["TEXTURE" + i]);
  13174. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13175. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13176. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13177. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13178. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13179. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13180. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13181. if (generateMipMaps) {
  13182. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13183. }
  13184. // Unbind
  13185. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13186. texture._framebuffer = framebuffer;
  13187. texture._depthStencilBuffer = depthStencilBuffer;
  13188. texture.baseWidth = width;
  13189. texture.baseHeight = height;
  13190. texture.width = width;
  13191. texture.height = height;
  13192. texture.isReady = true;
  13193. texture.samples = 1;
  13194. texture.generateMipMaps = generateMipMaps;
  13195. texture.samplingMode = samplingMode;
  13196. texture.type = type;
  13197. texture._generateDepthBuffer = generateDepthBuffer;
  13198. texture._generateStencilBuffer = generateStencilBuffer;
  13199. texture._attachments = attachments;
  13200. this._internalTexturesCache.push(texture);
  13201. }
  13202. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13203. // Depth texture
  13204. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13205. gl.activeTexture(gl.TEXTURE0);
  13206. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13207. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13208. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13209. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13210. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13211. 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);
  13212. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13213. depthTexture._framebuffer = framebuffer;
  13214. depthTexture.baseWidth = width;
  13215. depthTexture.baseHeight = height;
  13216. depthTexture.width = width;
  13217. depthTexture.height = height;
  13218. depthTexture.isReady = true;
  13219. depthTexture.samples = 1;
  13220. depthTexture.generateMipMaps = generateMipMaps;
  13221. depthTexture.samplingMode = gl.NEAREST;
  13222. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13223. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13224. textures.push(depthTexture);
  13225. this._internalTexturesCache.push(depthTexture);
  13226. }
  13227. gl.drawBuffers(attachments);
  13228. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13229. this.bindUnboundFramebuffer(null);
  13230. this.resetTextureCache();
  13231. return textures;
  13232. };
  13233. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13234. if (samples === void 0) { samples = 1; }
  13235. var depthStencilBuffer = null;
  13236. var gl = this._gl;
  13237. // Create the depth/stencil buffer
  13238. if (generateStencilBuffer) {
  13239. depthStencilBuffer = gl.createRenderbuffer();
  13240. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13241. if (samples > 1) {
  13242. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13243. }
  13244. else {
  13245. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13246. }
  13247. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13248. }
  13249. else if (generateDepthBuffer) {
  13250. depthStencilBuffer = gl.createRenderbuffer();
  13251. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13252. if (samples > 1) {
  13253. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13254. }
  13255. else {
  13256. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13257. }
  13258. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13259. }
  13260. return depthStencilBuffer;
  13261. };
  13262. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13263. if (this.webGLVersion < 2 || !texture) {
  13264. return 1;
  13265. }
  13266. if (texture.samples === samples) {
  13267. return samples;
  13268. }
  13269. var gl = this._gl;
  13270. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13271. // Dispose previous render buffers
  13272. if (texture._depthStencilBuffer) {
  13273. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13274. texture._depthStencilBuffer = null;
  13275. }
  13276. if (texture._MSAAFramebuffer) {
  13277. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13278. texture._MSAAFramebuffer = null;
  13279. }
  13280. if (texture._MSAARenderBuffer) {
  13281. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13282. texture._MSAARenderBuffer = null;
  13283. }
  13284. if (samples > 1) {
  13285. var framebuffer = gl.createFramebuffer();
  13286. if (!framebuffer) {
  13287. throw new Error("Unable to create multi sampled framebuffer");
  13288. }
  13289. texture._MSAAFramebuffer = framebuffer;
  13290. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13291. var colorRenderbuffer = gl.createRenderbuffer();
  13292. if (!colorRenderbuffer) {
  13293. throw new Error("Unable to create multi sampled framebuffer");
  13294. }
  13295. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13296. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13297. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13298. texture._MSAARenderBuffer = colorRenderbuffer;
  13299. }
  13300. else {
  13301. this.bindUnboundFramebuffer(texture._framebuffer);
  13302. }
  13303. texture.samples = samples;
  13304. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13305. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13306. this.bindUnboundFramebuffer(null);
  13307. return samples;
  13308. };
  13309. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13310. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13311. return 1;
  13312. }
  13313. if (textures[0].samples === samples) {
  13314. return samples;
  13315. }
  13316. var gl = this._gl;
  13317. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13318. // Dispose previous render buffers
  13319. if (textures[0]._depthStencilBuffer) {
  13320. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13321. textures[0]._depthStencilBuffer = null;
  13322. }
  13323. if (textures[0]._MSAAFramebuffer) {
  13324. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13325. textures[0]._MSAAFramebuffer = null;
  13326. }
  13327. for (var i = 0; i < textures.length; i++) {
  13328. if (textures[i]._MSAARenderBuffer) {
  13329. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13330. textures[i]._MSAARenderBuffer = null;
  13331. }
  13332. }
  13333. if (samples > 1) {
  13334. var framebuffer = gl.createFramebuffer();
  13335. if (!framebuffer) {
  13336. throw new Error("Unable to create multi sampled framebuffer");
  13337. }
  13338. this.bindUnboundFramebuffer(framebuffer);
  13339. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13340. var attachments = [];
  13341. for (var i = 0; i < textures.length; i++) {
  13342. var texture = textures[i];
  13343. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13344. var colorRenderbuffer = gl.createRenderbuffer();
  13345. if (!colorRenderbuffer) {
  13346. throw new Error("Unable to create multi sampled framebuffer");
  13347. }
  13348. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13349. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13350. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13351. texture._MSAAFramebuffer = framebuffer;
  13352. texture._MSAARenderBuffer = colorRenderbuffer;
  13353. texture.samples = samples;
  13354. texture._depthStencilBuffer = depthStencilBuffer;
  13355. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13356. attachments.push(attachment);
  13357. }
  13358. gl.drawBuffers(attachments);
  13359. }
  13360. else {
  13361. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13362. }
  13363. this.bindUnboundFramebuffer(null);
  13364. return samples;
  13365. };
  13366. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13367. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13368. };
  13369. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13370. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13371. };
  13372. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13373. var gl = this._gl;
  13374. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13375. var generateMipMaps = true;
  13376. var generateDepthBuffer = true;
  13377. var generateStencilBuffer = false;
  13378. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13379. if (options !== undefined) {
  13380. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  13381. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13382. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  13383. if (options.samplingMode !== undefined) {
  13384. samplingMode = options.samplingMode;
  13385. }
  13386. }
  13387. texture.isCube = true;
  13388. texture.generateMipMaps = generateMipMaps;
  13389. texture.samples = 1;
  13390. texture.samplingMode = samplingMode;
  13391. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13392. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13393. for (var face = 0; face < 6; face++) {
  13394. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  13395. }
  13396. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13397. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13398. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13399. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13400. // Create the framebuffer
  13401. var framebuffer = gl.createFramebuffer();
  13402. this.bindUnboundFramebuffer(framebuffer);
  13403. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  13404. // Mipmaps
  13405. if (texture.generateMipMaps) {
  13406. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13407. }
  13408. // Unbind
  13409. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13410. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13411. this.bindUnboundFramebuffer(null);
  13412. texture._framebuffer = framebuffer;
  13413. texture.width = size;
  13414. texture.height = size;
  13415. texture.isReady = true;
  13416. //this.resetTextureCache();
  13417. this._internalTexturesCache.push(texture);
  13418. return texture;
  13419. };
  13420. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13421. var _this = this;
  13422. if (onLoad === void 0) { onLoad = null; }
  13423. if (onError === void 0) { onError = null; }
  13424. if (forcedExtension === void 0) { forcedExtension = null; }
  13425. var callback = function (loadData) {
  13426. if (!loadData) {
  13427. if (onLoad) {
  13428. onLoad(null);
  13429. }
  13430. return;
  13431. }
  13432. var texture = loadData.texture;
  13433. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13434. texture._lodGenerationScale = scale;
  13435. texture._lodGenerationOffset = offset;
  13436. if (_this._caps.textureLOD) {
  13437. // Do not add extra process if texture lod is supported.
  13438. if (onLoad) {
  13439. onLoad(texture);
  13440. }
  13441. return;
  13442. }
  13443. var mipSlices = 3;
  13444. var gl = _this._gl;
  13445. var width = loadData.width;
  13446. if (!width) {
  13447. return;
  13448. }
  13449. var textures = [];
  13450. for (var i = 0; i < mipSlices; i++) {
  13451. //compute LOD from even spacing in smoothness (matching shader calculation)
  13452. var smoothness = i / (mipSlices - 1);
  13453. var roughness = 1 - smoothness;
  13454. var minLODIndex = offset; // roughness = 0
  13455. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13456. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13457. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13458. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13459. glTextureFromLod.isCube = true;
  13460. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13461. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13462. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13463. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13464. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13465. if (loadData.isDDS) {
  13466. var info = loadData.info;
  13467. var data = loadData.data;
  13468. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13469. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13470. }
  13471. else {
  13472. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13473. }
  13474. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13475. // Wrap in a base texture for easy binding.
  13476. var lodTexture = new BABYLON.BaseTexture(scene);
  13477. lodTexture.isCube = true;
  13478. lodTexture._texture = glTextureFromLod;
  13479. glTextureFromLod.isReady = true;
  13480. textures.push(lodTexture);
  13481. }
  13482. texture._lodTextureHigh = textures[2];
  13483. texture._lodTextureMid = textures[1];
  13484. texture._lodTextureLow = textures[0];
  13485. if (onLoad) {
  13486. onLoad(texture);
  13487. }
  13488. };
  13489. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13490. };
  13491. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13492. var _this = this;
  13493. if (onLoad === void 0) { onLoad = null; }
  13494. if (onError === void 0) { onError = null; }
  13495. if (forcedExtension === void 0) { forcedExtension = null; }
  13496. var gl = this._gl;
  13497. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13498. texture.isCube = true;
  13499. texture.url = rootUrl;
  13500. texture.generateMipMaps = !noMipmap;
  13501. if (!this._doNotHandleContextLost) {
  13502. texture._extension = forcedExtension;
  13503. texture._files = files;
  13504. }
  13505. var isKTX = false;
  13506. var isDDS = false;
  13507. var lastDot = rootUrl.lastIndexOf('.');
  13508. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13509. if (this._textureFormatInUse) {
  13510. extension = this._textureFormatInUse;
  13511. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13512. isKTX = true;
  13513. }
  13514. else {
  13515. isDDS = (extension === ".dds");
  13516. }
  13517. var onerror = function (request, exception) {
  13518. if (onError && request) {
  13519. onError(request.status + " " + request.statusText, exception);
  13520. }
  13521. };
  13522. if (isKTX) {
  13523. this._loadFile(rootUrl, function (data) {
  13524. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13525. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13526. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13527. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13528. ktx.uploadLevels(_this._gl, !noMipmap);
  13529. _this.setCubeMapTextureParams(gl, loadMipmap);
  13530. texture.width = ktx.pixelWidth;
  13531. texture.height = ktx.pixelHeight;
  13532. texture.isReady = true;
  13533. }, undefined, undefined, true, onerror);
  13534. }
  13535. else if (isDDS) {
  13536. if (files && files.length === 6) {
  13537. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  13538. var info;
  13539. var loadMipmap = false;
  13540. var width = 0;
  13541. for (var index = 0; index < imgs.length; index++) {
  13542. var data = imgs[index];
  13543. info = BABYLON.DDSTools.GetDDSInfo(data);
  13544. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13545. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13546. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13547. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13548. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13549. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13550. }
  13551. texture.width = info.width;
  13552. texture.height = info.height;
  13553. texture.type = info.textureType;
  13554. width = info.width;
  13555. }
  13556. _this.setCubeMapTextureParams(gl, loadMipmap);
  13557. texture.isReady = true;
  13558. if (onLoad) {
  13559. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13560. }
  13561. }, files, onError);
  13562. }
  13563. else {
  13564. this._loadFile(rootUrl, function (data) {
  13565. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13566. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13567. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13568. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13569. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13570. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13571. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13572. }
  13573. _this.setCubeMapTextureParams(gl, loadMipmap);
  13574. texture.width = info.width;
  13575. texture.height = info.height;
  13576. texture.isReady = true;
  13577. texture.type = info.textureType;
  13578. if (onLoad) {
  13579. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13580. }
  13581. }, undefined, undefined, true, onerror);
  13582. }
  13583. }
  13584. else {
  13585. if (!files) {
  13586. throw new Error("Cannot load cubemap because files were not defined");
  13587. }
  13588. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13589. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13590. var height = width;
  13591. _this._prepareWorkingCanvas();
  13592. if (!_this._workingCanvas || !_this._workingContext) {
  13593. return;
  13594. }
  13595. _this._workingCanvas.width = width;
  13596. _this._workingCanvas.height = height;
  13597. var faces = [
  13598. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13599. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13600. ];
  13601. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13602. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13603. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13604. for (var index = 0; index < faces.length; index++) {
  13605. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13606. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13607. }
  13608. if (!noMipmap) {
  13609. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13610. }
  13611. _this.setCubeMapTextureParams(gl, !noMipmap);
  13612. texture.width = width;
  13613. texture.height = height;
  13614. texture.isReady = true;
  13615. if (format) {
  13616. texture.format = format;
  13617. }
  13618. texture.onLoadedObservable.notifyObservers(texture);
  13619. texture.onLoadedObservable.clear();
  13620. if (onLoad) {
  13621. onLoad();
  13622. }
  13623. }, files, onError);
  13624. }
  13625. this._internalTexturesCache.push(texture);
  13626. return texture;
  13627. };
  13628. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13629. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13630. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13631. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13632. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13633. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13634. // this.resetTextureCache();
  13635. };
  13636. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13637. if (compression === void 0) { compression = null; }
  13638. if (level === void 0) { level = 0; }
  13639. texture._bufferViewArray = data;
  13640. texture.format = format;
  13641. texture.type = type;
  13642. texture.invertY = invertY;
  13643. texture._compression = compression;
  13644. var gl = this._gl;
  13645. var textureType = this._getWebGLTextureType(type);
  13646. var internalFormat = this._getInternalFormat(format);
  13647. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13648. var needConversion = false;
  13649. if (internalFormat === gl.RGB) {
  13650. internalFormat = gl.RGBA;
  13651. needConversion = true;
  13652. }
  13653. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13654. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13655. if (texture.width % 4 !== 0) {
  13656. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13657. }
  13658. // Data are known to be in +X +Y +Z -X -Y -Z
  13659. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13660. var faceData = data[faceIndex];
  13661. if (compression) {
  13662. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13663. }
  13664. else {
  13665. if (needConversion) {
  13666. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  13667. }
  13668. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  13669. }
  13670. }
  13671. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13672. if (isPot && texture.generateMipMaps && level === 0) {
  13673. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13674. }
  13675. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13676. // this.resetTextureCache();
  13677. texture.isReady = true;
  13678. };
  13679. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13680. if (compression === void 0) { compression = null; }
  13681. var gl = this._gl;
  13682. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13683. texture.isCube = true;
  13684. texture.generateMipMaps = generateMipMaps;
  13685. texture.format = format;
  13686. texture.type = type;
  13687. if (!this._doNotHandleContextLost) {
  13688. texture._bufferViewArray = data;
  13689. }
  13690. var textureType = this._getWebGLTextureType(type);
  13691. var internalFormat = this._getInternalFormat(format);
  13692. if (internalFormat === gl.RGB) {
  13693. internalFormat = gl.RGBA;
  13694. }
  13695. var width = size;
  13696. var height = width;
  13697. texture.width = width;
  13698. texture.height = height;
  13699. // Double check on POT to generate Mips.
  13700. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13701. if (!isPot) {
  13702. generateMipMaps = false;
  13703. }
  13704. // Upload data if needed. The texture won't be ready until then.
  13705. if (data) {
  13706. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13707. }
  13708. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13709. // Filters
  13710. if (data && generateMipMaps) {
  13711. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13712. }
  13713. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13714. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13715. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13716. }
  13717. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13718. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13719. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13720. }
  13721. else {
  13722. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13723. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13724. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13725. }
  13726. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13727. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13728. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13729. return texture;
  13730. };
  13731. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13732. var _this = this;
  13733. if (onLoad === void 0) { onLoad = null; }
  13734. if (onError === void 0) { onError = null; }
  13735. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13736. if (invertY === void 0) { invertY = false; }
  13737. var gl = this._gl;
  13738. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13739. scene._addPendingData(texture);
  13740. texture.url = url;
  13741. this._internalTexturesCache.push(texture);
  13742. var onerror = function (request, exception) {
  13743. scene._removePendingData(texture);
  13744. if (onError && request) {
  13745. onError(request.status + " " + request.statusText, exception);
  13746. }
  13747. };
  13748. var internalCallback = function (data) {
  13749. var width = texture.width;
  13750. var faceDataArrays = callback(data);
  13751. if (!faceDataArrays) {
  13752. return;
  13753. }
  13754. if (mipmmapGenerator) {
  13755. var textureType = _this._getWebGLTextureType(type);
  13756. var internalFormat = _this._getInternalFormat(format);
  13757. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13758. var needConversion = false;
  13759. if (internalFormat === gl.RGB) {
  13760. internalFormat = gl.RGBA;
  13761. needConversion = true;
  13762. }
  13763. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13764. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13765. var mipData = mipmmapGenerator(faceDataArrays);
  13766. for (var level = 0; level < mipData.length; level++) {
  13767. var mipSize = width >> level;
  13768. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13769. var mipFaceData = mipData[level][faceIndex];
  13770. if (needConversion) {
  13771. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13772. }
  13773. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13774. }
  13775. }
  13776. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13777. }
  13778. else {
  13779. texture.generateMipMaps = !noMipmap;
  13780. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13781. }
  13782. texture.isReady = true;
  13783. // this.resetTextureCache();
  13784. scene._removePendingData(texture);
  13785. if (onLoad) {
  13786. onLoad();
  13787. }
  13788. };
  13789. this._loadFile(url, function (data) {
  13790. internalCallback(data);
  13791. }, undefined, scene.database, true, onerror);
  13792. return texture;
  13793. };
  13794. ;
  13795. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13796. if (compression === void 0) { compression = null; }
  13797. var internalFormat = this._getInternalFormat(format);
  13798. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13799. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13800. if (!this._doNotHandleContextLost) {
  13801. texture._bufferView = data;
  13802. texture.format = format;
  13803. texture.invertY = invertY;
  13804. texture._compression = compression;
  13805. }
  13806. if (texture.width % 4 !== 0) {
  13807. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13808. }
  13809. if (compression && data) {
  13810. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13811. }
  13812. else {
  13813. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13814. }
  13815. if (texture.generateMipMaps) {
  13816. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13817. }
  13818. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13819. // this.resetTextureCache();
  13820. texture.isReady = true;
  13821. };
  13822. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13823. if (compression === void 0) { compression = null; }
  13824. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13825. texture.baseWidth = width;
  13826. texture.baseHeight = height;
  13827. texture.baseDepth = depth;
  13828. texture.width = width;
  13829. texture.height = height;
  13830. texture.depth = depth;
  13831. texture.format = format;
  13832. texture.generateMipMaps = generateMipMaps;
  13833. texture.samplingMode = samplingMode;
  13834. texture.is3D = true;
  13835. if (!this._doNotHandleContextLost) {
  13836. texture._bufferView = data;
  13837. }
  13838. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13839. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13840. // Filters
  13841. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13842. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13843. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13844. if (generateMipMaps) {
  13845. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13846. }
  13847. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13848. this._internalTexturesCache.push(texture);
  13849. return texture;
  13850. };
  13851. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13852. var gl = this._gl;
  13853. if (!gl) {
  13854. return;
  13855. }
  13856. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13857. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13858. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13859. if (!noMipmap && !isCompressed) {
  13860. gl.generateMipmap(gl.TEXTURE_2D);
  13861. }
  13862. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13863. // this.resetTextureCache();
  13864. if (scene) {
  13865. scene._removePendingData(texture);
  13866. }
  13867. texture.onLoadedObservable.notifyObservers(texture);
  13868. texture.onLoadedObservable.clear();
  13869. };
  13870. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13871. var _this = this;
  13872. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13873. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13874. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13875. var gl = this._gl;
  13876. if (!gl) {
  13877. return;
  13878. }
  13879. if (!texture._webGLTexture) {
  13880. // this.resetTextureCache();
  13881. if (scene) {
  13882. scene._removePendingData(texture);
  13883. }
  13884. return;
  13885. }
  13886. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13887. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13888. texture.baseWidth = width;
  13889. texture.baseHeight = height;
  13890. texture.width = potWidth;
  13891. texture.height = potHeight;
  13892. texture.isReady = true;
  13893. if (processFunction(potWidth, potHeight, function () {
  13894. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13895. })) {
  13896. // Returning as texture needs extra async steps
  13897. return;
  13898. }
  13899. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13900. };
  13901. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13902. // Create new RGBA data container.
  13903. var rgbaData;
  13904. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13905. rgbaData = new Float32Array(width * height * 4);
  13906. }
  13907. else {
  13908. rgbaData = new Uint32Array(width * height * 4);
  13909. }
  13910. // Convert each pixel.
  13911. for (var x = 0; x < width; x++) {
  13912. for (var y = 0; y < height; y++) {
  13913. var index = (y * width + x) * 3;
  13914. var newIndex = (y * width + x) * 4;
  13915. // Map Old Value to new value.
  13916. rgbaData[newIndex + 0] = rgbData[index + 0];
  13917. rgbaData[newIndex + 1] = rgbData[index + 1];
  13918. rgbaData[newIndex + 2] = rgbData[index + 2];
  13919. // Add fully opaque alpha channel.
  13920. rgbaData[newIndex + 3] = 1;
  13921. }
  13922. }
  13923. return rgbaData;
  13924. };
  13925. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13926. var gl = this._gl;
  13927. if (texture._framebuffer) {
  13928. gl.deleteFramebuffer(texture._framebuffer);
  13929. texture._framebuffer = null;
  13930. }
  13931. if (texture._depthStencilBuffer) {
  13932. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13933. texture._depthStencilBuffer = null;
  13934. }
  13935. if (texture._MSAAFramebuffer) {
  13936. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13937. texture._MSAAFramebuffer = null;
  13938. }
  13939. if (texture._MSAARenderBuffer) {
  13940. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13941. texture._MSAARenderBuffer = null;
  13942. }
  13943. };
  13944. Engine.prototype._releaseTexture = function (texture) {
  13945. var gl = this._gl;
  13946. this._releaseFramebufferObjects(texture);
  13947. gl.deleteTexture(texture._webGLTexture);
  13948. // Unbind channels
  13949. this.unbindAllTextures();
  13950. var index = this._internalTexturesCache.indexOf(texture);
  13951. if (index !== -1) {
  13952. this._internalTexturesCache.splice(index, 1);
  13953. }
  13954. // Integrated fixed lod samplers.
  13955. if (texture._lodTextureHigh) {
  13956. texture._lodTextureHigh.dispose();
  13957. }
  13958. if (texture._lodTextureMid) {
  13959. texture._lodTextureMid.dispose();
  13960. }
  13961. if (texture._lodTextureLow) {
  13962. texture._lodTextureLow.dispose();
  13963. }
  13964. };
  13965. Engine.prototype.setProgram = function (program) {
  13966. if (this._currentProgram !== program) {
  13967. this._gl.useProgram(program);
  13968. this._currentProgram = program;
  13969. }
  13970. };
  13971. Engine.prototype.bindSamplers = function (effect) {
  13972. this.setProgram(effect.getProgram());
  13973. var samplers = effect.getSamplers();
  13974. for (var index = 0; index < samplers.length; index++) {
  13975. var uniform = effect.getUniform(samplers[index]);
  13976. if (uniform) {
  13977. this._boundUniforms[index] = uniform;
  13978. }
  13979. }
  13980. this._currentEffect = null;
  13981. };
  13982. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13983. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13984. return;
  13985. }
  13986. // Remove
  13987. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13988. // Bind last to it
  13989. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13990. // Bind to dummy
  13991. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13992. };
  13993. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13994. if (!internalTexture) {
  13995. return -1;
  13996. }
  13997. internalTexture._initialSlot = channel;
  13998. if (this.disableTextureBindingOptimization) {
  13999. if (channel !== internalTexture._designatedSlot) {
  14000. this._textureCollisions.addCount(1, false);
  14001. }
  14002. }
  14003. else {
  14004. if (channel !== internalTexture._designatedSlot) {
  14005. if (internalTexture._designatedSlot > -1) {
  14006. return internalTexture._designatedSlot;
  14007. }
  14008. else {
  14009. // No slot for this texture, let's pick a new one (if we find a free slot)
  14010. if (this._nextFreeTextureSlots.length) {
  14011. return this._nextFreeTextureSlots[0];
  14012. }
  14013. // We need to recycle the oldest bound texture, sorry.
  14014. this._textureCollisions.addCount(1, false);
  14015. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14016. }
  14017. }
  14018. }
  14019. return channel;
  14020. };
  14021. Engine.prototype._linkTrackers = function (previous, next) {
  14022. previous.next = next;
  14023. next.previous = previous;
  14024. };
  14025. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14026. var currentSlot = internalTexture._designatedSlot;
  14027. if (currentSlot === -1) {
  14028. return -1;
  14029. }
  14030. internalTexture._designatedSlot = -1;
  14031. if (this.disableTextureBindingOptimization) {
  14032. return -1;
  14033. }
  14034. // Remove from bound list
  14035. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14036. // Free the slot
  14037. this._boundTexturesCache[currentSlot] = null;
  14038. this._nextFreeTextureSlots.push(currentSlot);
  14039. return currentSlot;
  14040. };
  14041. Engine.prototype._activateCurrentTexture = function () {
  14042. if (this._currentTextureChannel !== this._activeChannel) {
  14043. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14044. this._currentTextureChannel = this._activeChannel;
  14045. }
  14046. };
  14047. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14048. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14049. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14050. this._activeChannel = texture._designatedSlot;
  14051. }
  14052. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14053. var isTextureForRendering = texture && texture._initialSlot > -1;
  14054. if (currentTextureBound !== texture) {
  14055. if (currentTextureBound) {
  14056. this._removeDesignatedSlot(currentTextureBound);
  14057. }
  14058. this._activateCurrentTexture();
  14059. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14060. this._boundTexturesCache[this._activeChannel] = texture;
  14061. if (texture) {
  14062. if (!this.disableTextureBindingOptimization) {
  14063. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14064. if (slotIndex > -1) {
  14065. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14066. }
  14067. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14068. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14069. }
  14070. texture._designatedSlot = this._activeChannel;
  14071. }
  14072. }
  14073. else if (forTextureDataUpdate) {
  14074. this._activateCurrentTexture();
  14075. }
  14076. if (isTextureForRendering && !forTextureDataUpdate) {
  14077. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14078. }
  14079. };
  14080. Engine.prototype._bindTexture = function (channel, texture) {
  14081. if (channel < 0) {
  14082. return;
  14083. }
  14084. if (texture) {
  14085. channel = this._getCorrectTextureChannel(channel, texture);
  14086. }
  14087. this._activeChannel = channel;
  14088. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14089. };
  14090. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14091. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14092. };
  14093. Engine.prototype.unbindAllTextures = function () {
  14094. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14095. this._activeChannel = channel;
  14096. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14097. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14098. if (this.webGLVersion > 1) {
  14099. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14100. }
  14101. }
  14102. };
  14103. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14104. if (channel < 0) {
  14105. return;
  14106. }
  14107. if (uniform) {
  14108. this._boundUniforms[channel] = uniform;
  14109. }
  14110. this._setTexture(channel, texture);
  14111. };
  14112. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14113. var uniform = this._boundUniforms[sourceSlot];
  14114. if (uniform._currentState === destination) {
  14115. return;
  14116. }
  14117. this._gl.uniform1i(uniform, destination);
  14118. uniform._currentState = destination;
  14119. };
  14120. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14121. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14122. // Not ready?
  14123. if (!texture) {
  14124. if (this._boundTexturesCache[channel] != null) {
  14125. this._activeChannel = channel;
  14126. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14127. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14128. if (this.webGLVersion > 1) {
  14129. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14130. }
  14131. }
  14132. return false;
  14133. }
  14134. // Video
  14135. if (texture.video) {
  14136. this._activeChannel = channel;
  14137. texture.update();
  14138. }
  14139. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14140. texture.delayLoad();
  14141. return false;
  14142. }
  14143. var internalTexture;
  14144. if (texture.isReady()) {
  14145. internalTexture = texture.getInternalTexture();
  14146. }
  14147. else if (texture.isCube) {
  14148. internalTexture = this.emptyCubeTexture;
  14149. }
  14150. else if (texture.is3D) {
  14151. internalTexture = this.emptyTexture3D;
  14152. }
  14153. else {
  14154. internalTexture = this.emptyTexture;
  14155. }
  14156. if (!isPartOfTextureArray) {
  14157. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14158. }
  14159. if (this._boundTexturesCache[channel] === internalTexture) {
  14160. this._moveBoundTextureOnTop(internalTexture);
  14161. if (!isPartOfTextureArray) {
  14162. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14163. }
  14164. return false;
  14165. }
  14166. this._activeChannel = channel;
  14167. if (internalTexture && internalTexture.is3D) {
  14168. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14169. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14170. internalTexture._cachedWrapU = texture.wrapU;
  14171. switch (texture.wrapU) {
  14172. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14173. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14174. break;
  14175. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14176. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14177. break;
  14178. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14179. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14180. break;
  14181. }
  14182. }
  14183. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14184. internalTexture._cachedWrapV = texture.wrapV;
  14185. switch (texture.wrapV) {
  14186. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14187. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14188. break;
  14189. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14190. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14191. break;
  14192. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14193. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14194. break;
  14195. }
  14196. }
  14197. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14198. internalTexture._cachedWrapR = texture.wrapR;
  14199. switch (texture.wrapR) {
  14200. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14201. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14202. break;
  14203. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14204. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14205. break;
  14206. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14207. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14208. break;
  14209. }
  14210. }
  14211. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14212. }
  14213. else if (internalTexture && internalTexture.isCube) {
  14214. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14215. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14216. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14217. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14218. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14219. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14220. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14221. }
  14222. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14223. }
  14224. else {
  14225. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14226. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14227. internalTexture._cachedWrapU = texture.wrapU;
  14228. switch (texture.wrapU) {
  14229. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14230. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14231. break;
  14232. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14233. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14234. break;
  14235. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14236. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14237. break;
  14238. }
  14239. }
  14240. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14241. internalTexture._cachedWrapV = texture.wrapV;
  14242. switch (texture.wrapV) {
  14243. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14244. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14245. break;
  14246. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14247. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14248. break;
  14249. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14250. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14251. break;
  14252. }
  14253. }
  14254. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14255. }
  14256. return true;
  14257. };
  14258. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14259. if (channel < 0 || !uniform) {
  14260. return;
  14261. }
  14262. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14263. this._textureUnits = new Int32Array(textures.length);
  14264. }
  14265. for (var i = 0; i < textures.length; i++) {
  14266. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14267. }
  14268. this._gl.uniform1iv(uniform, this._textureUnits);
  14269. for (var index = 0; index < textures.length; index++) {
  14270. this._setTexture(this._textureUnits[index], textures[index], true);
  14271. }
  14272. };
  14273. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14274. var internalTexture = texture.getInternalTexture();
  14275. if (!internalTexture) {
  14276. return;
  14277. }
  14278. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14279. var value = texture.anisotropicFilteringLevel;
  14280. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14281. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14282. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14283. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14284. }
  14285. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14286. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14287. internalTexture._cachedAnisotropicFilteringLevel = value;
  14288. }
  14289. };
  14290. Engine.prototype.readPixels = function (x, y, width, height) {
  14291. var data = new Uint8Array(height * width * 4);
  14292. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14293. return data;
  14294. };
  14295. /**
  14296. * Add an externaly attached data from its key.
  14297. * This method call will fail and return false, if such key already exists.
  14298. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14299. * @param key the unique key that identifies the data
  14300. * @param data the data object to associate to the key for this Engine instance
  14301. * @return true if no such key were already present and the data was added successfully, false otherwise
  14302. */
  14303. Engine.prototype.addExternalData = function (key, data) {
  14304. if (!this._externalData) {
  14305. this._externalData = new BABYLON.StringDictionary();
  14306. }
  14307. return this._externalData.add(key, data);
  14308. };
  14309. /**
  14310. * Get an externaly attached data from its key
  14311. * @param key the unique key that identifies the data
  14312. * @return the associated data, if present (can be null), or undefined if not present
  14313. */
  14314. Engine.prototype.getExternalData = function (key) {
  14315. if (!this._externalData) {
  14316. this._externalData = new BABYLON.StringDictionary();
  14317. }
  14318. return this._externalData.get(key);
  14319. };
  14320. /**
  14321. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14322. * @param key the unique key that identifies the data
  14323. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14324. * @return the associated data, can be null if the factory returned null.
  14325. */
  14326. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14327. if (!this._externalData) {
  14328. this._externalData = new BABYLON.StringDictionary();
  14329. }
  14330. return this._externalData.getOrAddWithFactory(key, factory);
  14331. };
  14332. /**
  14333. * Remove an externaly attached data from the Engine instance
  14334. * @param key the unique key that identifies the data
  14335. * @return true if the data was successfully removed, false if it doesn't exist
  14336. */
  14337. Engine.prototype.removeExternalData = function (key) {
  14338. if (!this._externalData) {
  14339. this._externalData = new BABYLON.StringDictionary();
  14340. }
  14341. return this._externalData.remove(key);
  14342. };
  14343. Engine.prototype.unbindAllAttributes = function () {
  14344. if (this._mustWipeVertexAttributes) {
  14345. this._mustWipeVertexAttributes = false;
  14346. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14347. this._gl.disableVertexAttribArray(i);
  14348. this._vertexAttribArraysEnabled[i] = false;
  14349. this._currentBufferPointers[i].active = false;
  14350. }
  14351. return;
  14352. }
  14353. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14354. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14355. continue;
  14356. }
  14357. this._gl.disableVertexAttribArray(i);
  14358. this._vertexAttribArraysEnabled[i] = false;
  14359. this._currentBufferPointers[i].active = false;
  14360. }
  14361. };
  14362. Engine.prototype.releaseEffects = function () {
  14363. for (var name in this._compiledEffects) {
  14364. this._deleteProgram(this._compiledEffects[name]._program);
  14365. }
  14366. this._compiledEffects = {};
  14367. };
  14368. // Dispose
  14369. Engine.prototype.dispose = function () {
  14370. this.hideLoadingUI();
  14371. this.stopRenderLoop();
  14372. // Release postProcesses
  14373. while (this.postProcesses.length) {
  14374. this.postProcesses[0].dispose();
  14375. }
  14376. // Empty texture
  14377. if (this._emptyTexture) {
  14378. this._releaseTexture(this._emptyTexture);
  14379. this._emptyTexture = null;
  14380. }
  14381. if (this._emptyCubeTexture) {
  14382. this._releaseTexture(this._emptyCubeTexture);
  14383. this._emptyCubeTexture = null;
  14384. }
  14385. // Rescale PP
  14386. if (this._rescalePostProcess) {
  14387. this._rescalePostProcess.dispose();
  14388. }
  14389. // Release scenes
  14390. while (this.scenes.length) {
  14391. this.scenes[0].dispose();
  14392. }
  14393. // Release audio engine
  14394. if (Engine.audioEngine) {
  14395. Engine.audioEngine.dispose();
  14396. }
  14397. // Release effects
  14398. this.releaseEffects();
  14399. // Unbind
  14400. this.unbindAllAttributes();
  14401. if (this._dummyFramebuffer) {
  14402. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14403. }
  14404. //WebVR
  14405. this.disableVR();
  14406. // Events
  14407. if (BABYLON.Tools.IsWindowObjectExist()) {
  14408. window.removeEventListener("blur", this._onBlur);
  14409. window.removeEventListener("focus", this._onFocus);
  14410. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14411. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14412. if (this._renderingCanvas) {
  14413. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14414. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14415. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14416. if (!this._doNotHandleContextLost) {
  14417. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14418. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14419. }
  14420. }
  14421. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14422. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14423. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14424. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14425. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14426. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14427. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14428. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14429. if (this._onVrDisplayConnect) {
  14430. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14431. if (this._onVrDisplayDisconnect) {
  14432. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14433. }
  14434. if (this._onVrDisplayPresentChange) {
  14435. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14436. }
  14437. this._onVrDisplayConnect = null;
  14438. this._onVrDisplayDisconnect = null;
  14439. }
  14440. }
  14441. // Remove from Instances
  14442. var index = Engine.Instances.indexOf(this);
  14443. if (index >= 0) {
  14444. Engine.Instances.splice(index, 1);
  14445. }
  14446. this._workingCanvas = null;
  14447. this._workingContext = null;
  14448. this._currentBufferPointers = [];
  14449. this._renderingCanvas = null;
  14450. this._currentProgram = null;
  14451. this.onResizeObservable.clear();
  14452. this.onCanvasBlurObservable.clear();
  14453. this.onCanvasFocusObservable.clear();
  14454. this.onCanvasPointerOutObservable.clear();
  14455. this.onBeginFrameObservable.clear();
  14456. this.onEndFrameObservable.clear();
  14457. BABYLON.Effect.ResetCache();
  14458. // Abort active requests
  14459. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14460. var request = _a[_i];
  14461. request.abort();
  14462. }
  14463. };
  14464. // Loading screen
  14465. Engine.prototype.displayLoadingUI = function () {
  14466. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14467. return;
  14468. }
  14469. var loadingScreen = this.loadingScreen;
  14470. if (loadingScreen) {
  14471. loadingScreen.displayLoadingUI();
  14472. }
  14473. };
  14474. Engine.prototype.hideLoadingUI = function () {
  14475. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14476. return;
  14477. }
  14478. var loadingScreen = this.loadingScreen;
  14479. if (loadingScreen) {
  14480. loadingScreen.hideLoadingUI();
  14481. }
  14482. };
  14483. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14484. get: function () {
  14485. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14486. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14487. return this._loadingScreen;
  14488. },
  14489. set: function (loadingScreen) {
  14490. this._loadingScreen = loadingScreen;
  14491. },
  14492. enumerable: true,
  14493. configurable: true
  14494. });
  14495. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14496. set: function (text) {
  14497. this.loadingScreen.loadingUIText = text;
  14498. },
  14499. enumerable: true,
  14500. configurable: true
  14501. });
  14502. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14503. set: function (color) {
  14504. this.loadingScreen.loadingUIBackgroundColor = color;
  14505. },
  14506. enumerable: true,
  14507. configurable: true
  14508. });
  14509. Engine.prototype.attachContextLostEvent = function (callback) {
  14510. if (this._renderingCanvas) {
  14511. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14512. }
  14513. };
  14514. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14515. if (this._renderingCanvas) {
  14516. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14517. }
  14518. };
  14519. Engine.prototype.getVertexShaderSource = function (program) {
  14520. var shaders = this._gl.getAttachedShaders(program);
  14521. if (!shaders) {
  14522. return null;
  14523. }
  14524. return this._gl.getShaderSource(shaders[0]);
  14525. };
  14526. Engine.prototype.getFragmentShaderSource = function (program) {
  14527. var shaders = this._gl.getAttachedShaders(program);
  14528. if (!shaders) {
  14529. return null;
  14530. }
  14531. return this._gl.getShaderSource(shaders[1]);
  14532. };
  14533. Engine.prototype.getError = function () {
  14534. return this._gl.getError();
  14535. };
  14536. // FPS
  14537. Engine.prototype.getFps = function () {
  14538. return this._fps;
  14539. };
  14540. Engine.prototype.getDeltaTime = function () {
  14541. return this._deltaTime;
  14542. };
  14543. Engine.prototype._measureFps = function () {
  14544. this._performanceMonitor.sampleFrame();
  14545. this._fps = this._performanceMonitor.averageFPS;
  14546. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14547. };
  14548. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14549. if (faceIndex === void 0) { faceIndex = -1; }
  14550. var gl = this._gl;
  14551. if (!this._dummyFramebuffer) {
  14552. var dummy = gl.createFramebuffer();
  14553. if (!dummy) {
  14554. throw new Error("Unable to create dummy framebuffer");
  14555. }
  14556. this._dummyFramebuffer = dummy;
  14557. }
  14558. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14559. if (faceIndex > -1) {
  14560. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14561. }
  14562. else {
  14563. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14564. }
  14565. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14566. var buffer;
  14567. switch (readType) {
  14568. case gl.UNSIGNED_BYTE:
  14569. buffer = new Uint8Array(4 * width * height);
  14570. readType = gl.UNSIGNED_BYTE;
  14571. break;
  14572. default:
  14573. buffer = new Float32Array(4 * width * height);
  14574. readType = gl.FLOAT;
  14575. break;
  14576. }
  14577. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14578. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14579. return buffer;
  14580. };
  14581. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14582. if (this._webGLVersion > 1) {
  14583. return this._caps.colorBufferFloat;
  14584. }
  14585. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14586. };
  14587. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14588. if (this._webGLVersion > 1) {
  14589. return this._caps.colorBufferFloat;
  14590. }
  14591. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14592. };
  14593. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14594. Engine.prototype._canRenderToFramebuffer = function (type) {
  14595. var gl = this._gl;
  14596. //clear existing errors
  14597. while (gl.getError() !== gl.NO_ERROR) { }
  14598. var successful = true;
  14599. var texture = gl.createTexture();
  14600. gl.bindTexture(gl.TEXTURE_2D, texture);
  14601. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14602. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14603. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14604. var fb = gl.createFramebuffer();
  14605. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14606. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14607. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14608. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14609. successful = successful && (gl.getError() === gl.NO_ERROR);
  14610. //try render by clearing frame buffer's color buffer
  14611. if (successful) {
  14612. gl.clear(gl.COLOR_BUFFER_BIT);
  14613. successful = successful && (gl.getError() === gl.NO_ERROR);
  14614. }
  14615. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14616. if (successful) {
  14617. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14618. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14619. var readFormat = gl.RGBA;
  14620. var readType = gl.UNSIGNED_BYTE;
  14621. var buffer = new Uint8Array(4);
  14622. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14623. successful = successful && (gl.getError() === gl.NO_ERROR);
  14624. }
  14625. //clean up
  14626. gl.deleteTexture(texture);
  14627. gl.deleteFramebuffer(fb);
  14628. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14629. //clear accumulated errors
  14630. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14631. return successful;
  14632. };
  14633. Engine.prototype._getWebGLTextureType = function (type) {
  14634. if (type === Engine.TEXTURETYPE_FLOAT) {
  14635. return this._gl.FLOAT;
  14636. }
  14637. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14638. // Add Half Float Constant.
  14639. return this._gl.HALF_FLOAT_OES;
  14640. }
  14641. return this._gl.UNSIGNED_BYTE;
  14642. };
  14643. ;
  14644. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  14645. if (this._webGLVersion === 1) {
  14646. return this._gl.RGBA;
  14647. }
  14648. if (type === Engine.TEXTURETYPE_FLOAT) {
  14649. return this._gl.RGBA32F;
  14650. }
  14651. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14652. return this._gl.RGBA16F;
  14653. }
  14654. return this._gl.RGBA;
  14655. };
  14656. ;
  14657. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  14658. if (type === Engine.TEXTURETYPE_FLOAT) {
  14659. return this._gl.RGBA32F;
  14660. }
  14661. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14662. return this._gl.RGBA16F;
  14663. }
  14664. return this._gl.RGBA8;
  14665. };
  14666. ;
  14667. Engine.prototype.createQuery = function () {
  14668. return this._gl.createQuery();
  14669. };
  14670. Engine.prototype.deleteQuery = function (query) {
  14671. this._gl.deleteQuery(query);
  14672. return this;
  14673. };
  14674. Engine.prototype.isQueryResultAvailable = function (query) {
  14675. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  14676. };
  14677. Engine.prototype.getQueryResult = function (query) {
  14678. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14679. };
  14680. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14681. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14682. this._gl.beginQuery(glAlgorithm, query);
  14683. return this;
  14684. };
  14685. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14686. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14687. this._gl.endQuery(glAlgorithm);
  14688. return this;
  14689. };
  14690. /* Time queries */
  14691. Engine.prototype._createTimeQuery = function () {
  14692. var timerQuery = this._caps.timerQuery;
  14693. if (timerQuery.createQueryEXT) {
  14694. return timerQuery.createQueryEXT();
  14695. }
  14696. return this.createQuery();
  14697. };
  14698. Engine.prototype._deleteTimeQuery = function (query) {
  14699. var timerQuery = this._caps.timerQuery;
  14700. if (timerQuery.deleteQueryEXT) {
  14701. timerQuery.deleteQueryEXT(query);
  14702. return;
  14703. }
  14704. this.deleteQuery(query);
  14705. };
  14706. Engine.prototype._getTimeQueryResult = function (query) {
  14707. var timerQuery = this._caps.timerQuery;
  14708. if (timerQuery.getQueryObjectEXT) {
  14709. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14710. }
  14711. return this.getQueryResult(query);
  14712. };
  14713. Engine.prototype._getTimeQueryAvailability = function (query) {
  14714. var timerQuery = this._caps.timerQuery;
  14715. if (timerQuery.getQueryObjectEXT) {
  14716. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14717. }
  14718. return this.isQueryResultAvailable(query);
  14719. };
  14720. Engine.prototype.startTimeQuery = function () {
  14721. var timerQuery = this._caps.timerQuery;
  14722. if (!timerQuery) {
  14723. return null;
  14724. }
  14725. var token = new BABYLON._TimeToken();
  14726. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14727. if (this._caps.canUseTimestampForTimerQuery) {
  14728. token._startTimeQuery = this._createTimeQuery();
  14729. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14730. }
  14731. else {
  14732. if (this._currentNonTimestampToken) {
  14733. return this._currentNonTimestampToken;
  14734. }
  14735. token._timeElapsedQuery = this._createTimeQuery();
  14736. if (timerQuery.beginQueryEXT) {
  14737. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14738. }
  14739. else {
  14740. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14741. }
  14742. this._currentNonTimestampToken = token;
  14743. }
  14744. return token;
  14745. };
  14746. Engine.prototype.endTimeQuery = function (token) {
  14747. var timerQuery = this._caps.timerQuery;
  14748. if (!timerQuery || !token) {
  14749. return -1;
  14750. }
  14751. if (this._caps.canUseTimestampForTimerQuery) {
  14752. if (!token._startTimeQuery) {
  14753. return -1;
  14754. }
  14755. if (!token._endTimeQuery) {
  14756. token._endTimeQuery = this._createTimeQuery();
  14757. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14758. }
  14759. }
  14760. else if (!token._timeElapsedQueryEnded) {
  14761. if (!token._timeElapsedQuery) {
  14762. return -1;
  14763. }
  14764. if (timerQuery.endQueryEXT) {
  14765. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14766. }
  14767. else {
  14768. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14769. }
  14770. token._timeElapsedQueryEnded = true;
  14771. }
  14772. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14773. var available = false;
  14774. if (token._endTimeQuery) {
  14775. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14776. }
  14777. else if (token._timeElapsedQuery) {
  14778. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14779. }
  14780. if (available && !disjoint) {
  14781. var result = 0;
  14782. if (this._caps.canUseTimestampForTimerQuery) {
  14783. if (!token._startTimeQuery || !token._endTimeQuery) {
  14784. return -1;
  14785. }
  14786. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14787. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14788. result = timeEnd - timeStart;
  14789. this._deleteTimeQuery(token._startTimeQuery);
  14790. this._deleteTimeQuery(token._endTimeQuery);
  14791. token._startTimeQuery = null;
  14792. token._endTimeQuery = null;
  14793. }
  14794. else {
  14795. if (!token._timeElapsedQuery) {
  14796. return -1;
  14797. }
  14798. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14799. this._deleteTimeQuery(token._timeElapsedQuery);
  14800. token._timeElapsedQuery = null;
  14801. token._timeElapsedQueryEnded = false;
  14802. this._currentNonTimestampToken = null;
  14803. }
  14804. return result;
  14805. }
  14806. return -1;
  14807. };
  14808. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14809. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14810. };
  14811. // Transform feedback
  14812. Engine.prototype.createTransformFeedback = function () {
  14813. return this._gl.createTransformFeedback();
  14814. };
  14815. Engine.prototype.deleteTransformFeedback = function (value) {
  14816. this._gl.deleteTransformFeedback(value);
  14817. };
  14818. Engine.prototype.bindTransformFeedback = function (value) {
  14819. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14820. };
  14821. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14822. if (usePoints === void 0) { usePoints = true; }
  14823. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14824. };
  14825. Engine.prototype.endTransformFeedback = function () {
  14826. this._gl.endTransformFeedback();
  14827. };
  14828. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14829. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14830. };
  14831. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14832. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14833. };
  14834. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14835. var _this = this;
  14836. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14837. this._activeRequests.push(request);
  14838. request.onCompleteObservable.add(function (request) {
  14839. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14840. });
  14841. return request;
  14842. };
  14843. /** @ignore */
  14844. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14845. var _this = this;
  14846. return new Promise(function (resolve, reject) {
  14847. _this._loadFile(url, function (data) {
  14848. resolve(data);
  14849. }, undefined, database, useArrayBuffer, function (request, exception) {
  14850. reject(exception);
  14851. });
  14852. });
  14853. };
  14854. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14855. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14856. var onload = function (data) {
  14857. loadedFiles[index] = data;
  14858. loadedFiles._internalCount++;
  14859. if (loadedFiles._internalCount === 6) {
  14860. onfinish(loadedFiles);
  14861. }
  14862. };
  14863. var onerror = function (request, exception) {
  14864. if (onErrorCallBack && request) {
  14865. onErrorCallBack(request.status + " " + request.statusText, exception);
  14866. }
  14867. };
  14868. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14869. };
  14870. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14871. if (onError === void 0) { onError = null; }
  14872. var loadedFiles = [];
  14873. loadedFiles._internalCount = 0;
  14874. for (var index = 0; index < 6; index++) {
  14875. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14876. }
  14877. };
  14878. // Statics
  14879. Engine.isSupported = function () {
  14880. try {
  14881. var tempcanvas = document.createElement("canvas");
  14882. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14883. return gl != null && !!window.WebGLRenderingContext;
  14884. }
  14885. catch (e) {
  14886. return false;
  14887. }
  14888. };
  14889. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14890. Engine.ExceptionList = [
  14891. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14892. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14893. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14894. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14895. ];
  14896. Engine.Instances = new Array();
  14897. // Const statics
  14898. Engine._ALPHA_DISABLE = 0;
  14899. Engine._ALPHA_ADD = 1;
  14900. Engine._ALPHA_COMBINE = 2;
  14901. Engine._ALPHA_SUBTRACT = 3;
  14902. Engine._ALPHA_MULTIPLY = 4;
  14903. Engine._ALPHA_MAXIMIZED = 5;
  14904. Engine._ALPHA_ONEONE = 6;
  14905. Engine._ALPHA_PREMULTIPLIED = 7;
  14906. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14907. Engine._ALPHA_INTERPOLATE = 9;
  14908. Engine._ALPHA_SCREENMODE = 10;
  14909. Engine._DELAYLOADSTATE_NONE = 0;
  14910. Engine._DELAYLOADSTATE_LOADED = 1;
  14911. Engine._DELAYLOADSTATE_LOADING = 2;
  14912. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14913. Engine._TEXTUREFORMAT_ALPHA = 0;
  14914. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14915. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14916. Engine._TEXTUREFORMAT_RGB = 4;
  14917. Engine._TEXTUREFORMAT_RGBA = 5;
  14918. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14919. Engine._TEXTURETYPE_FLOAT = 1;
  14920. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14921. // Depht or Stencil test Constants.
  14922. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14923. 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.
  14924. 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.
  14925. 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.
  14926. 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.
  14927. 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.
  14928. 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.
  14929. 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.
  14930. // Stencil Actions Constants.
  14931. Engine._KEEP = 0x1E00;
  14932. Engine._REPLACE = 0x1E01;
  14933. Engine._INCR = 0x1E02;
  14934. Engine._DECR = 0x1E03;
  14935. Engine._INVERT = 0x150A;
  14936. Engine._INCR_WRAP = 0x8507;
  14937. Engine._DECR_WRAP = 0x8508;
  14938. // Texture rescaling mode
  14939. Engine._SCALEMODE_FLOOR = 1;
  14940. Engine._SCALEMODE_NEAREST = 2;
  14941. Engine._SCALEMODE_CEILING = 3;
  14942. // Updatable statics so stick with vars here
  14943. Engine.CollisionsEpsilon = 0.001;
  14944. Engine.CodeRepository = "src/";
  14945. Engine.ShadersRepository = "src/Shaders/";
  14946. return Engine;
  14947. }());
  14948. BABYLON.Engine = Engine;
  14949. })(BABYLON || (BABYLON = {}));
  14950. //# sourceMappingURL=babylon.engine.js.map
  14951. var BABYLON;
  14952. (function (BABYLON) {
  14953. /**
  14954. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14955. */
  14956. var Node = /** @class */ (function () {
  14957. /**
  14958. * Creates a new Node
  14959. * @param {string} name - the name and id to be given to this node
  14960. * @param {BABYLON.Scene} the scene this node will be added to
  14961. */
  14962. function Node(name, scene) {
  14963. if (scene === void 0) { scene = null; }
  14964. /**
  14965. * Gets or sets a string used to store user defined state for the node
  14966. */
  14967. this.state = "";
  14968. /**
  14969. * Gets or sets an object used to store user defined information for the node
  14970. */
  14971. this.metadata = null;
  14972. /**
  14973. * Gets or sets a boolean used to define if the node must be serialized
  14974. */
  14975. this.doNotSerialize = false;
  14976. /** @ignore */
  14977. this._isDisposed = false;
  14978. /**
  14979. * Gets a list of {BABYLON.Animation} associated with the node
  14980. */
  14981. this.animations = new Array();
  14982. this._ranges = {};
  14983. this._isEnabled = true;
  14984. this._isReady = true;
  14985. /** @ignore */
  14986. this._currentRenderId = -1;
  14987. this._parentRenderId = -1;
  14988. /**
  14989. * An event triggered when the mesh is disposed
  14990. * @type {BABYLON.Observable}
  14991. */
  14992. this.onDisposeObservable = new BABYLON.Observable();
  14993. // Behaviors
  14994. this._behaviors = new Array();
  14995. this.name = name;
  14996. this.id = name;
  14997. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14998. this.uniqueId = this._scene.getUniqueId();
  14999. this._initCache();
  15000. }
  15001. /**
  15002. * Gets a boolean indicating if the node has been disposed
  15003. * @returns true if the node was disposed
  15004. */
  15005. Node.prototype.isDisposed = function () {
  15006. return this._isDisposed;
  15007. };
  15008. Object.defineProperty(Node.prototype, "parent", {
  15009. get: function () {
  15010. return this._parentNode;
  15011. },
  15012. /**
  15013. * Gets or sets the parent of the node
  15014. */
  15015. set: function (parent) {
  15016. if (this._parentNode === parent) {
  15017. return;
  15018. }
  15019. // Remove self from list of children of parent
  15020. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15021. var index = this._parentNode._children.indexOf(this);
  15022. if (index !== -1) {
  15023. this._parentNode._children.splice(index, 1);
  15024. }
  15025. }
  15026. // Store new parent
  15027. this._parentNode = parent;
  15028. // Add as child to new parent
  15029. if (this._parentNode) {
  15030. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15031. this._parentNode._children = new Array();
  15032. }
  15033. this._parentNode._children.push(this);
  15034. }
  15035. },
  15036. enumerable: true,
  15037. configurable: true
  15038. });
  15039. /**
  15040. * Gets a string idenfifying the name of the class
  15041. * @returns "Node" string
  15042. */
  15043. Node.prototype.getClassName = function () {
  15044. return "Node";
  15045. };
  15046. Object.defineProperty(Node.prototype, "onDispose", {
  15047. /**
  15048. * Sets a callback that will be raised when the node will be disposed
  15049. */
  15050. set: function (callback) {
  15051. if (this._onDisposeObserver) {
  15052. this.onDisposeObservable.remove(this._onDisposeObserver);
  15053. }
  15054. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15055. },
  15056. enumerable: true,
  15057. configurable: true
  15058. });
  15059. /**
  15060. * Gets the scene of the node
  15061. * @returns a {BABYLON.Scene}
  15062. */
  15063. Node.prototype.getScene = function () {
  15064. return this._scene;
  15065. };
  15066. /**
  15067. * Gets the engine of the node
  15068. * @returns a {BABYLON.Engine}
  15069. */
  15070. Node.prototype.getEngine = function () {
  15071. return this._scene.getEngine();
  15072. };
  15073. /**
  15074. * Attach a behavior to the node
  15075. * @see http://doc.babylonjs.com/features/behaviour
  15076. * @param behavior defines the behavior to attach
  15077. * @returns the current Node
  15078. */
  15079. Node.prototype.addBehavior = function (behavior) {
  15080. var _this = this;
  15081. var index = this._behaviors.indexOf(behavior);
  15082. if (index !== -1) {
  15083. return this;
  15084. }
  15085. behavior.init();
  15086. if (this._scene.isLoading) {
  15087. // We defer the attach when the scene will be loaded
  15088. var observer = this._scene.onDataLoadedObservable.add(function () {
  15089. behavior.attach(_this);
  15090. setTimeout(function () {
  15091. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15092. _this._scene.onDataLoadedObservable.remove(observer);
  15093. }, 0);
  15094. });
  15095. }
  15096. else {
  15097. behavior.attach(this);
  15098. }
  15099. this._behaviors.push(behavior);
  15100. return this;
  15101. };
  15102. /**
  15103. * Remove an attached behavior
  15104. * @see http://doc.babylonjs.com/features/behaviour
  15105. * @param behavior defines the behavior to attach
  15106. * @returns the current Node
  15107. */
  15108. Node.prototype.removeBehavior = function (behavior) {
  15109. var index = this._behaviors.indexOf(behavior);
  15110. if (index === -1) {
  15111. return this;
  15112. }
  15113. this._behaviors[index].detach();
  15114. this._behaviors.splice(index, 1);
  15115. return this;
  15116. };
  15117. Object.defineProperty(Node.prototype, "behaviors", {
  15118. /**
  15119. * Gets the list of attached behaviors
  15120. * @see http://doc.babylonjs.com/features/behaviour
  15121. */
  15122. get: function () {
  15123. return this._behaviors;
  15124. },
  15125. enumerable: true,
  15126. configurable: true
  15127. });
  15128. /**
  15129. * Gets an attached behavior by name
  15130. * @param name defines the name of the behavior to look for
  15131. * @see http://doc.babylonjs.com/features/behaviour
  15132. * @returns null if behavior was not found else the requested behavior
  15133. */
  15134. Node.prototype.getBehaviorByName = function (name) {
  15135. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15136. var behavior = _a[_i];
  15137. if (behavior.name === name) {
  15138. return behavior;
  15139. }
  15140. }
  15141. return null;
  15142. };
  15143. /**
  15144. * Returns the world matrix of the node
  15145. * @returns a matrix containing the node's world matrix
  15146. */
  15147. Node.prototype.getWorldMatrix = function () {
  15148. return BABYLON.Matrix.Identity();
  15149. };
  15150. // override it in derived class if you add new variables to the cache
  15151. // and call the parent class method
  15152. /** @ignore */
  15153. Node.prototype._initCache = function () {
  15154. this._cache = {};
  15155. this._cache.parent = undefined;
  15156. };
  15157. /** @ignore */
  15158. Node.prototype.updateCache = function (force) {
  15159. if (!force && this.isSynchronized())
  15160. return;
  15161. this._cache.parent = this.parent;
  15162. this._updateCache();
  15163. };
  15164. // override it in derived class if you add new variables to the cache
  15165. // and call the parent class method if !ignoreParentClass
  15166. /** @ignore */
  15167. Node.prototype._updateCache = function (ignoreParentClass) {
  15168. };
  15169. // override it in derived class if you add new variables to the cache
  15170. /** @ignore */
  15171. Node.prototype._isSynchronized = function () {
  15172. return true;
  15173. };
  15174. /** @ignore */
  15175. Node.prototype._markSyncedWithParent = function () {
  15176. if (this.parent) {
  15177. this._parentRenderId = this.parent._currentRenderId;
  15178. }
  15179. };
  15180. /** @ignore */
  15181. Node.prototype.isSynchronizedWithParent = function () {
  15182. if (!this.parent) {
  15183. return true;
  15184. }
  15185. if (this._parentRenderId !== this.parent._currentRenderId) {
  15186. return false;
  15187. }
  15188. return this.parent.isSynchronized();
  15189. };
  15190. /** @ignore */
  15191. Node.prototype.isSynchronized = function (updateCache) {
  15192. var check = this.hasNewParent();
  15193. check = check || !this.isSynchronizedWithParent();
  15194. check = check || !this._isSynchronized();
  15195. if (updateCache)
  15196. this.updateCache(true);
  15197. return !check;
  15198. };
  15199. /** @ignore */
  15200. Node.prototype.hasNewParent = function (update) {
  15201. if (this._cache.parent === this.parent)
  15202. return false;
  15203. if (update)
  15204. this._cache.parent = this.parent;
  15205. return true;
  15206. };
  15207. /**
  15208. * Is this node ready to be used/rendered
  15209. * @return true if the node is ready
  15210. */
  15211. Node.prototype.isReady = function () {
  15212. return this._isReady;
  15213. };
  15214. /**
  15215. * Is this node enabled?
  15216. * 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
  15217. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  15218. * @return whether this node (and its parent) is enabled
  15219. * @see setEnabled
  15220. */
  15221. Node.prototype.isEnabled = function (checkAncestors) {
  15222. if (checkAncestors === void 0) { checkAncestors = true; }
  15223. if (checkAncestors === false) {
  15224. return this._isEnabled;
  15225. }
  15226. if (this._isEnabled === false) {
  15227. return false;
  15228. }
  15229. if (this.parent !== undefined && this.parent !== null) {
  15230. return this.parent.isEnabled(checkAncestors);
  15231. }
  15232. return true;
  15233. };
  15234. /**
  15235. * Set the enabled state of this node
  15236. * @param value defines the new enabled state
  15237. * @see isEnabled
  15238. */
  15239. Node.prototype.setEnabled = function (value) {
  15240. this._isEnabled = value;
  15241. };
  15242. /**
  15243. * Is this node a descendant of the given node?
  15244. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15245. * @param ancestor defines the parent node to inspect
  15246. * @see parent
  15247. * @returns a boolean indicating if this node is a descendant of the given node
  15248. */
  15249. Node.prototype.isDescendantOf = function (ancestor) {
  15250. if (this.parent) {
  15251. if (this.parent === ancestor) {
  15252. return true;
  15253. }
  15254. return this.parent.isDescendantOf(ancestor);
  15255. }
  15256. return false;
  15257. };
  15258. /** @ignore */
  15259. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15260. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15261. if (!this._children) {
  15262. return;
  15263. }
  15264. for (var index = 0; index < this._children.length; index++) {
  15265. var item = this._children[index];
  15266. if (!predicate || predicate(item)) {
  15267. results.push(item);
  15268. }
  15269. if (!directDescendantsOnly) {
  15270. item._getDescendants(results, false, predicate);
  15271. }
  15272. }
  15273. };
  15274. /**
  15275. * Will return all nodes that have this node as ascendant
  15276. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15277. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15278. * @return all children nodes of all types
  15279. */
  15280. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15281. var results = new Array();
  15282. this._getDescendants(results, directDescendantsOnly, predicate);
  15283. return results;
  15284. };
  15285. /**
  15286. * Get all child-meshes of this node
  15287. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15288. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15289. * @returns an array of {BABYLON.AbstractMesh}
  15290. */
  15291. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15292. var results = [];
  15293. this._getDescendants(results, directDescendantsOnly, function (node) {
  15294. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15295. });
  15296. return results;
  15297. };
  15298. /**
  15299. * Get all child-transformNodes of this node
  15300. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15301. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15302. * @returns an array of {BABYLON.TransformNode}
  15303. */
  15304. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15305. var results = [];
  15306. this._getDescendants(results, directDescendantsOnly, function (node) {
  15307. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15308. });
  15309. return results;
  15310. };
  15311. /**
  15312. * Get all direct children of this node
  15313. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15314. * @returns an array of {BABYLON.Node}
  15315. */
  15316. Node.prototype.getChildren = function (predicate) {
  15317. return this.getDescendants(true, predicate);
  15318. };
  15319. /** @ignore */
  15320. Node.prototype._setReady = function (state) {
  15321. if (state === this._isReady) {
  15322. return;
  15323. }
  15324. if (!state) {
  15325. this._isReady = false;
  15326. return;
  15327. }
  15328. this._isReady = true;
  15329. if (this.onReady) {
  15330. this.onReady(this);
  15331. }
  15332. };
  15333. /**
  15334. * Get an animation by name
  15335. * @param name defines the name of the animation to look for
  15336. * @returns null if not found else the requested animation
  15337. */
  15338. Node.prototype.getAnimationByName = function (name) {
  15339. for (var i = 0; i < this.animations.length; i++) {
  15340. var animation = this.animations[i];
  15341. if (animation.name === name) {
  15342. return animation;
  15343. }
  15344. }
  15345. return null;
  15346. };
  15347. /**
  15348. * Creates an animation range for this node
  15349. * @param name defines the name of the range
  15350. * @param from defines the starting key
  15351. * @param to defines the end key
  15352. */
  15353. Node.prototype.createAnimationRange = function (name, from, to) {
  15354. // check name not already in use
  15355. if (!this._ranges[name]) {
  15356. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15357. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15358. if (this.animations[i]) {
  15359. this.animations[i].createRange(name, from, to);
  15360. }
  15361. }
  15362. }
  15363. };
  15364. /**
  15365. * Delete a specific animation range
  15366. * @param name defines the name of the range to delete
  15367. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15368. */
  15369. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15370. if (deleteFrames === void 0) { deleteFrames = true; }
  15371. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15372. if (this.animations[i]) {
  15373. this.animations[i].deleteRange(name, deleteFrames);
  15374. }
  15375. }
  15376. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15377. };
  15378. /**
  15379. * Get an animation range by name
  15380. * @param name defines the name of the animation range to look for
  15381. * @returns null if not found else the requested animation range
  15382. */
  15383. Node.prototype.getAnimationRange = function (name) {
  15384. return this._ranges[name];
  15385. };
  15386. /**
  15387. * Will start the animation sequence
  15388. * @param name defines the range frames for animation sequence
  15389. * @param loop defines if the animation should loop (false by default)
  15390. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15391. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15392. * @returns the object created for this animation. If range does not exist, it will return null
  15393. */
  15394. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15395. var range = this.getAnimationRange(name);
  15396. if (!range) {
  15397. return null;
  15398. }
  15399. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15400. };
  15401. /**
  15402. * Serialize animation ranges into a JSON compatible object
  15403. * @returns serialization object
  15404. */
  15405. Node.prototype.serializeAnimationRanges = function () {
  15406. var serializationRanges = [];
  15407. for (var name in this._ranges) {
  15408. var localRange = this._ranges[name];
  15409. if (!localRange) {
  15410. continue;
  15411. }
  15412. var range = {};
  15413. range.name = name;
  15414. range.from = localRange.from;
  15415. range.to = localRange.to;
  15416. serializationRanges.push(range);
  15417. }
  15418. return serializationRanges;
  15419. };
  15420. /**
  15421. * Computes the world matrix of the node
  15422. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15423. * @returns the world matrix
  15424. */
  15425. Node.prototype.computeWorldMatrix = function (force) {
  15426. return BABYLON.Matrix.Identity();
  15427. };
  15428. /**
  15429. * Releases all associated resources
  15430. */
  15431. Node.prototype.dispose = function () {
  15432. this.parent = null;
  15433. // Callback
  15434. this.onDisposeObservable.notifyObservers(this);
  15435. this.onDisposeObservable.clear();
  15436. // Behaviors
  15437. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15438. var behavior = _a[_i];
  15439. behavior.detach();
  15440. }
  15441. this._behaviors = [];
  15442. this._isDisposed = true;
  15443. };
  15444. /**
  15445. * Parse animation range data from a serialization object and store them into a given node
  15446. * @param node defines where to store the animation ranges
  15447. * @param parsedNode defines the serialization object to read data from
  15448. * @param scene defines the hosting scene
  15449. */
  15450. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15451. if (parsedNode.ranges) {
  15452. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15453. var data = parsedNode.ranges[index];
  15454. node.createAnimationRange(data.name, data.from, data.to);
  15455. }
  15456. }
  15457. };
  15458. __decorate([
  15459. BABYLON.serialize()
  15460. ], Node.prototype, "name", void 0);
  15461. __decorate([
  15462. BABYLON.serialize()
  15463. ], Node.prototype, "id", void 0);
  15464. __decorate([
  15465. BABYLON.serialize()
  15466. ], Node.prototype, "uniqueId", void 0);
  15467. __decorate([
  15468. BABYLON.serialize()
  15469. ], Node.prototype, "state", void 0);
  15470. __decorate([
  15471. BABYLON.serialize()
  15472. ], Node.prototype, "metadata", void 0);
  15473. return Node;
  15474. }());
  15475. BABYLON.Node = Node;
  15476. })(BABYLON || (BABYLON = {}));
  15477. //# sourceMappingURL=babylon.node.js.map
  15478. var BABYLON;
  15479. (function (BABYLON) {
  15480. var BoundingSphere = /** @class */ (function () {
  15481. function BoundingSphere(minimum, maximum) {
  15482. this.minimum = minimum;
  15483. this.maximum = maximum;
  15484. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15485. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15486. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15487. this.radius = distance * 0.5;
  15488. this.centerWorld = BABYLON.Vector3.Zero();
  15489. this._update(BABYLON.Matrix.Identity());
  15490. }
  15491. // Methods
  15492. BoundingSphere.prototype._update = function (world) {
  15493. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15494. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15495. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15496. };
  15497. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15498. for (var i = 0; i < 6; i++) {
  15499. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15500. return false;
  15501. }
  15502. return true;
  15503. };
  15504. BoundingSphere.prototype.intersectsPoint = function (point) {
  15505. var x = this.centerWorld.x - point.x;
  15506. var y = this.centerWorld.y - point.y;
  15507. var z = this.centerWorld.z - point.z;
  15508. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15509. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15510. return false;
  15511. return true;
  15512. };
  15513. // Statics
  15514. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15515. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15516. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15517. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15518. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15519. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15520. return false;
  15521. return true;
  15522. };
  15523. return BoundingSphere;
  15524. }());
  15525. BABYLON.BoundingSphere = BoundingSphere;
  15526. })(BABYLON || (BABYLON = {}));
  15527. //# sourceMappingURL=babylon.boundingSphere.js.map
  15528. var BABYLON;
  15529. (function (BABYLON) {
  15530. var BoundingBox = /** @class */ (function () {
  15531. function BoundingBox(minimum, maximum) {
  15532. this.minimum = minimum;
  15533. this.maximum = maximum;
  15534. this.vectors = new Array();
  15535. this.vectorsWorld = new Array();
  15536. // Bounding vectors
  15537. this.vectors.push(this.minimum.clone());
  15538. this.vectors.push(this.maximum.clone());
  15539. this.vectors.push(this.minimum.clone());
  15540. this.vectors[2].x = this.maximum.x;
  15541. this.vectors.push(this.minimum.clone());
  15542. this.vectors[3].y = this.maximum.y;
  15543. this.vectors.push(this.minimum.clone());
  15544. this.vectors[4].z = this.maximum.z;
  15545. this.vectors.push(this.maximum.clone());
  15546. this.vectors[5].z = this.minimum.z;
  15547. this.vectors.push(this.maximum.clone());
  15548. this.vectors[6].x = this.minimum.x;
  15549. this.vectors.push(this.maximum.clone());
  15550. this.vectors[7].y = this.minimum.y;
  15551. // OBB
  15552. this.center = this.maximum.add(this.minimum).scale(0.5);
  15553. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15554. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15555. // World
  15556. for (var index = 0; index < this.vectors.length; index++) {
  15557. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15558. }
  15559. this.minimumWorld = BABYLON.Vector3.Zero();
  15560. this.maximumWorld = BABYLON.Vector3.Zero();
  15561. this.centerWorld = BABYLON.Vector3.Zero();
  15562. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15563. this._update(BABYLON.Matrix.Identity());
  15564. }
  15565. // Methods
  15566. BoundingBox.prototype.getWorldMatrix = function () {
  15567. return this._worldMatrix;
  15568. };
  15569. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15570. this._worldMatrix.copyFrom(matrix);
  15571. return this;
  15572. };
  15573. BoundingBox.prototype._update = function (world) {
  15574. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15575. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15576. for (var index = 0; index < this.vectors.length; index++) {
  15577. var v = this.vectorsWorld[index];
  15578. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15579. if (v.x < this.minimumWorld.x)
  15580. this.minimumWorld.x = v.x;
  15581. if (v.y < this.minimumWorld.y)
  15582. this.minimumWorld.y = v.y;
  15583. if (v.z < this.minimumWorld.z)
  15584. this.minimumWorld.z = v.z;
  15585. if (v.x > this.maximumWorld.x)
  15586. this.maximumWorld.x = v.x;
  15587. if (v.y > this.maximumWorld.y)
  15588. this.maximumWorld.y = v.y;
  15589. if (v.z > this.maximumWorld.z)
  15590. this.maximumWorld.z = v.z;
  15591. }
  15592. // Extend
  15593. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15594. this.extendSizeWorld.scaleInPlace(0.5);
  15595. // OBB
  15596. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15597. this.centerWorld.scaleInPlace(0.5);
  15598. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15599. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15600. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15601. this._worldMatrix = world;
  15602. };
  15603. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15604. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15605. };
  15606. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15607. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15608. };
  15609. BoundingBox.prototype.intersectsPoint = function (point) {
  15610. var delta = -BABYLON.Epsilon;
  15611. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15612. return false;
  15613. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15614. return false;
  15615. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15616. return false;
  15617. return true;
  15618. };
  15619. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15620. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15621. };
  15622. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15623. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15624. return false;
  15625. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15626. return false;
  15627. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15628. return false;
  15629. return true;
  15630. };
  15631. // Statics
  15632. BoundingBox.Intersects = function (box0, box1) {
  15633. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  15634. return false;
  15635. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  15636. return false;
  15637. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  15638. return false;
  15639. return true;
  15640. };
  15641. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  15642. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  15643. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  15644. return (num <= (sphereRadius * sphereRadius));
  15645. };
  15646. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  15647. for (var p = 0; p < 6; p++) {
  15648. for (var i = 0; i < 8; i++) {
  15649. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15650. return false;
  15651. }
  15652. }
  15653. }
  15654. return true;
  15655. };
  15656. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  15657. for (var p = 0; p < 6; p++) {
  15658. var inCount = 8;
  15659. for (var i = 0; i < 8; i++) {
  15660. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15661. --inCount;
  15662. }
  15663. else {
  15664. break;
  15665. }
  15666. }
  15667. if (inCount === 0)
  15668. return false;
  15669. }
  15670. return true;
  15671. };
  15672. return BoundingBox;
  15673. }());
  15674. BABYLON.BoundingBox = BoundingBox;
  15675. })(BABYLON || (BABYLON = {}));
  15676. //# sourceMappingURL=babylon.boundingBox.js.map
  15677. var BABYLON;
  15678. (function (BABYLON) {
  15679. var computeBoxExtents = function (axis, box) {
  15680. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  15681. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  15682. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  15683. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  15684. var r = r0 + r1 + r2;
  15685. return {
  15686. min: p - r,
  15687. max: p + r
  15688. };
  15689. };
  15690. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  15691. var axisOverlap = function (axis, box0, box1) {
  15692. var result0 = computeBoxExtents(axis, box0);
  15693. var result1 = computeBoxExtents(axis, box1);
  15694. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  15695. };
  15696. var BoundingInfo = /** @class */ (function () {
  15697. function BoundingInfo(minimum, maximum) {
  15698. this.minimum = minimum;
  15699. this.maximum = maximum;
  15700. this._isLocked = false;
  15701. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  15702. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  15703. }
  15704. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  15705. get: function () {
  15706. return this._isLocked;
  15707. },
  15708. set: function (value) {
  15709. this._isLocked = value;
  15710. },
  15711. enumerable: true,
  15712. configurable: true
  15713. });
  15714. // Methods
  15715. BoundingInfo.prototype.update = function (world) {
  15716. if (this._isLocked) {
  15717. return;
  15718. }
  15719. this.boundingBox._update(world);
  15720. this.boundingSphere._update(world);
  15721. };
  15722. /**
  15723. * Recreate the bounding info to be centered around a specific point given a specific extend.
  15724. * @param center New center of the bounding info
  15725. * @param extend New extend of the bounding info
  15726. */
  15727. BoundingInfo.prototype.centerOn = function (center, extend) {
  15728. this.minimum = center.subtract(extend);
  15729. this.maximum = center.add(extend);
  15730. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  15731. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  15732. return this;
  15733. };
  15734. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  15735. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  15736. return false;
  15737. return this.boundingBox.isInFrustum(frustumPlanes);
  15738. };
  15739. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  15740. /**
  15741. * Gets the world distance between the min and max points of the bounding box
  15742. */
  15743. get: function () {
  15744. var boundingBox = this.boundingBox;
  15745. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  15746. return size.length();
  15747. },
  15748. enumerable: true,
  15749. configurable: true
  15750. });
  15751. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15752. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  15753. };
  15754. BoundingInfo.prototype._checkCollision = function (collider) {
  15755. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  15756. };
  15757. BoundingInfo.prototype.intersectsPoint = function (point) {
  15758. if (!this.boundingSphere.centerWorld) {
  15759. return false;
  15760. }
  15761. if (!this.boundingSphere.intersectsPoint(point)) {
  15762. return false;
  15763. }
  15764. if (!this.boundingBox.intersectsPoint(point)) {
  15765. return false;
  15766. }
  15767. return true;
  15768. };
  15769. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  15770. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  15771. return false;
  15772. }
  15773. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  15774. return false;
  15775. }
  15776. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  15777. return false;
  15778. }
  15779. if (!precise) {
  15780. return true;
  15781. }
  15782. var box0 = this.boundingBox;
  15783. var box1 = boundingInfo.boundingBox;
  15784. if (!axisOverlap(box0.directions[0], box0, box1))
  15785. return false;
  15786. if (!axisOverlap(box0.directions[1], box0, box1))
  15787. return false;
  15788. if (!axisOverlap(box0.directions[2], box0, box1))
  15789. return false;
  15790. if (!axisOverlap(box1.directions[0], box0, box1))
  15791. return false;
  15792. if (!axisOverlap(box1.directions[1], box0, box1))
  15793. return false;
  15794. if (!axisOverlap(box1.directions[2], box0, box1))
  15795. return false;
  15796. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15797. return false;
  15798. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15799. return false;
  15800. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15801. return false;
  15802. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15803. return false;
  15804. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15805. return false;
  15806. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15807. return false;
  15808. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15809. return false;
  15810. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15811. return false;
  15812. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15813. return false;
  15814. return true;
  15815. };
  15816. return BoundingInfo;
  15817. }());
  15818. BABYLON.BoundingInfo = BoundingInfo;
  15819. })(BABYLON || (BABYLON = {}));
  15820. //# sourceMappingURL=babylon.boundingInfo.js.map
  15821. var BABYLON;
  15822. (function (BABYLON) {
  15823. var TransformNode = /** @class */ (function (_super) {
  15824. __extends(TransformNode, _super);
  15825. function TransformNode(name, scene, isPure) {
  15826. if (scene === void 0) { scene = null; }
  15827. if (isPure === void 0) { isPure = true; }
  15828. var _this = _super.call(this, name, scene) || this;
  15829. // Properties
  15830. _this._rotation = BABYLON.Vector3.Zero();
  15831. _this._scaling = BABYLON.Vector3.One();
  15832. _this._isDirty = false;
  15833. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15834. _this.scalingDeterminant = 1;
  15835. _this.infiniteDistance = false;
  15836. _this.position = BABYLON.Vector3.Zero();
  15837. _this._localWorld = BABYLON.Matrix.Zero();
  15838. _this._worldMatrix = BABYLON.Matrix.Zero();
  15839. _this._worldMatrixDeterminant = 0;
  15840. _this._absolutePosition = BABYLON.Vector3.Zero();
  15841. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15842. _this._postMultiplyPivotMatrix = false;
  15843. _this._isWorldMatrixFrozen = false;
  15844. /**
  15845. * An event triggered after the world matrix is updated
  15846. * @type {BABYLON.Observable}
  15847. */
  15848. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15849. _this._nonUniformScaling = false;
  15850. if (isPure) {
  15851. _this.getScene().addTransformNode(_this);
  15852. }
  15853. return _this;
  15854. }
  15855. Object.defineProperty(TransformNode.prototype, "rotation", {
  15856. /**
  15857. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15858. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15859. * Default : (0.0, 0.0, 0.0)
  15860. */
  15861. get: function () {
  15862. return this._rotation;
  15863. },
  15864. set: function (newRotation) {
  15865. this._rotation = newRotation;
  15866. },
  15867. enumerable: true,
  15868. configurable: true
  15869. });
  15870. Object.defineProperty(TransformNode.prototype, "scaling", {
  15871. /**
  15872. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15873. * Default : (1.0, 1.0, 1.0)
  15874. */
  15875. get: function () {
  15876. return this._scaling;
  15877. },
  15878. /**
  15879. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15880. * Default : (1.0, 1.0, 1.0)
  15881. */
  15882. set: function (newScaling) {
  15883. this._scaling = newScaling;
  15884. },
  15885. enumerable: true,
  15886. configurable: true
  15887. });
  15888. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15889. /**
  15890. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15891. * It's null by default.
  15892. * 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)
  15893. */
  15894. get: function () {
  15895. return this._rotationQuaternion;
  15896. },
  15897. set: function (quaternion) {
  15898. this._rotationQuaternion = quaternion;
  15899. //reset the rotation vector.
  15900. if (quaternion && this.rotation.length()) {
  15901. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15902. }
  15903. },
  15904. enumerable: true,
  15905. configurable: true
  15906. });
  15907. /**
  15908. * Returns the latest update of the World matrix
  15909. * Returns a Matrix.
  15910. */
  15911. TransformNode.prototype.getWorldMatrix = function () {
  15912. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15913. this.computeWorldMatrix();
  15914. }
  15915. return this._worldMatrix;
  15916. };
  15917. /**
  15918. * Returns the latest update of the World matrix determinant.
  15919. */
  15920. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15921. return this._worldMatrixDeterminant;
  15922. };
  15923. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15924. /**
  15925. * Returns directly the latest state of the mesh World matrix.
  15926. * A Matrix is returned.
  15927. */
  15928. get: function () {
  15929. return this._worldMatrix;
  15930. },
  15931. enumerable: true,
  15932. configurable: true
  15933. });
  15934. /**
  15935. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15936. * Returns the AbstractMesh.
  15937. */
  15938. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15939. this._poseMatrix.copyFrom(matrix);
  15940. return this;
  15941. };
  15942. /**
  15943. * Returns the mesh Pose matrix.
  15944. * Returned object : Matrix
  15945. */
  15946. TransformNode.prototype.getPoseMatrix = function () {
  15947. return this._poseMatrix;
  15948. };
  15949. TransformNode.prototype._isSynchronized = function () {
  15950. if (this._isDirty) {
  15951. return false;
  15952. }
  15953. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15954. return false;
  15955. if (this._cache.pivotMatrixUpdated) {
  15956. return false;
  15957. }
  15958. if (this.infiniteDistance) {
  15959. return false;
  15960. }
  15961. if (!this._cache.position.equals(this.position))
  15962. return false;
  15963. if (this.rotationQuaternion) {
  15964. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15965. return false;
  15966. }
  15967. if (!this._cache.rotation.equals(this.rotation))
  15968. return false;
  15969. if (!this._cache.scaling.equals(this.scaling))
  15970. return false;
  15971. return true;
  15972. };
  15973. TransformNode.prototype._initCache = function () {
  15974. _super.prototype._initCache.call(this);
  15975. this._cache.localMatrixUpdated = false;
  15976. this._cache.position = BABYLON.Vector3.Zero();
  15977. this._cache.scaling = BABYLON.Vector3.Zero();
  15978. this._cache.rotation = BABYLON.Vector3.Zero();
  15979. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15980. this._cache.billboardMode = -1;
  15981. };
  15982. TransformNode.prototype.markAsDirty = function (property) {
  15983. if (property === "rotation") {
  15984. this.rotationQuaternion = null;
  15985. }
  15986. this._currentRenderId = Number.MAX_VALUE;
  15987. this._isDirty = true;
  15988. return this;
  15989. };
  15990. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15991. /**
  15992. * Returns the current mesh absolute position.
  15993. * Retuns a Vector3.
  15994. */
  15995. get: function () {
  15996. return this._absolutePosition;
  15997. },
  15998. enumerable: true,
  15999. configurable: true
  16000. });
  16001. /**
  16002. * Sets a new matrix to apply before all other transformation
  16003. * @param matrix defines the transform matrix
  16004. * @returns the current TransformNode
  16005. */
  16006. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16007. return this.setPivotMatrix(matrix, false);
  16008. };
  16009. /**
  16010. * Sets a new pivot matrix to the current node
  16011. * @param matrix defines the new pivot matrix to use
  16012. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  16013. * @returns the current TransformNode
  16014. */
  16015. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16016. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16017. this._pivotMatrix = matrix.clone();
  16018. this._cache.pivotMatrixUpdated = true;
  16019. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16020. if (this._postMultiplyPivotMatrix) {
  16021. if (!this._pivotMatrixInverse) {
  16022. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16023. }
  16024. else {
  16025. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16026. }
  16027. }
  16028. return this;
  16029. };
  16030. /**
  16031. * Returns the mesh pivot matrix.
  16032. * Default : Identity.
  16033. * A Matrix is returned.
  16034. */
  16035. TransformNode.prototype.getPivotMatrix = function () {
  16036. return this._pivotMatrix;
  16037. };
  16038. /**
  16039. * Prevents the World matrix to be computed any longer.
  16040. * Returns the AbstractMesh.
  16041. */
  16042. TransformNode.prototype.freezeWorldMatrix = function () {
  16043. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16044. this.computeWorldMatrix(true);
  16045. this._isWorldMatrixFrozen = true;
  16046. return this;
  16047. };
  16048. /**
  16049. * Allows back the World matrix computation.
  16050. * Returns the AbstractMesh.
  16051. */
  16052. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16053. this._isWorldMatrixFrozen = false;
  16054. this.computeWorldMatrix(true);
  16055. return this;
  16056. };
  16057. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16058. /**
  16059. * True if the World matrix has been frozen.
  16060. * Returns a boolean.
  16061. */
  16062. get: function () {
  16063. return this._isWorldMatrixFrozen;
  16064. },
  16065. enumerable: true,
  16066. configurable: true
  16067. });
  16068. /**
  16069. * Retuns the mesh absolute position in the World.
  16070. * Returns a Vector3.
  16071. */
  16072. TransformNode.prototype.getAbsolutePosition = function () {
  16073. this.computeWorldMatrix();
  16074. return this._absolutePosition;
  16075. };
  16076. /**
  16077. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16078. * Returns the AbstractMesh.
  16079. */
  16080. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16081. if (!absolutePosition) {
  16082. return this;
  16083. }
  16084. var absolutePositionX;
  16085. var absolutePositionY;
  16086. var absolutePositionZ;
  16087. if (absolutePosition.x === undefined) {
  16088. if (arguments.length < 3) {
  16089. return this;
  16090. }
  16091. absolutePositionX = arguments[0];
  16092. absolutePositionY = arguments[1];
  16093. absolutePositionZ = arguments[2];
  16094. }
  16095. else {
  16096. absolutePositionX = absolutePosition.x;
  16097. absolutePositionY = absolutePosition.y;
  16098. absolutePositionZ = absolutePosition.z;
  16099. }
  16100. if (this.parent) {
  16101. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16102. invertParentWorldMatrix.invert();
  16103. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16104. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16105. }
  16106. else {
  16107. this.position.x = absolutePositionX;
  16108. this.position.y = absolutePositionY;
  16109. this.position.z = absolutePositionZ;
  16110. }
  16111. return this;
  16112. };
  16113. /**
  16114. * Sets the mesh position in its local space.
  16115. * Returns the AbstractMesh.
  16116. */
  16117. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16118. this.computeWorldMatrix();
  16119. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16120. return this;
  16121. };
  16122. /**
  16123. * Returns the mesh position in the local space from the current World matrix values.
  16124. * Returns a new Vector3.
  16125. */
  16126. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16127. this.computeWorldMatrix();
  16128. var invLocalWorldMatrix = this._localWorld.clone();
  16129. invLocalWorldMatrix.invert();
  16130. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16131. };
  16132. /**
  16133. * Translates the mesh along the passed Vector3 in its local space.
  16134. * Returns the AbstractMesh.
  16135. */
  16136. TransformNode.prototype.locallyTranslate = function (vector3) {
  16137. this.computeWorldMatrix(true);
  16138. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16139. return this;
  16140. };
  16141. /**
  16142. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16143. * @param targetPoint the position (must be in same space as current mesh) to look at
  16144. * @param yawCor optional yaw (y-axis) correction in radians
  16145. * @param pitchCor optional pitch (x-axis) correction in radians
  16146. * @param rollCor optional roll (z-axis) correction in radians
  16147. * @param space the choosen space of the target
  16148. * @returns the TransformNode.
  16149. */
  16150. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16151. if (yawCor === void 0) { yawCor = 0; }
  16152. if (pitchCor === void 0) { pitchCor = 0; }
  16153. if (rollCor === void 0) { rollCor = 0; }
  16154. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16155. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16156. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16157. targetPoint.subtractToRef(pos, dv);
  16158. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16159. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16160. var pitch = Math.atan2(dv.y, len);
  16161. if (this.rotationQuaternion) {
  16162. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16163. }
  16164. else {
  16165. this.rotation.x = pitch + pitchCor;
  16166. this.rotation.y = yaw + yawCor;
  16167. this.rotation.z = rollCor;
  16168. }
  16169. return this;
  16170. };
  16171. /**
  16172. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16173. * This Vector3 is expressed in the World space.
  16174. */
  16175. TransformNode.prototype.getDirection = function (localAxis) {
  16176. var result = BABYLON.Vector3.Zero();
  16177. this.getDirectionToRef(localAxis, result);
  16178. return result;
  16179. };
  16180. /**
  16181. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16182. * localAxis is expressed in the mesh local space.
  16183. * result is computed in the Wordl space from the mesh World matrix.
  16184. * Returns the AbstractMesh.
  16185. */
  16186. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16187. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16188. return this;
  16189. };
  16190. /**
  16191. * Sets a new pivot point to the current node
  16192. * @param point defines the new pivot point to use
  16193. * @param space defines if the point is in world or local space (local by default)
  16194. * @returns the current TransformNode
  16195. */
  16196. TransformNode.prototype.setPivotPoint = function (point, space) {
  16197. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16198. if (this.getScene().getRenderId() == 0) {
  16199. this.computeWorldMatrix(true);
  16200. }
  16201. var wm = this.getWorldMatrix();
  16202. if (space == BABYLON.Space.WORLD) {
  16203. var tmat = BABYLON.Tmp.Matrix[0];
  16204. wm.invertToRef(tmat);
  16205. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16206. }
  16207. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16208. };
  16209. /**
  16210. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16211. */
  16212. TransformNode.prototype.getPivotPoint = function () {
  16213. var point = BABYLON.Vector3.Zero();
  16214. this.getPivotPointToRef(point);
  16215. return point;
  16216. };
  16217. /**
  16218. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16219. * Returns the AbstractMesh.
  16220. */
  16221. TransformNode.prototype.getPivotPointToRef = function (result) {
  16222. result.x = -this._pivotMatrix.m[12];
  16223. result.y = -this._pivotMatrix.m[13];
  16224. result.z = -this._pivotMatrix.m[14];
  16225. return this;
  16226. };
  16227. /**
  16228. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16229. */
  16230. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16231. var point = BABYLON.Vector3.Zero();
  16232. this.getAbsolutePivotPointToRef(point);
  16233. return point;
  16234. };
  16235. /**
  16236. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16237. * Returns the AbstractMesh.
  16238. */
  16239. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16240. result.x = this._pivotMatrix.m[12];
  16241. result.y = this._pivotMatrix.m[13];
  16242. result.z = this._pivotMatrix.m[14];
  16243. this.getPivotPointToRef(result);
  16244. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16245. return this;
  16246. };
  16247. /**
  16248. * Defines the passed node as the parent of the current node.
  16249. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16250. * Returns the TransformNode.
  16251. */
  16252. TransformNode.prototype.setParent = function (node) {
  16253. if (node === null) {
  16254. var rotation = BABYLON.Tmp.Quaternion[0];
  16255. var position = BABYLON.Tmp.Vector3[0];
  16256. var scale = BABYLON.Tmp.Vector3[1];
  16257. if (this.parent && this.parent.computeWorldMatrix) {
  16258. this.parent.computeWorldMatrix(true);
  16259. }
  16260. this.computeWorldMatrix(true);
  16261. this.getWorldMatrix().decompose(scale, rotation, position);
  16262. if (this.rotationQuaternion) {
  16263. this.rotationQuaternion.copyFrom(rotation);
  16264. }
  16265. else {
  16266. rotation.toEulerAnglesToRef(this.rotation);
  16267. }
  16268. this.scaling.x = scale.x;
  16269. this.scaling.y = scale.y;
  16270. this.scaling.z = scale.z;
  16271. this.position.x = position.x;
  16272. this.position.y = position.y;
  16273. this.position.z = position.z;
  16274. }
  16275. else {
  16276. var rotation = BABYLON.Tmp.Quaternion[0];
  16277. var position = BABYLON.Tmp.Vector3[0];
  16278. var scale = BABYLON.Tmp.Vector3[1];
  16279. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16280. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16281. this.computeWorldMatrix(true);
  16282. node.computeWorldMatrix(true);
  16283. node.getWorldMatrix().invertToRef(invParentMatrix);
  16284. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16285. diffMatrix.decompose(scale, rotation, position);
  16286. if (this.rotationQuaternion) {
  16287. this.rotationQuaternion.copyFrom(rotation);
  16288. }
  16289. else {
  16290. rotation.toEulerAnglesToRef(this.rotation);
  16291. }
  16292. this.position.x = position.x;
  16293. this.position.y = position.y;
  16294. this.position.z = position.z;
  16295. this.scaling.x = scale.x;
  16296. this.scaling.y = scale.y;
  16297. this.scaling.z = scale.z;
  16298. }
  16299. this.parent = node;
  16300. return this;
  16301. };
  16302. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16303. get: function () {
  16304. return this._nonUniformScaling;
  16305. },
  16306. enumerable: true,
  16307. configurable: true
  16308. });
  16309. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16310. if (this._nonUniformScaling === value) {
  16311. return false;
  16312. }
  16313. this._nonUniformScaling = true;
  16314. return true;
  16315. };
  16316. /**
  16317. * Attach the current TransformNode to another TransformNode associated with a bone
  16318. * @param bone Bone affecting the TransformNode
  16319. * @param affectedTransformNode TransformNode associated with the bone
  16320. */
  16321. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16322. this._transformToBoneReferal = affectedTransformNode;
  16323. this.parent = bone;
  16324. if (bone.getWorldMatrix().determinant() < 0) {
  16325. this.scalingDeterminant *= -1;
  16326. }
  16327. return this;
  16328. };
  16329. TransformNode.prototype.detachFromBone = function () {
  16330. if (!this.parent) {
  16331. return this;
  16332. }
  16333. if (this.parent.getWorldMatrix().determinant() < 0) {
  16334. this.scalingDeterminant *= -1;
  16335. }
  16336. this._transformToBoneReferal = null;
  16337. this.parent = null;
  16338. return this;
  16339. };
  16340. /**
  16341. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16342. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16343. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16344. * The passed axis is also normalized.
  16345. * Returns the AbstractMesh.
  16346. */
  16347. TransformNode.prototype.rotate = function (axis, amount, space) {
  16348. axis.normalize();
  16349. if (!this.rotationQuaternion) {
  16350. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16351. this.rotation = BABYLON.Vector3.Zero();
  16352. }
  16353. var rotationQuaternion;
  16354. if (!space || space === BABYLON.Space.LOCAL) {
  16355. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16356. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16357. }
  16358. else {
  16359. if (this.parent) {
  16360. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16361. invertParentWorldMatrix.invert();
  16362. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16363. }
  16364. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16365. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16366. }
  16367. return this;
  16368. };
  16369. /**
  16370. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16371. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16372. * The passed axis is also normalized.
  16373. * Returns the AbstractMesh.
  16374. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16375. */
  16376. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16377. axis.normalize();
  16378. if (!this.rotationQuaternion) {
  16379. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16380. this.rotation.copyFromFloats(0, 0, 0);
  16381. }
  16382. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16383. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16384. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16385. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16386. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16387. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16388. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16389. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16390. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16391. return this;
  16392. };
  16393. /**
  16394. * Translates the mesh along the axis vector for the passed distance in the given space.
  16395. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16396. * Returns the AbstractMesh.
  16397. */
  16398. TransformNode.prototype.translate = function (axis, distance, space) {
  16399. var displacementVector = axis.scale(distance);
  16400. if (!space || space === BABYLON.Space.LOCAL) {
  16401. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16402. this.setPositionWithLocalVector(tempV3);
  16403. }
  16404. else {
  16405. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16406. }
  16407. return this;
  16408. };
  16409. /**
  16410. * Adds a rotation step to the mesh current rotation.
  16411. * x, y, z are Euler angles expressed in radians.
  16412. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16413. * This means this rotation is made in the mesh local space only.
  16414. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16415. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16416. * ```javascript
  16417. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16418. * ```
  16419. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16420. * 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.
  16421. * Returns the AbstractMesh.
  16422. */
  16423. TransformNode.prototype.addRotation = function (x, y, z) {
  16424. var rotationQuaternion;
  16425. if (this.rotationQuaternion) {
  16426. rotationQuaternion = this.rotationQuaternion;
  16427. }
  16428. else {
  16429. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16430. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16431. }
  16432. var accumulation = BABYLON.Tmp.Quaternion[0];
  16433. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16434. rotationQuaternion.multiplyInPlace(accumulation);
  16435. if (!this.rotationQuaternion) {
  16436. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16437. }
  16438. return this;
  16439. };
  16440. /**
  16441. * Computes the mesh World matrix and returns it.
  16442. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16443. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16444. * If the parameter `force`is set to `true`, the actual computation is done.
  16445. * Returns the mesh World Matrix.
  16446. */
  16447. TransformNode.prototype.computeWorldMatrix = function (force) {
  16448. if (this._isWorldMatrixFrozen) {
  16449. return this._worldMatrix;
  16450. }
  16451. if (!force && this.isSynchronized(true)) {
  16452. return this._worldMatrix;
  16453. }
  16454. this._cache.position.copyFrom(this.position);
  16455. this._cache.scaling.copyFrom(this.scaling);
  16456. this._cache.pivotMatrixUpdated = false;
  16457. this._cache.billboardMode = this.billboardMode;
  16458. this._currentRenderId = this.getScene().getRenderId();
  16459. this._isDirty = false;
  16460. // Scaling
  16461. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16462. // Rotation
  16463. //rotate, if quaternion is set and rotation was used
  16464. if (this.rotationQuaternion) {
  16465. var len = this.rotation.length();
  16466. if (len) {
  16467. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16468. this.rotation.copyFromFloats(0, 0, 0);
  16469. }
  16470. }
  16471. if (this.rotationQuaternion) {
  16472. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16473. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16474. }
  16475. else {
  16476. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16477. this._cache.rotation.copyFrom(this.rotation);
  16478. }
  16479. // Translation
  16480. var camera = this.getScene().activeCamera;
  16481. if (this.infiniteDistance && !this.parent && camera) {
  16482. var cameraWorldMatrix = camera.getWorldMatrix();
  16483. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16484. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16485. }
  16486. else {
  16487. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16488. }
  16489. // Composing transformations
  16490. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16491. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16492. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16493. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16494. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16495. // Need to decompose each rotation here
  16496. var currentPosition = BABYLON.Tmp.Vector3[3];
  16497. if (this.parent && this.parent.getWorldMatrix) {
  16498. if (this._transformToBoneReferal) {
  16499. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16500. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16501. }
  16502. else {
  16503. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16504. }
  16505. }
  16506. else {
  16507. currentPosition.copyFrom(this.position);
  16508. }
  16509. currentPosition.subtractInPlace(camera.globalPosition);
  16510. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16511. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16512. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16513. }
  16514. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16515. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16516. }
  16517. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16518. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16519. }
  16520. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16521. }
  16522. else {
  16523. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16524. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16525. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16526. }
  16527. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16528. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16529. }
  16530. // Local world
  16531. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16532. // Parent
  16533. if (this.parent && this.parent.getWorldMatrix) {
  16534. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16535. if (this._transformToBoneReferal) {
  16536. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16537. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16538. }
  16539. else {
  16540. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16541. }
  16542. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16543. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16544. this._worldMatrix.copyFrom(this._localWorld);
  16545. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16546. }
  16547. else {
  16548. if (this._transformToBoneReferal) {
  16549. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16550. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16551. }
  16552. else {
  16553. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16554. }
  16555. }
  16556. this._markSyncedWithParent();
  16557. }
  16558. else {
  16559. this._worldMatrix.copyFrom(this._localWorld);
  16560. }
  16561. // Post multiply inverse of pivotMatrix
  16562. if (this._postMultiplyPivotMatrix) {
  16563. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16564. }
  16565. // Normal matrix
  16566. if (this.scaling.isNonUniform) {
  16567. this._updateNonUniformScalingState(true);
  16568. }
  16569. else if (this.parent && this.parent._nonUniformScaling) {
  16570. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16571. }
  16572. else {
  16573. this._updateNonUniformScalingState(false);
  16574. }
  16575. this._afterComputeWorldMatrix();
  16576. // Absolute position
  16577. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16578. // Callbacks
  16579. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16580. if (!this._poseMatrix) {
  16581. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16582. }
  16583. // Cache the determinant
  16584. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16585. return this._worldMatrix;
  16586. };
  16587. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16588. };
  16589. /**
  16590. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16591. * @param func: callback function to add
  16592. *
  16593. * Returns the TransformNode.
  16594. */
  16595. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16596. this.onAfterWorldMatrixUpdateObservable.add(func);
  16597. return this;
  16598. };
  16599. /**
  16600. * Removes a registered callback function.
  16601. * Returns the TransformNode.
  16602. */
  16603. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16604. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16605. return this;
  16606. };
  16607. /**
  16608. * Clone the current transform node
  16609. * Returns the new transform node
  16610. * @param name Name of the new clone
  16611. * @param newParent New parent for the clone
  16612. * @param doNotCloneChildren Do not clone children hierarchy
  16613. */
  16614. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16615. var _this = this;
  16616. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16617. result.name = name;
  16618. result.id = name;
  16619. if (newParent) {
  16620. result.parent = newParent;
  16621. }
  16622. if (!doNotCloneChildren) {
  16623. // Children
  16624. var directDescendants = this.getDescendants(true);
  16625. for (var index = 0; index < directDescendants.length; index++) {
  16626. var child = directDescendants[index];
  16627. if (child.clone) {
  16628. child.clone(name + "." + child.name, result);
  16629. }
  16630. }
  16631. }
  16632. return result;
  16633. };
  16634. TransformNode.prototype.serialize = function (currentSerializationObject) {
  16635. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  16636. serializationObject.type = this.getClassName();
  16637. // Parent
  16638. if (this.parent) {
  16639. serializationObject.parentId = this.parent.id;
  16640. }
  16641. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  16642. serializationObject.tags = BABYLON.Tags.GetTags(this);
  16643. }
  16644. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  16645. serializationObject.isEnabled = this.isEnabled();
  16646. // Parent
  16647. if (this.parent) {
  16648. serializationObject.parentId = this.parent.id;
  16649. }
  16650. return serializationObject;
  16651. };
  16652. // Statics
  16653. /**
  16654. * Returns a new TransformNode object parsed from the source provided.
  16655. * The parameter `parsedMesh` is the source.
  16656. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  16657. */
  16658. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  16659. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  16660. if (BABYLON.Tags) {
  16661. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  16662. }
  16663. if (parsedTransformNode.localMatrix) {
  16664. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  16665. }
  16666. else if (parsedTransformNode.pivotMatrix) {
  16667. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  16668. }
  16669. transformNode.setEnabled(parsedTransformNode.isEnabled);
  16670. // Parent
  16671. if (parsedTransformNode.parentId) {
  16672. transformNode._waitingParentId = parsedTransformNode.parentId;
  16673. }
  16674. return transformNode;
  16675. };
  16676. /**
  16677. * Disposes the TransformNode.
  16678. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16679. * Returns nothing.
  16680. */
  16681. TransformNode.prototype.dispose = function (doNotRecurse) {
  16682. // Animations
  16683. this.getScene().stopAnimation(this);
  16684. // Remove from scene
  16685. this.getScene().removeTransformNode(this);
  16686. if (!doNotRecurse) {
  16687. // Children
  16688. var objects = this.getDescendants(true);
  16689. for (var index = 0; index < objects.length; index++) {
  16690. objects[index].dispose();
  16691. }
  16692. }
  16693. else {
  16694. var childMeshes = this.getChildMeshes(true);
  16695. for (index = 0; index < childMeshes.length; index++) {
  16696. var child = childMeshes[index];
  16697. child.parent = null;
  16698. child.computeWorldMatrix(true);
  16699. }
  16700. }
  16701. this.onAfterWorldMatrixUpdateObservable.clear();
  16702. _super.prototype.dispose.call(this);
  16703. };
  16704. // Statics
  16705. TransformNode.BILLBOARDMODE_NONE = 0;
  16706. TransformNode.BILLBOARDMODE_X = 1;
  16707. TransformNode.BILLBOARDMODE_Y = 2;
  16708. TransformNode.BILLBOARDMODE_Z = 4;
  16709. TransformNode.BILLBOARDMODE_ALL = 7;
  16710. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  16711. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  16712. __decorate([
  16713. BABYLON.serializeAsVector3()
  16714. ], TransformNode.prototype, "_rotation", void 0);
  16715. __decorate([
  16716. BABYLON.serializeAsQuaternion()
  16717. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  16718. __decorate([
  16719. BABYLON.serializeAsVector3()
  16720. ], TransformNode.prototype, "_scaling", void 0);
  16721. __decorate([
  16722. BABYLON.serialize()
  16723. ], TransformNode.prototype, "billboardMode", void 0);
  16724. __decorate([
  16725. BABYLON.serialize()
  16726. ], TransformNode.prototype, "scalingDeterminant", void 0);
  16727. __decorate([
  16728. BABYLON.serialize()
  16729. ], TransformNode.prototype, "infiniteDistance", void 0);
  16730. __decorate([
  16731. BABYLON.serializeAsVector3()
  16732. ], TransformNode.prototype, "position", void 0);
  16733. return TransformNode;
  16734. }(BABYLON.Node));
  16735. BABYLON.TransformNode = TransformNode;
  16736. })(BABYLON || (BABYLON = {}));
  16737. //# sourceMappingURL=babylon.transformNode.js.map
  16738. var BABYLON;
  16739. (function (BABYLON) {
  16740. var AbstractMesh = /** @class */ (function (_super) {
  16741. __extends(AbstractMesh, _super);
  16742. // Constructor
  16743. function AbstractMesh(name, scene) {
  16744. if (scene === void 0) { scene = null; }
  16745. var _this = _super.call(this, name, scene, false) || this;
  16746. _this._facetNb = 0; // facet number
  16747. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  16748. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  16749. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  16750. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  16751. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  16752. _this._subDiv = {
  16753. max: 1,
  16754. X: 1,
  16755. Y: 1,
  16756. Z: 1
  16757. };
  16758. _this._facetDepthSort = false; // is the facet depth sort to be computed
  16759. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  16760. // Events
  16761. /**
  16762. * An event triggered when this mesh collides with another one
  16763. * @type {BABYLON.Observable}
  16764. */
  16765. _this.onCollideObservable = new BABYLON.Observable();
  16766. /**
  16767. * An event triggered when the collision's position changes
  16768. * @type {BABYLON.Observable}
  16769. */
  16770. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  16771. /**
  16772. * An event triggered when material is changed
  16773. * @type {BABYLON.Observable}
  16774. */
  16775. _this.onMaterialChangedObservable = new BABYLON.Observable();
  16776. // Properties
  16777. _this.definedFacingForward = true; // orientation for POV movement & rotation
  16778. /**
  16779. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  16780. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  16781. * or
  16782. * 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.
  16783. * for more info check WebGl documentations
  16784. */
  16785. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  16786. /**
  16787. * 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:
  16788. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  16789. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  16790. * 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.
  16791. */
  16792. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  16793. /**
  16794. * 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.
  16795. * The default value is -1 which means don't break the query and wait till the result.
  16796. */
  16797. _this.occlusionRetryCount = -1;
  16798. _this._occlusionInternalRetryCounter = 0;
  16799. _this._isOccluded = false;
  16800. _this._isOcclusionQueryInProgress = false;
  16801. _this._visibility = 1.0;
  16802. _this.alphaIndex = Number.MAX_VALUE;
  16803. _this.isVisible = true;
  16804. _this.isPickable = true;
  16805. _this.showBoundingBox = false;
  16806. _this.showSubMeshesBoundingBox = false;
  16807. _this.isBlocker = false;
  16808. _this.enablePointerMoveEvents = false;
  16809. _this.renderingGroupId = 0;
  16810. _this._receiveShadows = false;
  16811. _this.renderOutline = false;
  16812. _this.outlineColor = BABYLON.Color3.Red();
  16813. _this.outlineWidth = 0.02;
  16814. _this.renderOverlay = false;
  16815. _this.overlayColor = BABYLON.Color3.Red();
  16816. _this.overlayAlpha = 0.5;
  16817. _this._hasVertexAlpha = false;
  16818. _this._useVertexColors = true;
  16819. _this._computeBonesUsingShaders = true;
  16820. _this._numBoneInfluencers = 4;
  16821. _this._applyFog = true;
  16822. _this.useOctreeForRenderingSelection = true;
  16823. _this.useOctreeForPicking = true;
  16824. _this.useOctreeForCollisions = true;
  16825. _this._layerMask = 0x0FFFFFFF;
  16826. /**
  16827. * True if the mesh must be rendered in any case.
  16828. */
  16829. _this.alwaysSelectAsActiveMesh = false;
  16830. /**
  16831. * This scene's action manager
  16832. * @type {BABYLON.ActionManager}
  16833. */
  16834. _this.actionManager = null;
  16835. // Physics
  16836. _this.physicsImpostor = null;
  16837. // Collisions
  16838. _this._checkCollisions = false;
  16839. _this._collisionMask = -1;
  16840. _this._collisionGroup = -1;
  16841. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16842. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16843. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16844. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16845. // Edges
  16846. _this.edgesWidth = 1;
  16847. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16848. // Cache
  16849. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16850. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16851. _this._renderId = 0;
  16852. _this._intersectionsInProgress = new Array();
  16853. _this._unIndexed = false;
  16854. _this._lightSources = new Array();
  16855. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16856. if (collidedMesh === void 0) { collidedMesh = null; }
  16857. //TODO move this to the collision coordinator!
  16858. if (_this.getScene().workerCollisions)
  16859. newPosition.multiplyInPlace(_this._collider._radius);
  16860. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16861. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16862. _this.position.addInPlace(_this._diffPositionForCollisions);
  16863. }
  16864. if (collidedMesh) {
  16865. _this.onCollideObservable.notifyObservers(collidedMesh);
  16866. }
  16867. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16868. };
  16869. _this.getScene().addMesh(_this);
  16870. _this._resyncLightSources();
  16871. return _this;
  16872. }
  16873. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16874. get: function () {
  16875. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16876. },
  16877. enumerable: true,
  16878. configurable: true
  16879. });
  16880. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16881. get: function () {
  16882. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16883. },
  16884. enumerable: true,
  16885. configurable: true
  16886. });
  16887. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  16888. get: function () {
  16889. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  16890. },
  16891. enumerable: true,
  16892. configurable: true
  16893. });
  16894. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  16895. get: function () {
  16896. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  16897. },
  16898. enumerable: true,
  16899. configurable: true
  16900. });
  16901. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  16902. get: function () {
  16903. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  16904. },
  16905. enumerable: true,
  16906. configurable: true
  16907. });
  16908. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  16909. /**
  16910. * Read-only : the number of facets in the mesh
  16911. */
  16912. get: function () {
  16913. return this._facetNb;
  16914. },
  16915. enumerable: true,
  16916. configurable: true
  16917. });
  16918. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  16919. /**
  16920. * The number (integer) of subdivisions per axis in the partioning space
  16921. */
  16922. get: function () {
  16923. return this._partitioningSubdivisions;
  16924. },
  16925. set: function (nb) {
  16926. this._partitioningSubdivisions = nb;
  16927. },
  16928. enumerable: true,
  16929. configurable: true
  16930. });
  16931. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16932. /**
  16933. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16934. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16935. */
  16936. get: function () {
  16937. return this._partitioningBBoxRatio;
  16938. },
  16939. set: function (ratio) {
  16940. this._partitioningBBoxRatio = ratio;
  16941. },
  16942. enumerable: true,
  16943. configurable: true
  16944. });
  16945. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16946. /**
  16947. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16948. * Works only for updatable meshes.
  16949. * Doesn't work with multi-materials.
  16950. */
  16951. get: function () {
  16952. return this._facetDepthSort;
  16953. },
  16954. set: function (sort) {
  16955. this._facetDepthSort = sort;
  16956. },
  16957. enumerable: true,
  16958. configurable: true
  16959. });
  16960. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16961. /**
  16962. * The location (Vector3) where the facet depth sort must be computed from.
  16963. * By default, the active camera position.
  16964. * Used only when facet depth sort is enabled.
  16965. */
  16966. get: function () {
  16967. return this._facetDepthSortFrom;
  16968. },
  16969. set: function (location) {
  16970. this._facetDepthSortFrom = location;
  16971. },
  16972. enumerable: true,
  16973. configurable: true
  16974. });
  16975. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16976. /**
  16977. * Read-only boolean : is the feature facetData enabled ?
  16978. */
  16979. get: function () {
  16980. return this._facetDataEnabled;
  16981. },
  16982. enumerable: true,
  16983. configurable: true
  16984. });
  16985. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16986. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16987. return false;
  16988. }
  16989. this._markSubMeshesAsMiscDirty();
  16990. return true;
  16991. };
  16992. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16993. set: function (callback) {
  16994. if (this._onCollideObserver) {
  16995. this.onCollideObservable.remove(this._onCollideObserver);
  16996. }
  16997. this._onCollideObserver = this.onCollideObservable.add(callback);
  16998. },
  16999. enumerable: true,
  17000. configurable: true
  17001. });
  17002. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17003. set: function (callback) {
  17004. if (this._onCollisionPositionChangeObserver) {
  17005. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17006. }
  17007. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17008. },
  17009. enumerable: true,
  17010. configurable: true
  17011. });
  17012. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17013. /**
  17014. * 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.
  17015. */
  17016. get: function () {
  17017. return this._isOccluded;
  17018. },
  17019. set: function (value) {
  17020. this._isOccluded = value;
  17021. },
  17022. enumerable: true,
  17023. configurable: true
  17024. });
  17025. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17026. /**
  17027. * Flag to check the progress status of the query
  17028. */
  17029. get: function () {
  17030. return this._isOcclusionQueryInProgress;
  17031. },
  17032. enumerable: true,
  17033. configurable: true
  17034. });
  17035. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17036. /**
  17037. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17038. */
  17039. get: function () {
  17040. return this._visibility;
  17041. },
  17042. /**
  17043. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17044. */
  17045. set: function (value) {
  17046. if (this._visibility === value) {
  17047. return;
  17048. }
  17049. this._visibility = value;
  17050. this._markSubMeshesAsMiscDirty();
  17051. },
  17052. enumerable: true,
  17053. configurable: true
  17054. });
  17055. Object.defineProperty(AbstractMesh.prototype, "material", {
  17056. get: function () {
  17057. return this._material;
  17058. },
  17059. set: function (value) {
  17060. if (this._material === value) {
  17061. return;
  17062. }
  17063. this._material = value;
  17064. if (this.onMaterialChangedObservable.hasObservers) {
  17065. this.onMaterialChangedObservable.notifyObservers(this);
  17066. }
  17067. if (!this.subMeshes) {
  17068. return;
  17069. }
  17070. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17071. var subMesh = _a[_i];
  17072. subMesh.setEffect(null);
  17073. }
  17074. },
  17075. enumerable: true,
  17076. configurable: true
  17077. });
  17078. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17079. get: function () {
  17080. return this._receiveShadows;
  17081. },
  17082. set: function (value) {
  17083. if (this._receiveShadows === value) {
  17084. return;
  17085. }
  17086. this._receiveShadows = value;
  17087. this._markSubMeshesAsLightDirty();
  17088. },
  17089. enumerable: true,
  17090. configurable: true
  17091. });
  17092. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17093. get: function () {
  17094. return this._hasVertexAlpha;
  17095. },
  17096. set: function (value) {
  17097. if (this._hasVertexAlpha === value) {
  17098. return;
  17099. }
  17100. this._hasVertexAlpha = value;
  17101. this._markSubMeshesAsAttributesDirty();
  17102. this._markSubMeshesAsMiscDirty();
  17103. },
  17104. enumerable: true,
  17105. configurable: true
  17106. });
  17107. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17108. get: function () {
  17109. return this._useVertexColors;
  17110. },
  17111. set: function (value) {
  17112. if (this._useVertexColors === value) {
  17113. return;
  17114. }
  17115. this._useVertexColors = value;
  17116. this._markSubMeshesAsAttributesDirty();
  17117. },
  17118. enumerable: true,
  17119. configurable: true
  17120. });
  17121. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17122. get: function () {
  17123. return this._computeBonesUsingShaders;
  17124. },
  17125. set: function (value) {
  17126. if (this._computeBonesUsingShaders === value) {
  17127. return;
  17128. }
  17129. this._computeBonesUsingShaders = value;
  17130. this._markSubMeshesAsAttributesDirty();
  17131. },
  17132. enumerable: true,
  17133. configurable: true
  17134. });
  17135. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17136. get: function () {
  17137. return this._numBoneInfluencers;
  17138. },
  17139. set: function (value) {
  17140. if (this._numBoneInfluencers === value) {
  17141. return;
  17142. }
  17143. this._numBoneInfluencers = value;
  17144. this._markSubMeshesAsAttributesDirty();
  17145. },
  17146. enumerable: true,
  17147. configurable: true
  17148. });
  17149. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17150. get: function () {
  17151. return this._applyFog;
  17152. },
  17153. set: function (value) {
  17154. if (this._applyFog === value) {
  17155. return;
  17156. }
  17157. this._applyFog = value;
  17158. this._markSubMeshesAsMiscDirty();
  17159. },
  17160. enumerable: true,
  17161. configurable: true
  17162. });
  17163. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17164. get: function () {
  17165. return this._layerMask;
  17166. },
  17167. set: function (value) {
  17168. if (value === this._layerMask) {
  17169. return;
  17170. }
  17171. this._layerMask = value;
  17172. this._resyncLightSources();
  17173. },
  17174. enumerable: true,
  17175. configurable: true
  17176. });
  17177. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17178. get: function () {
  17179. return this._collisionMask;
  17180. },
  17181. set: function (mask) {
  17182. this._collisionMask = !isNaN(mask) ? mask : -1;
  17183. },
  17184. enumerable: true,
  17185. configurable: true
  17186. });
  17187. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17188. get: function () {
  17189. return this._collisionGroup;
  17190. },
  17191. set: function (mask) {
  17192. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17193. },
  17194. enumerable: true,
  17195. configurable: true
  17196. });
  17197. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17198. get: function () {
  17199. return null;
  17200. },
  17201. enumerable: true,
  17202. configurable: true
  17203. });
  17204. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17205. get: function () {
  17206. return this._skeleton;
  17207. },
  17208. set: function (value) {
  17209. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17210. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17211. }
  17212. if (value && value.needInitialSkinMatrix) {
  17213. value._registerMeshWithPoseMatrix(this);
  17214. }
  17215. this._skeleton = value;
  17216. if (!this._skeleton) {
  17217. this._bonesTransformMatrices = null;
  17218. }
  17219. this._markSubMeshesAsAttributesDirty();
  17220. },
  17221. enumerable: true,
  17222. configurable: true
  17223. });
  17224. /**
  17225. * Returns the string "AbstractMesh"
  17226. */
  17227. AbstractMesh.prototype.getClassName = function () {
  17228. return "AbstractMesh";
  17229. };
  17230. /**
  17231. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17232. */
  17233. AbstractMesh.prototype.toString = function (fullDetails) {
  17234. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17235. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17236. if (this._skeleton) {
  17237. ret += ", skeleton: " + this._skeleton.name;
  17238. }
  17239. if (fullDetails) {
  17240. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17241. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17242. }
  17243. return ret;
  17244. };
  17245. AbstractMesh.prototype._rebuild = function () {
  17246. if (this._occlusionQuery) {
  17247. this._occlusionQuery = null;
  17248. }
  17249. if (this._edgesRenderer) {
  17250. this._edgesRenderer._rebuild();
  17251. }
  17252. if (!this.subMeshes) {
  17253. return;
  17254. }
  17255. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17256. var subMesh = _a[_i];
  17257. subMesh._rebuild();
  17258. }
  17259. };
  17260. AbstractMesh.prototype._resyncLightSources = function () {
  17261. this._lightSources.length = 0;
  17262. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17263. var light = _a[_i];
  17264. if (!light.isEnabled()) {
  17265. continue;
  17266. }
  17267. if (light.canAffectMesh(this)) {
  17268. this._lightSources.push(light);
  17269. }
  17270. }
  17271. this._markSubMeshesAsLightDirty();
  17272. };
  17273. AbstractMesh.prototype._resyncLighSource = function (light) {
  17274. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17275. var index = this._lightSources.indexOf(light);
  17276. if (index === -1) {
  17277. if (!isIn) {
  17278. return;
  17279. }
  17280. this._lightSources.push(light);
  17281. }
  17282. else {
  17283. if (isIn) {
  17284. return;
  17285. }
  17286. this._lightSources.splice(index, 1);
  17287. }
  17288. this._markSubMeshesAsLightDirty();
  17289. };
  17290. AbstractMesh.prototype._removeLightSource = function (light) {
  17291. var index = this._lightSources.indexOf(light);
  17292. if (index === -1) {
  17293. return;
  17294. }
  17295. this._lightSources.splice(index, 1);
  17296. this._markSubMeshesAsLightDirty();
  17297. };
  17298. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17299. if (!this.subMeshes) {
  17300. return;
  17301. }
  17302. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17303. var subMesh = _a[_i];
  17304. if (subMesh._materialDefines) {
  17305. func(subMesh._materialDefines);
  17306. }
  17307. }
  17308. };
  17309. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17310. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17311. };
  17312. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17313. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17314. };
  17315. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17316. if (!this.subMeshes) {
  17317. return;
  17318. }
  17319. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17320. var subMesh = _a[_i];
  17321. var material = subMesh.getMaterial();
  17322. if (material) {
  17323. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17324. }
  17325. }
  17326. };
  17327. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17328. /**
  17329. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17330. * Default : (1.0, 1.0, 1.0)
  17331. */
  17332. get: function () {
  17333. return this._scaling;
  17334. },
  17335. /**
  17336. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17337. * Default : (1.0, 1.0, 1.0)
  17338. */
  17339. set: function (newScaling) {
  17340. this._scaling = newScaling;
  17341. if (this.physicsImpostor) {
  17342. this.physicsImpostor.forceUpdate();
  17343. }
  17344. },
  17345. enumerable: true,
  17346. configurable: true
  17347. });
  17348. // Methods
  17349. /**
  17350. * Disables the mesh edger rendering mode.
  17351. * Returns the AbstractMesh.
  17352. */
  17353. AbstractMesh.prototype.disableEdgesRendering = function () {
  17354. if (this._edgesRenderer) {
  17355. this._edgesRenderer.dispose();
  17356. this._edgesRenderer = null;
  17357. }
  17358. return this;
  17359. };
  17360. /**
  17361. * Enables the edge rendering mode on the mesh.
  17362. * This mode makes the mesh edges visible.
  17363. * Returns the AbstractMesh.
  17364. */
  17365. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17366. if (epsilon === void 0) { epsilon = 0.95; }
  17367. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17368. this.disableEdgesRendering();
  17369. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17370. return this;
  17371. };
  17372. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17373. /**
  17374. * Returns true if the mesh is blocked. Used by the class Mesh.
  17375. * Returns the boolean `false` by default.
  17376. */
  17377. get: function () {
  17378. return false;
  17379. },
  17380. enumerable: true,
  17381. configurable: true
  17382. });
  17383. /**
  17384. * Returns the mesh itself by default, used by the class Mesh.
  17385. * Returned type : AbstractMesh
  17386. */
  17387. AbstractMesh.prototype.getLOD = function (camera) {
  17388. return this;
  17389. };
  17390. /**
  17391. * Returns 0 by default, used by the class Mesh.
  17392. * Returns an integer.
  17393. */
  17394. AbstractMesh.prototype.getTotalVertices = function () {
  17395. return 0;
  17396. };
  17397. /**
  17398. * Returns null by default, used by the class Mesh.
  17399. * Returned type : integer array
  17400. */
  17401. AbstractMesh.prototype.getIndices = function () {
  17402. return null;
  17403. };
  17404. /**
  17405. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17406. * Returned type : float array or Float32Array
  17407. */
  17408. AbstractMesh.prototype.getVerticesData = function (kind) {
  17409. return null;
  17410. };
  17411. /**
  17412. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17413. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17414. * The `data` are either a numeric array either a Float32Array.
  17415. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17416. * 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).
  17417. * Note that a new underlying VertexBuffer object is created each call.
  17418. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17419. *
  17420. * Possible `kind` values :
  17421. * - BABYLON.VertexBuffer.PositionKind
  17422. * - BABYLON.VertexBuffer.UVKind
  17423. * - BABYLON.VertexBuffer.UV2Kind
  17424. * - BABYLON.VertexBuffer.UV3Kind
  17425. * - BABYLON.VertexBuffer.UV4Kind
  17426. * - BABYLON.VertexBuffer.UV5Kind
  17427. * - BABYLON.VertexBuffer.UV6Kind
  17428. * - BABYLON.VertexBuffer.ColorKind
  17429. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17430. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17431. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17432. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17433. *
  17434. * Returns the Mesh.
  17435. */
  17436. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17437. return this;
  17438. };
  17439. /**
  17440. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17441. * If the mesh has no geometry, it is simply returned as it is.
  17442. * The `data` are either a numeric array either a Float32Array.
  17443. * No new underlying VertexBuffer object is created.
  17444. * 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.
  17445. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17446. *
  17447. * Possible `kind` values :
  17448. * - BABYLON.VertexBuffer.PositionKind
  17449. * - BABYLON.VertexBuffer.UVKind
  17450. * - BABYLON.VertexBuffer.UV2Kind
  17451. * - BABYLON.VertexBuffer.UV3Kind
  17452. * - BABYLON.VertexBuffer.UV4Kind
  17453. * - BABYLON.VertexBuffer.UV5Kind
  17454. * - BABYLON.VertexBuffer.UV6Kind
  17455. * - BABYLON.VertexBuffer.ColorKind
  17456. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17457. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17458. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17459. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17460. *
  17461. * Returns the Mesh.
  17462. */
  17463. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17464. return this;
  17465. };
  17466. /**
  17467. * Sets the mesh indices.
  17468. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17469. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17470. * This method creates a new index buffer each call.
  17471. * Returns the Mesh.
  17472. */
  17473. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17474. return this;
  17475. };
  17476. /** Returns false by default, used by the class Mesh.
  17477. * Returns a boolean
  17478. */
  17479. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17480. return false;
  17481. };
  17482. /**
  17483. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17484. * Returns a BoundingInfo
  17485. */
  17486. AbstractMesh.prototype.getBoundingInfo = function () {
  17487. if (this._masterMesh) {
  17488. return this._masterMesh.getBoundingInfo();
  17489. }
  17490. if (!this._boundingInfo) {
  17491. // this._boundingInfo is being created here
  17492. this._updateBoundingInfo();
  17493. }
  17494. // cannot be null.
  17495. return this._boundingInfo;
  17496. };
  17497. /**
  17498. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17499. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17500. */
  17501. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17502. if (includeDescendants === void 0) { includeDescendants = true; }
  17503. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17504. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17505. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17506. if (maxDimension === 0) {
  17507. return this;
  17508. }
  17509. var scale = 1 / maxDimension;
  17510. this.scaling.scaleInPlace(scale);
  17511. return this;
  17512. };
  17513. /**
  17514. * Sets a mesh new object BoundingInfo.
  17515. * Returns the AbstractMesh.
  17516. */
  17517. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17518. this._boundingInfo = boundingInfo;
  17519. return this;
  17520. };
  17521. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17522. get: function () {
  17523. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17524. },
  17525. enumerable: true,
  17526. configurable: true
  17527. });
  17528. AbstractMesh.prototype._preActivate = function () {
  17529. };
  17530. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17531. };
  17532. AbstractMesh.prototype._activate = function (renderId) {
  17533. this._renderId = renderId;
  17534. };
  17535. /**
  17536. * Returns the latest update of the World matrix
  17537. * Returns a Matrix.
  17538. */
  17539. AbstractMesh.prototype.getWorldMatrix = function () {
  17540. if (this._masterMesh) {
  17541. return this._masterMesh.getWorldMatrix();
  17542. }
  17543. return _super.prototype.getWorldMatrix.call(this);
  17544. };
  17545. /**
  17546. * Returns the latest update of the World matrix determinant.
  17547. */
  17548. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17549. if (this._masterMesh) {
  17550. return this._masterMesh._getWorldMatrixDeterminant();
  17551. }
  17552. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17553. };
  17554. // ================================== Point of View Movement =================================
  17555. /**
  17556. * Perform relative position change from the point of view of behind the front of the mesh.
  17557. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17558. * Supports definition of mesh facing forward or backward.
  17559. * @param {number} amountRight
  17560. * @param {number} amountUp
  17561. * @param {number} amountForward
  17562. *
  17563. * Returns the AbstractMesh.
  17564. */
  17565. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17566. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17567. return this;
  17568. };
  17569. /**
  17570. * Calculate relative position change from the point of view of behind the front of the mesh.
  17571. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17572. * Supports definition of mesh facing forward or backward.
  17573. * @param {number} amountRight
  17574. * @param {number} amountUp
  17575. * @param {number} amountForward
  17576. *
  17577. * Returns a new Vector3.
  17578. */
  17579. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17580. var rotMatrix = new BABYLON.Matrix();
  17581. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17582. rotQuaternion.toRotationMatrix(rotMatrix);
  17583. var translationDelta = BABYLON.Vector3.Zero();
  17584. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17585. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17586. return translationDelta;
  17587. };
  17588. // ================================== Point of View Rotation =================================
  17589. /**
  17590. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17591. * Supports definition of mesh facing forward or backward.
  17592. * @param {number} flipBack
  17593. * @param {number} twirlClockwise
  17594. * @param {number} tiltRight
  17595. *
  17596. * Returns the AbstractMesh.
  17597. */
  17598. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17599. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17600. return this;
  17601. };
  17602. /**
  17603. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17604. * Supports definition of mesh facing forward or backward.
  17605. * @param {number} flipBack
  17606. * @param {number} twirlClockwise
  17607. * @param {number} tiltRight
  17608. *
  17609. * Returns a new Vector3.
  17610. */
  17611. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17612. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17613. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17614. };
  17615. /**
  17616. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17617. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17618. */
  17619. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17620. if (includeDescendants === void 0) { includeDescendants = true; }
  17621. this.computeWorldMatrix(true);
  17622. var min;
  17623. var max;
  17624. var boundingInfo = this.getBoundingInfo();
  17625. if (!this.subMeshes) {
  17626. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17627. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17628. }
  17629. else {
  17630. min = boundingInfo.boundingBox.minimumWorld;
  17631. max = boundingInfo.boundingBox.maximumWorld;
  17632. }
  17633. if (includeDescendants) {
  17634. var descendants = this.getDescendants(false);
  17635. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  17636. var descendant = descendants_1[_i];
  17637. var childMesh = descendant;
  17638. childMesh.computeWorldMatrix(true);
  17639. //make sure we have the needed params to get mix and max
  17640. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  17641. continue;
  17642. }
  17643. var childBoundingInfo = childMesh.getBoundingInfo();
  17644. var boundingBox = childBoundingInfo.boundingBox;
  17645. var minBox = boundingBox.minimumWorld;
  17646. var maxBox = boundingBox.maximumWorld;
  17647. BABYLON.Tools.CheckExtends(minBox, min, max);
  17648. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17649. }
  17650. }
  17651. return {
  17652. min: min,
  17653. max: max
  17654. };
  17655. };
  17656. /**
  17657. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  17658. * Returns the AbstractMesh.
  17659. */
  17660. AbstractMesh.prototype._updateBoundingInfo = function () {
  17661. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  17662. this._boundingInfo.update(this.worldMatrixFromCache);
  17663. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17664. return this;
  17665. };
  17666. /**
  17667. * Update a mesh's children BoundingInfo objects only.
  17668. * Returns the AbstractMesh.
  17669. */
  17670. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  17671. if (!this.subMeshes) {
  17672. return this;
  17673. }
  17674. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  17675. var subMesh = this.subMeshes[subIndex];
  17676. if (!subMesh.IsGlobal) {
  17677. subMesh.updateBoundingInfo(matrix);
  17678. }
  17679. }
  17680. return this;
  17681. };
  17682. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  17683. // Bounding info
  17684. this._updateBoundingInfo();
  17685. };
  17686. /**
  17687. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  17688. * A mesh is in the frustum if its bounding box intersects the frustum.
  17689. * Boolean returned.
  17690. */
  17691. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  17692. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  17693. };
  17694. /**
  17695. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  17696. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  17697. * Boolean returned.
  17698. */
  17699. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17700. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  17701. ;
  17702. };
  17703. /**
  17704. * True if the mesh intersects another mesh or a SolidParticle object.
  17705. * 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)
  17706. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  17707. * Returns a boolean.
  17708. */
  17709. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  17710. if (precise === void 0) { precise = false; }
  17711. if (!this._boundingInfo || !mesh._boundingInfo) {
  17712. return false;
  17713. }
  17714. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  17715. return true;
  17716. }
  17717. if (includeDescendants) {
  17718. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  17719. var child = _a[_i];
  17720. if (child.intersectsMesh(mesh, precise, true)) {
  17721. return true;
  17722. }
  17723. }
  17724. }
  17725. return false;
  17726. };
  17727. /**
  17728. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  17729. * Returns a boolean.
  17730. */
  17731. AbstractMesh.prototype.intersectsPoint = function (point) {
  17732. if (!this._boundingInfo) {
  17733. return false;
  17734. }
  17735. return this._boundingInfo.intersectsPoint(point);
  17736. };
  17737. AbstractMesh.prototype.getPhysicsImpostor = function () {
  17738. return this.physicsImpostor;
  17739. };
  17740. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  17741. if (camera === void 0) { camera = null; }
  17742. if (!camera) {
  17743. camera = this.getScene().activeCamera;
  17744. }
  17745. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  17746. };
  17747. /**
  17748. * Returns the distance from the mesh to the active camera.
  17749. * Returns a float.
  17750. */
  17751. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  17752. if (camera === void 0) { camera = null; }
  17753. if (!camera) {
  17754. camera = this.getScene().activeCamera;
  17755. }
  17756. return this.absolutePosition.subtract(camera.position).length();
  17757. };
  17758. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  17759. if (!this.physicsImpostor) {
  17760. return this;
  17761. }
  17762. this.physicsImpostor.applyImpulse(force, contactPoint);
  17763. return this;
  17764. };
  17765. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  17766. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  17767. return this;
  17768. }
  17769. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  17770. mainPivot: pivot1,
  17771. connectedPivot: pivot2,
  17772. nativeParams: options
  17773. });
  17774. return this;
  17775. };
  17776. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  17777. // Collisions
  17778. /**
  17779. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  17780. * Default `false`.
  17781. */
  17782. get: function () {
  17783. return this._checkCollisions;
  17784. },
  17785. set: function (collisionEnabled) {
  17786. this._checkCollisions = collisionEnabled;
  17787. if (this.getScene().workerCollisions) {
  17788. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17789. }
  17790. },
  17791. enumerable: true,
  17792. configurable: true
  17793. });
  17794. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17795. /**
  17796. * Gets Collider object used to compute collisions (not physics)
  17797. */
  17798. get: function () {
  17799. return this._collider;
  17800. },
  17801. enumerable: true,
  17802. configurable: true
  17803. });
  17804. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17805. var globalPosition = this.getAbsolutePosition();
  17806. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17807. if (!this._collider) {
  17808. this._collider = new BABYLON.Collider();
  17809. }
  17810. this._collider._radius = this.ellipsoid;
  17811. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17812. return this;
  17813. };
  17814. // Submeshes octree
  17815. /**
  17816. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17817. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17818. * Returns an Octree of submeshes.
  17819. */
  17820. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17821. if (maxCapacity === void 0) { maxCapacity = 64; }
  17822. if (maxDepth === void 0) { maxDepth = 2; }
  17823. if (!this._submeshesOctree) {
  17824. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17825. }
  17826. this.computeWorldMatrix(true);
  17827. var boundingInfo = this.getBoundingInfo();
  17828. // Update octree
  17829. var bbox = boundingInfo.boundingBox;
  17830. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17831. return this._submeshesOctree;
  17832. };
  17833. // Collisions
  17834. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17835. this._generatePointsArray();
  17836. if (!this._positions) {
  17837. return this;
  17838. }
  17839. // Transformation
  17840. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17841. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17842. subMesh._lastColliderWorldVertices = [];
  17843. subMesh._trianglePlanes = [];
  17844. var start = subMesh.verticesStart;
  17845. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17846. for (var i = start; i < end; i++) {
  17847. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17848. }
  17849. }
  17850. // Collide
  17851. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17852. if (collider.collisionFound) {
  17853. collider.collidedMesh = this;
  17854. }
  17855. return this;
  17856. };
  17857. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17858. var subMeshes;
  17859. var len;
  17860. // Octrees
  17861. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17862. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17863. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17864. len = intersections.length;
  17865. subMeshes = intersections.data;
  17866. }
  17867. else {
  17868. subMeshes = this.subMeshes;
  17869. len = subMeshes.length;
  17870. }
  17871. for (var index = 0; index < len; index++) {
  17872. var subMesh = subMeshes[index];
  17873. // Bounding test
  17874. if (len > 1 && !subMesh._checkCollision(collider))
  17875. continue;
  17876. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17877. }
  17878. return this;
  17879. };
  17880. AbstractMesh.prototype._checkCollision = function (collider) {
  17881. // Bounding box test
  17882. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17883. return this;
  17884. // Transformation matrix
  17885. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17886. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  17887. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  17888. return this;
  17889. };
  17890. // Picking
  17891. AbstractMesh.prototype._generatePointsArray = function () {
  17892. return false;
  17893. };
  17894. /**
  17895. * Checks if the passed Ray intersects with the mesh.
  17896. * Returns an object PickingInfo.
  17897. */
  17898. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17899. var pickingInfo = new BABYLON.PickingInfo();
  17900. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  17901. return pickingInfo;
  17902. }
  17903. if (!this._generatePointsArray()) {
  17904. return pickingInfo;
  17905. }
  17906. var intersectInfo = null;
  17907. // Octrees
  17908. var subMeshes;
  17909. var len;
  17910. if (this._submeshesOctree && this.useOctreeForPicking) {
  17911. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  17912. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  17913. len = intersections.length;
  17914. subMeshes = intersections.data;
  17915. }
  17916. else {
  17917. subMeshes = this.subMeshes;
  17918. len = subMeshes.length;
  17919. }
  17920. for (var index = 0; index < len; index++) {
  17921. var subMesh = subMeshes[index];
  17922. // Bounding test
  17923. if (len > 1 && !subMesh.canIntersects(ray))
  17924. continue;
  17925. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17926. if (currentIntersectInfo) {
  17927. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17928. intersectInfo = currentIntersectInfo;
  17929. intersectInfo.subMeshId = index;
  17930. if (fastCheck) {
  17931. break;
  17932. }
  17933. }
  17934. }
  17935. }
  17936. if (intersectInfo) {
  17937. // Get picked point
  17938. var world = this.getWorldMatrix();
  17939. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17940. var direction = ray.direction.clone();
  17941. direction = direction.scale(intersectInfo.distance);
  17942. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17943. var pickedPoint = worldOrigin.add(worldDirection);
  17944. // Return result
  17945. pickingInfo.hit = true;
  17946. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17947. pickingInfo.pickedPoint = pickedPoint;
  17948. pickingInfo.pickedMesh = this;
  17949. pickingInfo.bu = intersectInfo.bu || 0;
  17950. pickingInfo.bv = intersectInfo.bv || 0;
  17951. pickingInfo.faceId = intersectInfo.faceId;
  17952. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17953. return pickingInfo;
  17954. }
  17955. return pickingInfo;
  17956. };
  17957. /**
  17958. * Clones the mesh, used by the class Mesh.
  17959. * Just returns `null` for an AbstractMesh.
  17960. */
  17961. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17962. return null;
  17963. };
  17964. /**
  17965. * Disposes all the mesh submeshes.
  17966. * Returns the AbstractMesh.
  17967. */
  17968. AbstractMesh.prototype.releaseSubMeshes = function () {
  17969. if (this.subMeshes) {
  17970. while (this.subMeshes.length) {
  17971. this.subMeshes[0].dispose();
  17972. }
  17973. }
  17974. else {
  17975. this.subMeshes = new Array();
  17976. }
  17977. return this;
  17978. };
  17979. /**
  17980. * Disposes the AbstractMesh.
  17981. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17982. * Returns nothing.
  17983. */
  17984. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17985. var _this = this;
  17986. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17987. var index;
  17988. // Action manager
  17989. if (this.actionManager !== undefined && this.actionManager !== null) {
  17990. this.actionManager.dispose();
  17991. this.actionManager = null;
  17992. }
  17993. // Skeleton
  17994. this.skeleton = null;
  17995. // Physics
  17996. if (this.physicsImpostor) {
  17997. this.physicsImpostor.dispose();
  17998. }
  17999. // Intersections in progress
  18000. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18001. var other = this._intersectionsInProgress[index];
  18002. var pos = other._intersectionsInProgress.indexOf(this);
  18003. other._intersectionsInProgress.splice(pos, 1);
  18004. }
  18005. this._intersectionsInProgress = [];
  18006. // Lights
  18007. var lights = this.getScene().lights;
  18008. lights.forEach(function (light) {
  18009. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18010. if (meshIndex !== -1) {
  18011. light.includedOnlyMeshes.splice(meshIndex, 1);
  18012. }
  18013. meshIndex = light.excludedMeshes.indexOf(_this);
  18014. if (meshIndex !== -1) {
  18015. light.excludedMeshes.splice(meshIndex, 1);
  18016. }
  18017. // Shadow generators
  18018. var generator = light.getShadowGenerator();
  18019. if (generator) {
  18020. var shadowMap = generator.getShadowMap();
  18021. if (shadowMap && shadowMap.renderList) {
  18022. meshIndex = shadowMap.renderList.indexOf(_this);
  18023. if (meshIndex !== -1) {
  18024. shadowMap.renderList.splice(meshIndex, 1);
  18025. }
  18026. }
  18027. }
  18028. });
  18029. // Edges
  18030. if (this._edgesRenderer) {
  18031. this._edgesRenderer.dispose();
  18032. this._edgesRenderer = null;
  18033. }
  18034. // SubMeshes
  18035. if (this.getClassName() !== "InstancedMesh") {
  18036. this.releaseSubMeshes();
  18037. }
  18038. // Octree
  18039. var sceneOctree = this.getScene().selectionOctree;
  18040. if (sceneOctree !== undefined && sceneOctree !== null) {
  18041. var index = sceneOctree.dynamicContent.indexOf(this);
  18042. if (index !== -1) {
  18043. sceneOctree.dynamicContent.splice(index, 1);
  18044. }
  18045. }
  18046. // Query
  18047. var engine = this.getScene().getEngine();
  18048. if (this._occlusionQuery) {
  18049. this._isOcclusionQueryInProgress = false;
  18050. engine.deleteQuery(this._occlusionQuery);
  18051. this._occlusionQuery = null;
  18052. }
  18053. // Engine
  18054. engine.wipeCaches();
  18055. // Remove from scene
  18056. this.getScene().removeMesh(this);
  18057. if (disposeMaterialAndTextures) {
  18058. if (this.material) {
  18059. this.material.dispose(false, true);
  18060. }
  18061. }
  18062. if (!doNotRecurse) {
  18063. // Particles
  18064. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18065. if (this.getScene().particleSystems[index].emitter === this) {
  18066. this.getScene().particleSystems[index].dispose();
  18067. index--;
  18068. }
  18069. }
  18070. }
  18071. // facet data
  18072. if (this._facetDataEnabled) {
  18073. this.disableFacetData();
  18074. }
  18075. this.onAfterWorldMatrixUpdateObservable.clear();
  18076. this.onCollideObservable.clear();
  18077. this.onCollisionPositionChangeObservable.clear();
  18078. _super.prototype.dispose.call(this, doNotRecurse);
  18079. };
  18080. /**
  18081. * Adds the passed mesh as a child to the current mesh.
  18082. * Returns the AbstractMesh.
  18083. */
  18084. AbstractMesh.prototype.addChild = function (mesh) {
  18085. mesh.setParent(this);
  18086. return this;
  18087. };
  18088. /**
  18089. * Removes the passed mesh from the current mesh children list.
  18090. * Returns the AbstractMesh.
  18091. */
  18092. AbstractMesh.prototype.removeChild = function (mesh) {
  18093. mesh.setParent(null);
  18094. return this;
  18095. };
  18096. // Facet data
  18097. /**
  18098. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18099. * Returns the AbstractMesh.
  18100. */
  18101. AbstractMesh.prototype._initFacetData = function () {
  18102. if (!this._facetNormals) {
  18103. this._facetNormals = new Array();
  18104. }
  18105. if (!this._facetPositions) {
  18106. this._facetPositions = new Array();
  18107. }
  18108. if (!this._facetPartitioning) {
  18109. this._facetPartitioning = new Array();
  18110. }
  18111. this._facetNb = (this.getIndices().length / 3) | 0;
  18112. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18113. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18114. for (var f = 0; f < this._facetNb; f++) {
  18115. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18116. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18117. }
  18118. this._facetDataEnabled = true;
  18119. return this;
  18120. };
  18121. /**
  18122. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18123. * This method can be called within the render loop.
  18124. * 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.
  18125. * Returns the AbstractMesh.
  18126. */
  18127. AbstractMesh.prototype.updateFacetData = function () {
  18128. if (!this._facetDataEnabled) {
  18129. this._initFacetData();
  18130. }
  18131. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18132. var indices = this.getIndices();
  18133. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18134. var bInfo = this.getBoundingInfo();
  18135. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18136. // init arrays, matrix and sort function on first call
  18137. this._facetDepthSortEnabled = true;
  18138. if (indices instanceof Uint16Array) {
  18139. this._depthSortedIndices = new Uint16Array(indices);
  18140. }
  18141. else if (indices instanceof Uint32Array) {
  18142. this._depthSortedIndices = new Uint32Array(indices);
  18143. }
  18144. else {
  18145. var needs32bits = false;
  18146. for (var i = 0; i < indices.length; i++) {
  18147. if (indices[i] > 65535) {
  18148. needs32bits = true;
  18149. break;
  18150. }
  18151. }
  18152. if (needs32bits) {
  18153. this._depthSortedIndices = new Uint32Array(indices);
  18154. }
  18155. else {
  18156. this._depthSortedIndices = new Uint16Array(indices);
  18157. }
  18158. }
  18159. this._facetDepthSortFunction = function (f1, f2) {
  18160. return (f2.sqDistance - f1.sqDistance);
  18161. };
  18162. if (!this._facetDepthSortFrom) {
  18163. var camera = this.getScene().activeCamera;
  18164. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18165. }
  18166. this._depthSortedFacets = [];
  18167. for (var f = 0; f < this._facetNb; f++) {
  18168. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18169. this._depthSortedFacets.push(depthSortedFacet);
  18170. }
  18171. this._invertedMatrix = BABYLON.Matrix.Identity();
  18172. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18173. }
  18174. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18175. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18176. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18177. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18178. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18179. this._subDiv.max = this._partitioningSubdivisions;
  18180. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18181. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18182. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18183. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18184. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18185. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18186. // set the parameters for ComputeNormals()
  18187. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18188. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18189. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18190. this._facetParameters.bInfo = bInfo;
  18191. this._facetParameters.bbSize = this._bbSize;
  18192. this._facetParameters.subDiv = this._subDiv;
  18193. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18194. this._facetParameters.depthSort = this._facetDepthSort;
  18195. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18196. this.computeWorldMatrix(true);
  18197. this._worldMatrix.invertToRef(this._invertedMatrix);
  18198. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18199. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18200. }
  18201. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18202. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18203. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18204. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18205. var l = (this._depthSortedIndices.length / 3) | 0;
  18206. for (var f = 0; f < l; f++) {
  18207. var sind = this._depthSortedFacets[f].ind;
  18208. this._depthSortedIndices[f * 3] = indices[sind];
  18209. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18210. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18211. }
  18212. this.updateIndices(this._depthSortedIndices);
  18213. }
  18214. return this;
  18215. };
  18216. /**
  18217. * Returns the facetLocalNormals array.
  18218. * The normals are expressed in the mesh local space.
  18219. */
  18220. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18221. if (!this._facetNormals) {
  18222. this.updateFacetData();
  18223. }
  18224. return this._facetNormals;
  18225. };
  18226. /**
  18227. * Returns the facetLocalPositions array.
  18228. * The facet positions are expressed in the mesh local space.
  18229. */
  18230. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18231. if (!this._facetPositions) {
  18232. this.updateFacetData();
  18233. }
  18234. return this._facetPositions;
  18235. };
  18236. /**
  18237. * Returns the facetLocalPartioning array.
  18238. */
  18239. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18240. if (!this._facetPartitioning) {
  18241. this.updateFacetData();
  18242. }
  18243. return this._facetPartitioning;
  18244. };
  18245. /**
  18246. * Returns the i-th facet position in the world system.
  18247. * This method allocates a new Vector3 per call.
  18248. */
  18249. AbstractMesh.prototype.getFacetPosition = function (i) {
  18250. var pos = BABYLON.Vector3.Zero();
  18251. this.getFacetPositionToRef(i, pos);
  18252. return pos;
  18253. };
  18254. /**
  18255. * Sets the reference Vector3 with the i-th facet position in the world system.
  18256. * Returns the AbstractMesh.
  18257. */
  18258. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18259. var localPos = (this.getFacetLocalPositions())[i];
  18260. var world = this.getWorldMatrix();
  18261. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18262. return this;
  18263. };
  18264. /**
  18265. * Returns the i-th facet normal in the world system.
  18266. * This method allocates a new Vector3 per call.
  18267. */
  18268. AbstractMesh.prototype.getFacetNormal = function (i) {
  18269. var norm = BABYLON.Vector3.Zero();
  18270. this.getFacetNormalToRef(i, norm);
  18271. return norm;
  18272. };
  18273. /**
  18274. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18275. * Returns the AbstractMesh.
  18276. */
  18277. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18278. var localNorm = (this.getFacetLocalNormals())[i];
  18279. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18280. return this;
  18281. };
  18282. /**
  18283. * 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).
  18284. */
  18285. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18286. var bInfo = this.getBoundingInfo();
  18287. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18288. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18289. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18290. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18291. return null;
  18292. }
  18293. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18294. };
  18295. /**
  18296. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18297. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18298. * 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.
  18299. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18300. * 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.
  18301. */
  18302. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18303. if (checkFace === void 0) { checkFace = false; }
  18304. if (facing === void 0) { facing = true; }
  18305. var world = this.getWorldMatrix();
  18306. var invMat = BABYLON.Tmp.Matrix[5];
  18307. world.invertToRef(invMat);
  18308. var invVect = BABYLON.Tmp.Vector3[8];
  18309. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18310. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18311. if (projected) {
  18312. // tranform the local computed projected vector to world coordinates
  18313. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18314. }
  18315. return closest;
  18316. };
  18317. /**
  18318. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18319. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18320. * 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.
  18321. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18322. * 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.
  18323. */
  18324. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18325. if (checkFace === void 0) { checkFace = false; }
  18326. if (facing === void 0) { facing = true; }
  18327. var closest = null;
  18328. var tmpx = 0.0;
  18329. var tmpy = 0.0;
  18330. var tmpz = 0.0;
  18331. var d = 0.0; // tmp dot facet normal * facet position
  18332. var t0 = 0.0;
  18333. var projx = 0.0;
  18334. var projy = 0.0;
  18335. var projz = 0.0;
  18336. // Get all the facets in the same partitioning block than (x, y, z)
  18337. var facetPositions = this.getFacetLocalPositions();
  18338. var facetNormals = this.getFacetLocalNormals();
  18339. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18340. if (!facetsInBlock) {
  18341. return null;
  18342. }
  18343. // Get the closest facet to (x, y, z)
  18344. var shortest = Number.MAX_VALUE; // init distance vars
  18345. var tmpDistance = shortest;
  18346. var fib; // current facet in the block
  18347. var norm; // current facet normal
  18348. var p0; // current facet barycenter position
  18349. // loop on all the facets in the current partitioning block
  18350. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18351. fib = facetsInBlock[idx];
  18352. norm = facetNormals[fib];
  18353. p0 = facetPositions[fib];
  18354. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18355. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18356. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18357. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18358. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18359. projx = x + norm.x * t0;
  18360. projy = y + norm.y * t0;
  18361. projz = z + norm.z * t0;
  18362. tmpx = projx - x;
  18363. tmpy = projy - y;
  18364. tmpz = projz - z;
  18365. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18366. if (tmpDistance < shortest) {
  18367. shortest = tmpDistance;
  18368. closest = fib;
  18369. if (projected) {
  18370. projected.x = projx;
  18371. projected.y = projy;
  18372. projected.z = projz;
  18373. }
  18374. }
  18375. }
  18376. }
  18377. return closest;
  18378. };
  18379. /**
  18380. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18381. */
  18382. AbstractMesh.prototype.getFacetDataParameters = function () {
  18383. return this._facetParameters;
  18384. };
  18385. /**
  18386. * Disables the feature FacetData and frees the related memory.
  18387. * Returns the AbstractMesh.
  18388. */
  18389. AbstractMesh.prototype.disableFacetData = function () {
  18390. if (this._facetDataEnabled) {
  18391. this._facetDataEnabled = false;
  18392. this._facetPositions = new Array();
  18393. this._facetNormals = new Array();
  18394. this._facetPartitioning = new Array();
  18395. this._facetParameters = null;
  18396. this._depthSortedIndices = new Uint32Array(0);
  18397. }
  18398. return this;
  18399. };
  18400. /**
  18401. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18402. * Returns the mesh.
  18403. */
  18404. AbstractMesh.prototype.updateIndices = function (indices) {
  18405. return this;
  18406. };
  18407. /**
  18408. * The mesh Geometry. Actually used by the Mesh object.
  18409. * Returns a blank geometry object.
  18410. */
  18411. /**
  18412. * Creates new normals data for the mesh.
  18413. * @param updatable.
  18414. */
  18415. AbstractMesh.prototype.createNormals = function (updatable) {
  18416. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18417. var indices = this.getIndices();
  18418. var normals;
  18419. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18420. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18421. }
  18422. else {
  18423. normals = [];
  18424. }
  18425. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18426. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18427. };
  18428. /**
  18429. * Align the mesh with a normal.
  18430. * Returns the mesh.
  18431. */
  18432. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18433. if (!upDirection) {
  18434. upDirection = BABYLON.Axis.Y;
  18435. }
  18436. var axisX = BABYLON.Tmp.Vector3[0];
  18437. var axisZ = BABYLON.Tmp.Vector3[1];
  18438. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18439. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18440. if (this.rotationQuaternion) {
  18441. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18442. }
  18443. else {
  18444. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18445. }
  18446. return this;
  18447. };
  18448. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18449. var engine = this.getEngine();
  18450. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18451. this._isOccluded = false;
  18452. return;
  18453. }
  18454. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18455. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18456. if (isOcclusionQueryAvailable) {
  18457. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18458. this._isOcclusionQueryInProgress = false;
  18459. this._occlusionInternalRetryCounter = 0;
  18460. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18461. }
  18462. else {
  18463. this._occlusionInternalRetryCounter++;
  18464. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18465. this._isOcclusionQueryInProgress = false;
  18466. this._occlusionInternalRetryCounter = 0;
  18467. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18468. // if strict continue the last state of the object.
  18469. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18470. }
  18471. else {
  18472. return;
  18473. }
  18474. }
  18475. }
  18476. var scene = this.getScene();
  18477. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18478. if (!this._occlusionQuery) {
  18479. this._occlusionQuery = engine.createQuery();
  18480. }
  18481. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18482. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18483. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18484. this._isOcclusionQueryInProgress = true;
  18485. };
  18486. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18487. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18488. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18489. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18490. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18491. return AbstractMesh;
  18492. }(BABYLON.TransformNode));
  18493. BABYLON.AbstractMesh = AbstractMesh;
  18494. })(BABYLON || (BABYLON = {}));
  18495. //# sourceMappingURL=babylon.abstractMesh.js.map
  18496. var BABYLON;
  18497. (function (BABYLON) {
  18498. /**
  18499. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18500. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18501. * 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.
  18502. */
  18503. var Light = /** @class */ (function (_super) {
  18504. __extends(Light, _super);
  18505. /**
  18506. * Creates a Light object in the scene.
  18507. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18508. * @param name The firendly name of the light
  18509. * @param scene The scene the light belongs too
  18510. */
  18511. function Light(name, scene) {
  18512. var _this = _super.call(this, name, scene) || this;
  18513. /**
  18514. * Diffuse gives the basic color to an object.
  18515. */
  18516. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18517. /**
  18518. * Specular produces a highlight color on an object.
  18519. * Note: This is note affecting PBR materials.
  18520. */
  18521. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18522. /**
  18523. * Strength of the light.
  18524. * Note: By default it is define in the framework own unit.
  18525. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18526. */
  18527. _this.intensity = 1.0;
  18528. /**
  18529. * Defines how far from the source the light is impacting in scene units.
  18530. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18531. */
  18532. _this.range = Number.MAX_VALUE;
  18533. /**
  18534. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18535. * of light.
  18536. */
  18537. _this._photometricScale = 1.0;
  18538. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18539. _this._radius = 0.00001;
  18540. /**
  18541. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18542. * exceeding the number allowed of the materials.
  18543. */
  18544. _this.renderPriority = 0;
  18545. /**
  18546. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18547. * the current shadow generator.
  18548. */
  18549. _this.shadowEnabled = true;
  18550. _this._excludeWithLayerMask = 0;
  18551. _this._includeOnlyWithLayerMask = 0;
  18552. _this._lightmapMode = 0;
  18553. /**
  18554. * @ignore Internal use only.
  18555. */
  18556. _this._excludedMeshesIds = new Array();
  18557. /**
  18558. * @ignore Internal use only.
  18559. */
  18560. _this._includedOnlyMeshesIds = new Array();
  18561. _this.getScene().addLight(_this);
  18562. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18563. _this._buildUniformLayout();
  18564. _this.includedOnlyMeshes = new Array();
  18565. _this.excludedMeshes = new Array();
  18566. _this._resyncMeshes();
  18567. return _this;
  18568. }
  18569. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18570. /**
  18571. * If every light affecting the material is in this lightmapMode,
  18572. * material.lightmapTexture adds or multiplies
  18573. * (depends on material.useLightmapAsShadowmap)
  18574. * after every other light calculations.
  18575. */
  18576. get: function () {
  18577. return Light._LIGHTMAP_DEFAULT;
  18578. },
  18579. enumerable: true,
  18580. configurable: true
  18581. });
  18582. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18583. /**
  18584. * material.lightmapTexture as only diffuse lighting from this light
  18585. * adds only specular lighting from this light
  18586. * adds dynamic shadows
  18587. */
  18588. get: function () {
  18589. return Light._LIGHTMAP_SPECULAR;
  18590. },
  18591. enumerable: true,
  18592. configurable: true
  18593. });
  18594. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18595. /**
  18596. * material.lightmapTexture as only lighting
  18597. * no light calculation from this light
  18598. * only adds dynamic shadows from this light
  18599. */
  18600. get: function () {
  18601. return Light._LIGHTMAP_SHADOWSONLY;
  18602. },
  18603. enumerable: true,
  18604. configurable: true
  18605. });
  18606. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18607. /**
  18608. * Each light type uses the default quantity according to its type:
  18609. * point/spot lights use luminous intensity
  18610. * directional lights use illuminance
  18611. */
  18612. get: function () {
  18613. return Light._INTENSITYMODE_AUTOMATIC;
  18614. },
  18615. enumerable: true,
  18616. configurable: true
  18617. });
  18618. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18619. /**
  18620. * lumen (lm)
  18621. */
  18622. get: function () {
  18623. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18624. },
  18625. enumerable: true,
  18626. configurable: true
  18627. });
  18628. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18629. /**
  18630. * candela (lm/sr)
  18631. */
  18632. get: function () {
  18633. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  18634. },
  18635. enumerable: true,
  18636. configurable: true
  18637. });
  18638. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  18639. /**
  18640. * lux (lm/m^2)
  18641. */
  18642. get: function () {
  18643. return Light._INTENSITYMODE_ILLUMINANCE;
  18644. },
  18645. enumerable: true,
  18646. configurable: true
  18647. });
  18648. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  18649. /**
  18650. * nit (cd/m^2)
  18651. */
  18652. get: function () {
  18653. return Light._INTENSITYMODE_LUMINANCE;
  18654. },
  18655. enumerable: true,
  18656. configurable: true
  18657. });
  18658. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  18659. /**
  18660. * Light type const id of the point light.
  18661. */
  18662. get: function () {
  18663. return Light._LIGHTTYPEID_POINTLIGHT;
  18664. },
  18665. enumerable: true,
  18666. configurable: true
  18667. });
  18668. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  18669. /**
  18670. * Light type const id of the directional light.
  18671. */
  18672. get: function () {
  18673. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  18674. },
  18675. enumerable: true,
  18676. configurable: true
  18677. });
  18678. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  18679. /**
  18680. * Light type const id of the spot light.
  18681. */
  18682. get: function () {
  18683. return Light._LIGHTTYPEID_SPOTLIGHT;
  18684. },
  18685. enumerable: true,
  18686. configurable: true
  18687. });
  18688. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  18689. /**
  18690. * Light type const id of the hemispheric light.
  18691. */
  18692. get: function () {
  18693. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  18694. },
  18695. enumerable: true,
  18696. configurable: true
  18697. });
  18698. Object.defineProperty(Light.prototype, "intensityMode", {
  18699. /**
  18700. * Gets the photometric scale used to interpret the intensity.
  18701. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18702. */
  18703. get: function () {
  18704. return this._intensityMode;
  18705. },
  18706. /**
  18707. * Sets the photometric scale used to interpret the intensity.
  18708. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18709. */
  18710. set: function (value) {
  18711. this._intensityMode = value;
  18712. this._computePhotometricScale();
  18713. },
  18714. enumerable: true,
  18715. configurable: true
  18716. });
  18717. ;
  18718. ;
  18719. Object.defineProperty(Light.prototype, "radius", {
  18720. /**
  18721. * Gets the light radius used by PBR Materials to simulate soft area lights.
  18722. */
  18723. get: function () {
  18724. return this._radius;
  18725. },
  18726. /**
  18727. * sets the light radius used by PBR Materials to simulate soft area lights.
  18728. */
  18729. set: function (value) {
  18730. this._radius = value;
  18731. this._computePhotometricScale();
  18732. },
  18733. enumerable: true,
  18734. configurable: true
  18735. });
  18736. ;
  18737. ;
  18738. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  18739. /**
  18740. * Gets the only meshes impacted by this light.
  18741. */
  18742. get: function () {
  18743. return this._includedOnlyMeshes;
  18744. },
  18745. /**
  18746. * Sets the only meshes impacted by this light.
  18747. */
  18748. set: function (value) {
  18749. this._includedOnlyMeshes = value;
  18750. this._hookArrayForIncludedOnly(value);
  18751. },
  18752. enumerable: true,
  18753. configurable: true
  18754. });
  18755. Object.defineProperty(Light.prototype, "excludedMeshes", {
  18756. /**
  18757. * Gets the meshes not impacted by this light.
  18758. */
  18759. get: function () {
  18760. return this._excludedMeshes;
  18761. },
  18762. /**
  18763. * Sets the meshes not impacted by this light.
  18764. */
  18765. set: function (value) {
  18766. this._excludedMeshes = value;
  18767. this._hookArrayForExcluded(value);
  18768. },
  18769. enumerable: true,
  18770. configurable: true
  18771. });
  18772. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  18773. /**
  18774. * Gets the layer id use to find what meshes are not impacted by the light.
  18775. * Inactive if 0
  18776. */
  18777. get: function () {
  18778. return this._excludeWithLayerMask;
  18779. },
  18780. /**
  18781. * Sets the layer id use to find what meshes are not impacted by the light.
  18782. * Inactive if 0
  18783. */
  18784. set: function (value) {
  18785. this._excludeWithLayerMask = value;
  18786. this._resyncMeshes();
  18787. },
  18788. enumerable: true,
  18789. configurable: true
  18790. });
  18791. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18792. /**
  18793. * Gets the layer id use to find what meshes are impacted by the light.
  18794. * Inactive if 0
  18795. */
  18796. get: function () {
  18797. return this._includeOnlyWithLayerMask;
  18798. },
  18799. /**
  18800. * Sets the layer id use to find what meshes are impacted by the light.
  18801. * Inactive if 0
  18802. */
  18803. set: function (value) {
  18804. this._includeOnlyWithLayerMask = value;
  18805. this._resyncMeshes();
  18806. },
  18807. enumerable: true,
  18808. configurable: true
  18809. });
  18810. Object.defineProperty(Light.prototype, "lightmapMode", {
  18811. /**
  18812. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18813. */
  18814. get: function () {
  18815. return this._lightmapMode;
  18816. },
  18817. /**
  18818. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18819. */
  18820. set: function (value) {
  18821. if (this._lightmapMode === value) {
  18822. return;
  18823. }
  18824. this._lightmapMode = value;
  18825. this._markMeshesAsLightDirty();
  18826. },
  18827. enumerable: true,
  18828. configurable: true
  18829. });
  18830. /**
  18831. * Returns the string "Light".
  18832. * @returns the class name
  18833. */
  18834. Light.prototype.getClassName = function () {
  18835. return "Light";
  18836. };
  18837. /**
  18838. * Converts the light information to a readable string for debug purpose.
  18839. * @param fullDetails Supports for multiple levels of logging within scene loading
  18840. * @returns the human readable light info
  18841. */
  18842. Light.prototype.toString = function (fullDetails) {
  18843. var ret = "Name: " + this.name;
  18844. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18845. if (this.animations) {
  18846. for (var i = 0; i < this.animations.length; i++) {
  18847. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18848. }
  18849. }
  18850. if (fullDetails) {
  18851. }
  18852. return ret;
  18853. };
  18854. /**
  18855. * Set the enabled state of this node.
  18856. * @param value - the new enabled state
  18857. * @see isEnabled
  18858. */
  18859. Light.prototype.setEnabled = function (value) {
  18860. _super.prototype.setEnabled.call(this, value);
  18861. this._resyncMeshes();
  18862. };
  18863. /**
  18864. * Returns the Light associated shadow generator if any.
  18865. * @return the associated shadow generator.
  18866. */
  18867. Light.prototype.getShadowGenerator = function () {
  18868. return this._shadowGenerator;
  18869. };
  18870. /**
  18871. * Returns a Vector3, the absolute light position in the World.
  18872. * @returns the world space position of the light
  18873. */
  18874. Light.prototype.getAbsolutePosition = function () {
  18875. return BABYLON.Vector3.Zero();
  18876. };
  18877. /**
  18878. * Specifies if the light will affect the passed mesh.
  18879. * @param mesh The mesh to test against the light
  18880. * @return true the mesh is affected otherwise, false.
  18881. */
  18882. Light.prototype.canAffectMesh = function (mesh) {
  18883. if (!mesh) {
  18884. return true;
  18885. }
  18886. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  18887. return false;
  18888. }
  18889. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  18890. return false;
  18891. }
  18892. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  18893. return false;
  18894. }
  18895. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18896. return false;
  18897. }
  18898. return true;
  18899. };
  18900. /**
  18901. * Computes and Returns the light World matrix.
  18902. * @returns the world matrix
  18903. */
  18904. Light.prototype.getWorldMatrix = function () {
  18905. this._currentRenderId = this.getScene().getRenderId();
  18906. var worldMatrix = this._getWorldMatrix();
  18907. if (this.parent && this.parent.getWorldMatrix) {
  18908. if (!this._parentedWorldMatrix) {
  18909. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  18910. }
  18911. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  18912. this._markSyncedWithParent();
  18913. return this._parentedWorldMatrix;
  18914. }
  18915. return worldMatrix;
  18916. };
  18917. /**
  18918. * Sort function to order lights for rendering.
  18919. * @param a First Light object to compare to second.
  18920. * @param b Second Light object to compare first.
  18921. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  18922. */
  18923. Light.CompareLightsPriority = function (a, b) {
  18924. //shadow-casting lights have priority over non-shadow-casting lights
  18925. //the renderPrioirty is a secondary sort criterion
  18926. if (a.shadowEnabled !== b.shadowEnabled) {
  18927. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  18928. }
  18929. return b.renderPriority - a.renderPriority;
  18930. };
  18931. /**
  18932. * Disposes the light.
  18933. */
  18934. Light.prototype.dispose = function () {
  18935. if (this._shadowGenerator) {
  18936. this._shadowGenerator.dispose();
  18937. this._shadowGenerator = null;
  18938. }
  18939. // Animations
  18940. this.getScene().stopAnimation(this);
  18941. // Remove from meshes
  18942. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18943. var mesh = _a[_i];
  18944. mesh._removeLightSource(this);
  18945. }
  18946. this._uniformBuffer.dispose();
  18947. // Remove from scene
  18948. this.getScene().removeLight(this);
  18949. _super.prototype.dispose.call(this);
  18950. };
  18951. /**
  18952. * Returns the light type ID (integer).
  18953. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  18954. */
  18955. Light.prototype.getTypeID = function () {
  18956. return 0;
  18957. };
  18958. /**
  18959. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  18960. * @returns the scaled intensity in intensity mode unit
  18961. */
  18962. Light.prototype.getScaledIntensity = function () {
  18963. return this._photometricScale * this.intensity;
  18964. };
  18965. /**
  18966. * Returns a new Light object, named "name", from the current one.
  18967. * @param name The name of the cloned light
  18968. * @returns the new created light
  18969. */
  18970. Light.prototype.clone = function (name) {
  18971. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  18972. if (!constructor) {
  18973. return null;
  18974. }
  18975. return BABYLON.SerializationHelper.Clone(constructor, this);
  18976. };
  18977. /**
  18978. * Serializes the current light into a Serialization object.
  18979. * @returns the serialized object.
  18980. */
  18981. Light.prototype.serialize = function () {
  18982. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18983. // Type
  18984. serializationObject.type = this.getTypeID();
  18985. // Parent
  18986. if (this.parent) {
  18987. serializationObject.parentId = this.parent.id;
  18988. }
  18989. // Inclusion / exclusions
  18990. if (this.excludedMeshes.length > 0) {
  18991. serializationObject.excludedMeshesIds = [];
  18992. this.excludedMeshes.forEach(function (mesh) {
  18993. serializationObject.excludedMeshesIds.push(mesh.id);
  18994. });
  18995. }
  18996. if (this.includedOnlyMeshes.length > 0) {
  18997. serializationObject.includedOnlyMeshesIds = [];
  18998. this.includedOnlyMeshes.forEach(function (mesh) {
  18999. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19000. });
  19001. }
  19002. // Animations
  19003. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19004. serializationObject.ranges = this.serializeAnimationRanges();
  19005. return serializationObject;
  19006. };
  19007. /**
  19008. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19009. * This new light is named "name" and added to the passed scene.
  19010. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19011. * @param name The friendly name of the light
  19012. * @param scene The scene the new light will belong to
  19013. * @returns the constructor function
  19014. */
  19015. Light.GetConstructorFromName = function (type, name, scene) {
  19016. switch (type) {
  19017. case 0:
  19018. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19019. case 1:
  19020. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19021. case 2:
  19022. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19023. case 3:
  19024. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19025. }
  19026. return null;
  19027. };
  19028. /**
  19029. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19030. * @param parsedLight The JSON representation of the light
  19031. * @param scene The scene to create the parsed light in
  19032. * @returns the created light after parsing
  19033. */
  19034. Light.Parse = function (parsedLight, scene) {
  19035. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19036. if (!constructor) {
  19037. return null;
  19038. }
  19039. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19040. // Inclusion / exclusions
  19041. if (parsedLight.excludedMeshesIds) {
  19042. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19043. }
  19044. if (parsedLight.includedOnlyMeshesIds) {
  19045. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19046. }
  19047. // Parent
  19048. if (parsedLight.parentId) {
  19049. light._waitingParentId = parsedLight.parentId;
  19050. }
  19051. // Animations
  19052. if (parsedLight.animations) {
  19053. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19054. var parsedAnimation = parsedLight.animations[animationIndex];
  19055. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19056. }
  19057. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19058. }
  19059. if (parsedLight.autoAnimate) {
  19060. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19061. }
  19062. return light;
  19063. };
  19064. Light.prototype._hookArrayForExcluded = function (array) {
  19065. var _this = this;
  19066. var oldPush = array.push;
  19067. array.push = function () {
  19068. var items = [];
  19069. for (var _i = 0; _i < arguments.length; _i++) {
  19070. items[_i] = arguments[_i];
  19071. }
  19072. var result = oldPush.apply(array, items);
  19073. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19074. var item = items_1[_a];
  19075. item._resyncLighSource(_this);
  19076. }
  19077. return result;
  19078. };
  19079. var oldSplice = array.splice;
  19080. array.splice = function (index, deleteCount) {
  19081. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19082. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19083. var item = deleted_1[_i];
  19084. item._resyncLighSource(_this);
  19085. }
  19086. return deleted;
  19087. };
  19088. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19089. var item = array_1[_i];
  19090. item._resyncLighSource(this);
  19091. }
  19092. };
  19093. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19094. var _this = this;
  19095. var oldPush = array.push;
  19096. array.push = function () {
  19097. var items = [];
  19098. for (var _i = 0; _i < arguments.length; _i++) {
  19099. items[_i] = arguments[_i];
  19100. }
  19101. var result = oldPush.apply(array, items);
  19102. _this._resyncMeshes();
  19103. return result;
  19104. };
  19105. var oldSplice = array.splice;
  19106. array.splice = function (index, deleteCount) {
  19107. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19108. _this._resyncMeshes();
  19109. return deleted;
  19110. };
  19111. this._resyncMeshes();
  19112. };
  19113. Light.prototype._resyncMeshes = function () {
  19114. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19115. var mesh = _a[_i];
  19116. mesh._resyncLighSource(this);
  19117. }
  19118. };
  19119. /**
  19120. * Forces the meshes to update their light related information in their rendering used effects
  19121. * @ignore Internal Use Only
  19122. */
  19123. Light.prototype._markMeshesAsLightDirty = function () {
  19124. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19125. var mesh = _a[_i];
  19126. if (mesh._lightSources.indexOf(this) !== -1) {
  19127. mesh._markSubMeshesAsLightDirty();
  19128. }
  19129. }
  19130. };
  19131. /**
  19132. * Recomputes the cached photometric scale if needed.
  19133. */
  19134. Light.prototype._computePhotometricScale = function () {
  19135. this._photometricScale = this._getPhotometricScale();
  19136. this.getScene().resetCachedMaterial();
  19137. };
  19138. /**
  19139. * Returns the Photometric Scale according to the light type and intensity mode.
  19140. */
  19141. Light.prototype._getPhotometricScale = function () {
  19142. var photometricScale = 0.0;
  19143. var lightTypeID = this.getTypeID();
  19144. //get photometric mode
  19145. var photometricMode = this.intensityMode;
  19146. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19147. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19148. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19149. }
  19150. else {
  19151. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19152. }
  19153. }
  19154. //compute photometric scale
  19155. switch (lightTypeID) {
  19156. case Light.LIGHTTYPEID_POINTLIGHT:
  19157. case Light.LIGHTTYPEID_SPOTLIGHT:
  19158. switch (photometricMode) {
  19159. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19160. photometricScale = 1.0 / (4.0 * Math.PI);
  19161. break;
  19162. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19163. photometricScale = 1.0;
  19164. break;
  19165. case Light.INTENSITYMODE_LUMINANCE:
  19166. photometricScale = this.radius * this.radius;
  19167. break;
  19168. }
  19169. break;
  19170. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19171. switch (photometricMode) {
  19172. case Light.INTENSITYMODE_ILLUMINANCE:
  19173. photometricScale = 1.0;
  19174. break;
  19175. case Light.INTENSITYMODE_LUMINANCE:
  19176. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19177. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19178. var apexAngleRadians = this.radius;
  19179. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19180. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19181. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19182. photometricScale = solidAngle;
  19183. break;
  19184. }
  19185. break;
  19186. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19187. // No fall off in hemisperic light.
  19188. photometricScale = 1.0;
  19189. break;
  19190. }
  19191. return photometricScale;
  19192. };
  19193. /**
  19194. * Reorder the light in the scene according to their defined priority.
  19195. * @ignore Internal Use Only
  19196. */
  19197. Light.prototype._reorderLightsInScene = function () {
  19198. var scene = this.getScene();
  19199. if (this._renderPriority != 0) {
  19200. scene.requireLightSorting = true;
  19201. }
  19202. this.getScene().sortLightsByPriority();
  19203. };
  19204. //lightmapMode Consts
  19205. Light._LIGHTMAP_DEFAULT = 0;
  19206. Light._LIGHTMAP_SPECULAR = 1;
  19207. Light._LIGHTMAP_SHADOWSONLY = 2;
  19208. // Intensity Mode Consts
  19209. Light._INTENSITYMODE_AUTOMATIC = 0;
  19210. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19211. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19212. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19213. Light._INTENSITYMODE_LUMINANCE = 4;
  19214. // Light types ids const.
  19215. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19216. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19217. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19218. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19219. __decorate([
  19220. BABYLON.serializeAsColor3()
  19221. ], Light.prototype, "diffuse", void 0);
  19222. __decorate([
  19223. BABYLON.serializeAsColor3()
  19224. ], Light.prototype, "specular", void 0);
  19225. __decorate([
  19226. BABYLON.serialize()
  19227. ], Light.prototype, "intensity", void 0);
  19228. __decorate([
  19229. BABYLON.serialize()
  19230. ], Light.prototype, "range", void 0);
  19231. __decorate([
  19232. BABYLON.serialize()
  19233. ], Light.prototype, "intensityMode", null);
  19234. __decorate([
  19235. BABYLON.serialize()
  19236. ], Light.prototype, "radius", null);
  19237. __decorate([
  19238. BABYLON.serialize()
  19239. ], Light.prototype, "_renderPriority", void 0);
  19240. __decorate([
  19241. BABYLON.expandToProperty("_reorderLightsInScene")
  19242. ], Light.prototype, "renderPriority", void 0);
  19243. __decorate([
  19244. BABYLON.serialize()
  19245. ], Light.prototype, "shadowEnabled", void 0);
  19246. __decorate([
  19247. BABYLON.serialize("excludeWithLayerMask")
  19248. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19249. __decorate([
  19250. BABYLON.serialize("includeOnlyWithLayerMask")
  19251. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19252. __decorate([
  19253. BABYLON.serialize("lightmapMode")
  19254. ], Light.prototype, "_lightmapMode", void 0);
  19255. return Light;
  19256. }(BABYLON.Node));
  19257. BABYLON.Light = Light;
  19258. })(BABYLON || (BABYLON = {}));
  19259. //# sourceMappingURL=babylon.light.js.map
  19260. var BABYLON;
  19261. (function (BABYLON) {
  19262. var Camera = /** @class */ (function (_super) {
  19263. __extends(Camera, _super);
  19264. function Camera(name, position, scene) {
  19265. var _this = _super.call(this, name, scene) || this;
  19266. /**
  19267. * The vector the camera should consider as up.
  19268. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19269. */
  19270. _this.upVector = BABYLON.Vector3.Up();
  19271. _this.orthoLeft = null;
  19272. _this.orthoRight = null;
  19273. _this.orthoBottom = null;
  19274. _this.orthoTop = null;
  19275. /**
  19276. * FOV is set in Radians. (default is 0.8)
  19277. */
  19278. _this.fov = 0.8;
  19279. _this.minZ = 1;
  19280. _this.maxZ = 10000.0;
  19281. _this.inertia = 0.9;
  19282. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19283. _this.isIntermediate = false;
  19284. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19285. /**
  19286. * Restricts the camera to viewing objects with the same layerMask.
  19287. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19288. */
  19289. _this.layerMask = 0x0FFFFFFF;
  19290. /**
  19291. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19292. */
  19293. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19294. // Camera rig members
  19295. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19296. _this._rigCameras = new Array();
  19297. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19298. _this._skipRendering = false;
  19299. _this.customRenderTargets = new Array();
  19300. // Observables
  19301. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19302. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19303. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19304. _this.onRestoreStateObservable = new BABYLON.Observable();
  19305. // Cache
  19306. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19307. _this._projectionMatrix = new BABYLON.Matrix();
  19308. _this._doNotComputeProjectionMatrix = false;
  19309. _this._postProcesses = new Array();
  19310. _this._transformMatrix = BABYLON.Matrix.Zero();
  19311. _this._activeMeshes = new BABYLON.SmartArray(256);
  19312. _this._globalPosition = BABYLON.Vector3.Zero();
  19313. _this._refreshFrustumPlanes = true;
  19314. _this.getScene().addCamera(_this);
  19315. if (!_this.getScene().activeCamera) {
  19316. _this.getScene().activeCamera = _this;
  19317. }
  19318. _this.position = position;
  19319. return _this;
  19320. }
  19321. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19322. get: function () {
  19323. return Camera._PERSPECTIVE_CAMERA;
  19324. },
  19325. enumerable: true,
  19326. configurable: true
  19327. });
  19328. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19329. get: function () {
  19330. return Camera._ORTHOGRAPHIC_CAMERA;
  19331. },
  19332. enumerable: true,
  19333. configurable: true
  19334. });
  19335. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19336. /**
  19337. * This is the default FOV mode for perspective cameras.
  19338. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19339. *
  19340. */
  19341. get: function () {
  19342. return Camera._FOVMODE_VERTICAL_FIXED;
  19343. },
  19344. enumerable: true,
  19345. configurable: true
  19346. });
  19347. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19348. /**
  19349. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19350. *
  19351. */
  19352. get: function () {
  19353. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19354. },
  19355. enumerable: true,
  19356. configurable: true
  19357. });
  19358. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19359. get: function () {
  19360. return Camera._RIG_MODE_NONE;
  19361. },
  19362. enumerable: true,
  19363. configurable: true
  19364. });
  19365. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19366. get: function () {
  19367. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19368. },
  19369. enumerable: true,
  19370. configurable: true
  19371. });
  19372. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19373. get: function () {
  19374. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19375. },
  19376. enumerable: true,
  19377. configurable: true
  19378. });
  19379. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19380. get: function () {
  19381. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19382. },
  19383. enumerable: true,
  19384. configurable: true
  19385. });
  19386. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19387. get: function () {
  19388. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19389. },
  19390. enumerable: true,
  19391. configurable: true
  19392. });
  19393. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19394. get: function () {
  19395. return Camera._RIG_MODE_VR;
  19396. },
  19397. enumerable: true,
  19398. configurable: true
  19399. });
  19400. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19401. get: function () {
  19402. return Camera._RIG_MODE_WEBVR;
  19403. },
  19404. enumerable: true,
  19405. configurable: true
  19406. });
  19407. /**
  19408. * Store current camera state (fov, position, etc..)
  19409. */
  19410. Camera.prototype.storeState = function () {
  19411. this._stateStored = true;
  19412. this._storedFov = this.fov;
  19413. return this;
  19414. };
  19415. /**
  19416. * Restores the camera state values if it has been stored. You must call storeState() first
  19417. */
  19418. Camera.prototype._restoreStateValues = function () {
  19419. if (!this._stateStored) {
  19420. return false;
  19421. }
  19422. this.fov = this._storedFov;
  19423. return true;
  19424. };
  19425. /**
  19426. * Restored camera state. You must call storeState() first
  19427. */
  19428. Camera.prototype.restoreState = function () {
  19429. if (this._restoreStateValues()) {
  19430. this.onRestoreStateObservable.notifyObservers(this);
  19431. return true;
  19432. }
  19433. return false;
  19434. };
  19435. Camera.prototype.getClassName = function () {
  19436. return "Camera";
  19437. };
  19438. /**
  19439. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19440. */
  19441. Camera.prototype.toString = function (fullDetails) {
  19442. var ret = "Name: " + this.name;
  19443. ret += ", type: " + this.getClassName();
  19444. if (this.animations) {
  19445. for (var i = 0; i < this.animations.length; i++) {
  19446. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19447. }
  19448. }
  19449. if (fullDetails) {
  19450. }
  19451. return ret;
  19452. };
  19453. Object.defineProperty(Camera.prototype, "globalPosition", {
  19454. get: function () {
  19455. return this._globalPosition;
  19456. },
  19457. enumerable: true,
  19458. configurable: true
  19459. });
  19460. Camera.prototype.getActiveMeshes = function () {
  19461. return this._activeMeshes;
  19462. };
  19463. Camera.prototype.isActiveMesh = function (mesh) {
  19464. return (this._activeMeshes.indexOf(mesh) !== -1);
  19465. };
  19466. //Cache
  19467. Camera.prototype._initCache = function () {
  19468. _super.prototype._initCache.call(this);
  19469. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19470. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19471. this._cache.mode = undefined;
  19472. this._cache.minZ = undefined;
  19473. this._cache.maxZ = undefined;
  19474. this._cache.fov = undefined;
  19475. this._cache.fovMode = undefined;
  19476. this._cache.aspectRatio = undefined;
  19477. this._cache.orthoLeft = undefined;
  19478. this._cache.orthoRight = undefined;
  19479. this._cache.orthoBottom = undefined;
  19480. this._cache.orthoTop = undefined;
  19481. this._cache.renderWidth = undefined;
  19482. this._cache.renderHeight = undefined;
  19483. };
  19484. Camera.prototype._updateCache = function (ignoreParentClass) {
  19485. if (!ignoreParentClass) {
  19486. _super.prototype._updateCache.call(this);
  19487. }
  19488. this._cache.position.copyFrom(this.position);
  19489. this._cache.upVector.copyFrom(this.upVector);
  19490. };
  19491. // Synchronized
  19492. Camera.prototype._isSynchronized = function () {
  19493. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19494. };
  19495. Camera.prototype._isSynchronizedViewMatrix = function () {
  19496. if (!_super.prototype._isSynchronized.call(this))
  19497. return false;
  19498. return this._cache.position.equals(this.position)
  19499. && this._cache.upVector.equals(this.upVector)
  19500. && this.isSynchronizedWithParent();
  19501. };
  19502. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19503. var check = this._cache.mode === this.mode
  19504. && this._cache.minZ === this.minZ
  19505. && this._cache.maxZ === this.maxZ;
  19506. if (!check) {
  19507. return false;
  19508. }
  19509. var engine = this.getEngine();
  19510. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19511. check = this._cache.fov === this.fov
  19512. && this._cache.fovMode === this.fovMode
  19513. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19514. }
  19515. else {
  19516. check = this._cache.orthoLeft === this.orthoLeft
  19517. && this._cache.orthoRight === this.orthoRight
  19518. && this._cache.orthoBottom === this.orthoBottom
  19519. && this._cache.orthoTop === this.orthoTop
  19520. && this._cache.renderWidth === engine.getRenderWidth()
  19521. && this._cache.renderHeight === engine.getRenderHeight();
  19522. }
  19523. return check;
  19524. };
  19525. // Controls
  19526. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19527. };
  19528. Camera.prototype.detachControl = function (element) {
  19529. };
  19530. Camera.prototype.update = function () {
  19531. this._checkInputs();
  19532. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19533. this._updateRigCameras();
  19534. }
  19535. };
  19536. Camera.prototype._checkInputs = function () {
  19537. this.onAfterCheckInputsObservable.notifyObservers(this);
  19538. };
  19539. Object.defineProperty(Camera.prototype, "rigCameras", {
  19540. get: function () {
  19541. return this._rigCameras;
  19542. },
  19543. enumerable: true,
  19544. configurable: true
  19545. });
  19546. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19547. get: function () {
  19548. return this._rigPostProcess;
  19549. },
  19550. enumerable: true,
  19551. configurable: true
  19552. });
  19553. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19554. // invalidate framebuffer
  19555. if (this._postProcesses.length > 0) {
  19556. this._postProcesses[0].markTextureDirty();
  19557. }
  19558. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19559. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19560. var cam = this._rigCameras[i];
  19561. var rigPostProcess = cam._rigPostProcess;
  19562. // for VR rig, there does not have to be a post process
  19563. if (rigPostProcess) {
  19564. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19565. if (isPass) {
  19566. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19567. cam.isIntermediate = this._postProcesses.length === 0;
  19568. }
  19569. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19570. rigPostProcess.markTextureDirty();
  19571. }
  19572. else {
  19573. cam._postProcesses = this._postProcesses.slice(0);
  19574. }
  19575. }
  19576. };
  19577. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19578. if (insertAt === void 0) { insertAt = null; }
  19579. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19580. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19581. return 0;
  19582. }
  19583. if (insertAt == null || insertAt < 0) {
  19584. this._postProcesses.push(postProcess);
  19585. }
  19586. else {
  19587. this._postProcesses.splice(insertAt, 0, postProcess);
  19588. }
  19589. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19590. return this._postProcesses.indexOf(postProcess);
  19591. };
  19592. Camera.prototype.detachPostProcess = function (postProcess) {
  19593. var idx = this._postProcesses.indexOf(postProcess);
  19594. if (idx !== -1) {
  19595. this._postProcesses.splice(idx, 1);
  19596. }
  19597. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19598. };
  19599. Camera.prototype.getWorldMatrix = function () {
  19600. if (!this._worldMatrix) {
  19601. this._worldMatrix = BABYLON.Matrix.Identity();
  19602. }
  19603. var viewMatrix = this.getViewMatrix();
  19604. viewMatrix.invertToRef(this._worldMatrix);
  19605. return this._worldMatrix;
  19606. };
  19607. Camera.prototype._getViewMatrix = function () {
  19608. return BABYLON.Matrix.Identity();
  19609. };
  19610. Camera.prototype.getViewMatrix = function (force) {
  19611. if (!force && this._isSynchronizedViewMatrix()) {
  19612. return this._computedViewMatrix;
  19613. }
  19614. this.updateCache();
  19615. this._computedViewMatrix = this._getViewMatrix();
  19616. this._currentRenderId = this.getScene().getRenderId();
  19617. this._refreshFrustumPlanes = true;
  19618. if (!this.parent || !this.parent.getWorldMatrix) {
  19619. this._globalPosition.copyFrom(this.position);
  19620. }
  19621. else {
  19622. if (!this._worldMatrix) {
  19623. this._worldMatrix = BABYLON.Matrix.Identity();
  19624. }
  19625. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19626. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19627. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19628. this._computedViewMatrix.invert();
  19629. this._markSyncedWithParent();
  19630. }
  19631. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  19632. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  19633. }
  19634. this.onViewMatrixChangedObservable.notifyObservers(this);
  19635. return this._computedViewMatrix;
  19636. };
  19637. Camera.prototype.freezeProjectionMatrix = function (projection) {
  19638. this._doNotComputeProjectionMatrix = true;
  19639. if (projection !== undefined) {
  19640. this._projectionMatrix = projection;
  19641. }
  19642. };
  19643. ;
  19644. Camera.prototype.unfreezeProjectionMatrix = function () {
  19645. this._doNotComputeProjectionMatrix = false;
  19646. };
  19647. ;
  19648. Camera.prototype.getProjectionMatrix = function (force) {
  19649. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  19650. return this._projectionMatrix;
  19651. }
  19652. // Cache
  19653. this._cache.mode = this.mode;
  19654. this._cache.minZ = this.minZ;
  19655. this._cache.maxZ = this.maxZ;
  19656. // Matrix
  19657. this._refreshFrustumPlanes = true;
  19658. var engine = this.getEngine();
  19659. var scene = this.getScene();
  19660. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19661. this._cache.fov = this.fov;
  19662. this._cache.fovMode = this.fovMode;
  19663. this._cache.aspectRatio = engine.getAspectRatio(this);
  19664. if (this.minZ <= 0) {
  19665. this.minZ = 0.1;
  19666. }
  19667. if (scene.useRightHandedSystem) {
  19668. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19669. }
  19670. else {
  19671. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19672. }
  19673. }
  19674. else {
  19675. var halfWidth = engine.getRenderWidth() / 2.0;
  19676. var halfHeight = engine.getRenderHeight() / 2.0;
  19677. if (scene.useRightHandedSystem) {
  19678. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19679. }
  19680. else {
  19681. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19682. }
  19683. this._cache.orthoLeft = this.orthoLeft;
  19684. this._cache.orthoRight = this.orthoRight;
  19685. this._cache.orthoBottom = this.orthoBottom;
  19686. this._cache.orthoTop = this.orthoTop;
  19687. this._cache.renderWidth = engine.getRenderWidth();
  19688. this._cache.renderHeight = engine.getRenderHeight();
  19689. }
  19690. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  19691. return this._projectionMatrix;
  19692. };
  19693. Camera.prototype.getTranformationMatrix = function () {
  19694. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19695. return this._transformMatrix;
  19696. };
  19697. Camera.prototype.updateFrustumPlanes = function () {
  19698. if (!this._refreshFrustumPlanes) {
  19699. return;
  19700. }
  19701. this.getTranformationMatrix();
  19702. if (!this._frustumPlanes) {
  19703. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19704. }
  19705. else {
  19706. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19707. }
  19708. this._refreshFrustumPlanes = false;
  19709. };
  19710. Camera.prototype.isInFrustum = function (target) {
  19711. this.updateFrustumPlanes();
  19712. return target.isInFrustum(this._frustumPlanes);
  19713. };
  19714. Camera.prototype.isCompletelyInFrustum = function (target) {
  19715. this.updateFrustumPlanes();
  19716. return target.isCompletelyInFrustum(this._frustumPlanes);
  19717. };
  19718. Camera.prototype.getForwardRay = function (length, transform, origin) {
  19719. if (length === void 0) { length = 100; }
  19720. if (!transform) {
  19721. transform = this.getWorldMatrix();
  19722. }
  19723. if (!origin) {
  19724. origin = this.position;
  19725. }
  19726. var forward = new BABYLON.Vector3(0, 0, 1);
  19727. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  19728. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  19729. return new BABYLON.Ray(origin, direction, length);
  19730. };
  19731. Camera.prototype.dispose = function () {
  19732. // Observables
  19733. this.onViewMatrixChangedObservable.clear();
  19734. this.onProjectionMatrixChangedObservable.clear();
  19735. this.onAfterCheckInputsObservable.clear();
  19736. this.onRestoreStateObservable.clear();
  19737. // Inputs
  19738. if (this.inputs) {
  19739. this.inputs.clear();
  19740. }
  19741. // Animations
  19742. this.getScene().stopAnimation(this);
  19743. // Remove from scene
  19744. this.getScene().removeCamera(this);
  19745. while (this._rigCameras.length > 0) {
  19746. var camera = this._rigCameras.pop();
  19747. if (camera) {
  19748. camera.dispose();
  19749. }
  19750. }
  19751. // Postprocesses
  19752. if (this._rigPostProcess) {
  19753. this._rigPostProcess.dispose(this);
  19754. this._rigPostProcess = null;
  19755. this._postProcesses = [];
  19756. }
  19757. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19758. this._rigPostProcess = null;
  19759. this._postProcesses = [];
  19760. }
  19761. else {
  19762. var i = this._postProcesses.length;
  19763. while (--i >= 0) {
  19764. this._postProcesses[i].dispose(this);
  19765. }
  19766. }
  19767. // Render targets
  19768. var i = this.customRenderTargets.length;
  19769. while (--i >= 0) {
  19770. this.customRenderTargets[i].dispose();
  19771. }
  19772. this.customRenderTargets = [];
  19773. // Active Meshes
  19774. this._activeMeshes.dispose();
  19775. _super.prototype.dispose.call(this);
  19776. };
  19777. Object.defineProperty(Camera.prototype, "leftCamera", {
  19778. // ---- Camera rigs section ----
  19779. get: function () {
  19780. if (this._rigCameras.length < 1) {
  19781. return null;
  19782. }
  19783. return this._rigCameras[0];
  19784. },
  19785. enumerable: true,
  19786. configurable: true
  19787. });
  19788. Object.defineProperty(Camera.prototype, "rightCamera", {
  19789. get: function () {
  19790. if (this._rigCameras.length < 2) {
  19791. return null;
  19792. }
  19793. return this._rigCameras[1];
  19794. },
  19795. enumerable: true,
  19796. configurable: true
  19797. });
  19798. Camera.prototype.getLeftTarget = function () {
  19799. if (this._rigCameras.length < 1) {
  19800. return null;
  19801. }
  19802. return this._rigCameras[0].getTarget();
  19803. };
  19804. Camera.prototype.getRightTarget = function () {
  19805. if (this._rigCameras.length < 2) {
  19806. return null;
  19807. }
  19808. return this._rigCameras[1].getTarget();
  19809. };
  19810. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19811. if (this.cameraRigMode === mode) {
  19812. return;
  19813. }
  19814. while (this._rigCameras.length > 0) {
  19815. var camera = this._rigCameras.pop();
  19816. if (camera) {
  19817. camera.dispose();
  19818. }
  19819. }
  19820. this.cameraRigMode = mode;
  19821. this._cameraRigParams = {};
  19822. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19823. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19824. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19825. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19826. // create the rig cameras, unless none
  19827. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19828. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19829. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19830. if (leftCamera && rightCamera) {
  19831. this._rigCameras.push(leftCamera);
  19832. this._rigCameras.push(rightCamera);
  19833. }
  19834. }
  19835. switch (this.cameraRigMode) {
  19836. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19837. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19838. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19839. break;
  19840. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19841. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19842. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19843. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19844. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19845. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19846. break;
  19847. case Camera.RIG_MODE_VR:
  19848. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19849. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19850. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19851. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19852. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19853. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19854. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19855. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19856. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19857. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19858. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19859. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19860. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19861. if (metrics.compensateDistortion) {
  19862. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19863. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19864. }
  19865. break;
  19866. case Camera.RIG_MODE_WEBVR:
  19867. if (rigParams.vrDisplay) {
  19868. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19869. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19870. //Left eye
  19871. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19872. this._rigCameras[0].setCameraRigParameter("left", true);
  19873. //leaving this for future reference
  19874. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19875. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19876. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19877. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19878. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19879. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19880. this._rigCameras[0].parent = this;
  19881. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19882. //Right eye
  19883. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19884. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19885. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19886. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  19887. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19888. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19889. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19890. this._rigCameras[1].parent = this;
  19891. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19892. if (Camera.UseAlternateWebVRRendering) {
  19893. this._rigCameras[1]._skipRendering = true;
  19894. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19895. }
  19896. }
  19897. break;
  19898. }
  19899. this._cascadePostProcessesToRigCams();
  19900. this.update();
  19901. };
  19902. Camera.prototype._getVRProjectionMatrix = function () {
  19903. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  19904. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  19905. return this._projectionMatrix;
  19906. };
  19907. Camera.prototype._updateCameraRotationMatrix = function () {
  19908. //Here for WebVR
  19909. };
  19910. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  19911. //Here for WebVR
  19912. };
  19913. /**
  19914. * This function MUST be overwritten by the different WebVR cameras available.
  19915. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19916. */
  19917. Camera.prototype._getWebVRProjectionMatrix = function () {
  19918. return BABYLON.Matrix.Identity();
  19919. };
  19920. /**
  19921. * This function MUST be overwritten by the different WebVR cameras available.
  19922. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19923. */
  19924. Camera.prototype._getWebVRViewMatrix = function () {
  19925. return BABYLON.Matrix.Identity();
  19926. };
  19927. Camera.prototype.setCameraRigParameter = function (name, value) {
  19928. if (!this._cameraRigParams) {
  19929. this._cameraRigParams = {};
  19930. }
  19931. this._cameraRigParams[name] = value;
  19932. //provisionnally:
  19933. if (name === "interaxialDistance") {
  19934. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  19935. }
  19936. };
  19937. /**
  19938. * needs to be overridden by children so sub has required properties to be copied
  19939. */
  19940. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  19941. return null;
  19942. };
  19943. /**
  19944. * May need to be overridden by children
  19945. */
  19946. Camera.prototype._updateRigCameras = function () {
  19947. for (var i = 0; i < this._rigCameras.length; i++) {
  19948. this._rigCameras[i].minZ = this.minZ;
  19949. this._rigCameras[i].maxZ = this.maxZ;
  19950. this._rigCameras[i].fov = this.fov;
  19951. }
  19952. // only update viewport when ANAGLYPH
  19953. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  19954. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  19955. }
  19956. };
  19957. Camera.prototype._setupInputs = function () {
  19958. };
  19959. Camera.prototype.serialize = function () {
  19960. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19961. // Type
  19962. serializationObject.type = this.getClassName();
  19963. // Parent
  19964. if (this.parent) {
  19965. serializationObject.parentId = this.parent.id;
  19966. }
  19967. if (this.inputs) {
  19968. this.inputs.serialize(serializationObject);
  19969. }
  19970. // Animations
  19971. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19972. serializationObject.ranges = this.serializeAnimationRanges();
  19973. return serializationObject;
  19974. };
  19975. Camera.prototype.clone = function (name) {
  19976. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  19977. };
  19978. Camera.prototype.getDirection = function (localAxis) {
  19979. var result = BABYLON.Vector3.Zero();
  19980. this.getDirectionToRef(localAxis, result);
  19981. return result;
  19982. };
  19983. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  19984. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19985. };
  19986. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  19987. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  19988. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  19989. switch (type) {
  19990. case "ArcRotateCamera":
  19991. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  19992. case "DeviceOrientationCamera":
  19993. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  19994. case "FollowCamera":
  19995. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  19996. case "ArcFollowCamera":
  19997. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  19998. case "GamepadCamera":
  19999. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20000. case "TouchCamera":
  20001. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20002. case "VirtualJoysticksCamera":
  20003. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20004. case "WebVRFreeCamera":
  20005. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20006. case "WebVRGamepadCamera":
  20007. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20008. case "VRDeviceOrientationFreeCamera":
  20009. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20010. case "VRDeviceOrientationGamepadCamera":
  20011. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20012. case "AnaglyphArcRotateCamera":
  20013. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20014. case "AnaglyphFreeCamera":
  20015. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20016. case "AnaglyphGamepadCamera":
  20017. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20018. case "AnaglyphUniversalCamera":
  20019. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20020. case "StereoscopicArcRotateCamera":
  20021. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20022. case "StereoscopicFreeCamera":
  20023. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20024. case "StereoscopicGamepadCamera":
  20025. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20026. case "StereoscopicUniversalCamera":
  20027. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20028. case "FreeCamera":// Forcing Universal here
  20029. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20030. default:// Universal Camera is the default value
  20031. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20032. }
  20033. };
  20034. Camera.prototype.computeWorldMatrix = function () {
  20035. return this.getWorldMatrix();
  20036. };
  20037. Camera.Parse = function (parsedCamera, scene) {
  20038. var type = parsedCamera.type;
  20039. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20040. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20041. // Parent
  20042. if (parsedCamera.parentId) {
  20043. camera._waitingParentId = parsedCamera.parentId;
  20044. }
  20045. //If camera has an input manager, let it parse inputs settings
  20046. if (camera.inputs) {
  20047. camera.inputs.parse(parsedCamera);
  20048. camera._setupInputs();
  20049. }
  20050. if (camera.setPosition) {
  20051. camera.position.copyFromFloats(0, 0, 0);
  20052. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20053. }
  20054. // Target
  20055. if (parsedCamera.target) {
  20056. if (camera.setTarget) {
  20057. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20058. }
  20059. }
  20060. // Apply 3d rig, when found
  20061. if (parsedCamera.cameraRigMode) {
  20062. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20063. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20064. }
  20065. // Animations
  20066. if (parsedCamera.animations) {
  20067. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20068. var parsedAnimation = parsedCamera.animations[animationIndex];
  20069. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20070. }
  20071. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20072. }
  20073. if (parsedCamera.autoAnimate) {
  20074. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20075. }
  20076. return camera;
  20077. };
  20078. // Statics
  20079. Camera._PERSPECTIVE_CAMERA = 0;
  20080. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20081. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20082. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20083. Camera._RIG_MODE_NONE = 0;
  20084. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20085. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20086. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20087. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20088. Camera._RIG_MODE_VR = 20;
  20089. Camera._RIG_MODE_WEBVR = 21;
  20090. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20091. Camera.UseAlternateWebVRRendering = false;
  20092. __decorate([
  20093. BABYLON.serializeAsVector3()
  20094. ], Camera.prototype, "position", void 0);
  20095. __decorate([
  20096. BABYLON.serializeAsVector3()
  20097. ], Camera.prototype, "upVector", void 0);
  20098. __decorate([
  20099. BABYLON.serialize()
  20100. ], Camera.prototype, "orthoLeft", void 0);
  20101. __decorate([
  20102. BABYLON.serialize()
  20103. ], Camera.prototype, "orthoRight", void 0);
  20104. __decorate([
  20105. BABYLON.serialize()
  20106. ], Camera.prototype, "orthoBottom", void 0);
  20107. __decorate([
  20108. BABYLON.serialize()
  20109. ], Camera.prototype, "orthoTop", void 0);
  20110. __decorate([
  20111. BABYLON.serialize()
  20112. ], Camera.prototype, "fov", void 0);
  20113. __decorate([
  20114. BABYLON.serialize()
  20115. ], Camera.prototype, "minZ", void 0);
  20116. __decorate([
  20117. BABYLON.serialize()
  20118. ], Camera.prototype, "maxZ", void 0);
  20119. __decorate([
  20120. BABYLON.serialize()
  20121. ], Camera.prototype, "inertia", void 0);
  20122. __decorate([
  20123. BABYLON.serialize()
  20124. ], Camera.prototype, "mode", void 0);
  20125. __decorate([
  20126. BABYLON.serialize()
  20127. ], Camera.prototype, "layerMask", void 0);
  20128. __decorate([
  20129. BABYLON.serialize()
  20130. ], Camera.prototype, "fovMode", void 0);
  20131. __decorate([
  20132. BABYLON.serialize()
  20133. ], Camera.prototype, "cameraRigMode", void 0);
  20134. __decorate([
  20135. BABYLON.serialize()
  20136. ], Camera.prototype, "interaxialDistance", void 0);
  20137. __decorate([
  20138. BABYLON.serialize()
  20139. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20140. return Camera;
  20141. }(BABYLON.Node));
  20142. BABYLON.Camera = Camera;
  20143. })(BABYLON || (BABYLON = {}));
  20144. //# sourceMappingURL=babylon.camera.js.map
  20145. var BABYLON;
  20146. (function (BABYLON) {
  20147. var RenderingManager = /** @class */ (function () {
  20148. function RenderingManager(scene) {
  20149. this._renderingGroups = new Array();
  20150. this._autoClearDepthStencil = {};
  20151. this._customOpaqueSortCompareFn = {};
  20152. this._customAlphaTestSortCompareFn = {};
  20153. this._customTransparentSortCompareFn = {};
  20154. this._renderinGroupInfo = null;
  20155. this._scene = scene;
  20156. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20157. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20158. }
  20159. }
  20160. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20161. if (depth === void 0) { depth = true; }
  20162. if (stencil === void 0) { stencil = true; }
  20163. if (this._depthStencilBufferAlreadyCleaned) {
  20164. return;
  20165. }
  20166. this._scene.getEngine().clear(null, false, depth, stencil);
  20167. this._depthStencilBufferAlreadyCleaned = true;
  20168. };
  20169. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20170. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20171. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20172. var info = null;
  20173. if (observable) {
  20174. if (!this._renderinGroupInfo) {
  20175. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20176. }
  20177. info = this._renderinGroupInfo;
  20178. info.scene = this._scene;
  20179. info.camera = this._scene.activeCamera;
  20180. }
  20181. // Dispatch sprites
  20182. if (renderSprites) {
  20183. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20184. var manager = this._scene.spriteManagers[index];
  20185. this.dispatchSprites(manager);
  20186. }
  20187. }
  20188. // Render
  20189. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20190. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20191. var renderingGroup = this._renderingGroups[index];
  20192. if (!renderingGroup && !observable)
  20193. continue;
  20194. var renderingGroupMask = 0;
  20195. // Fire PRECLEAR stage
  20196. if (observable && info) {
  20197. renderingGroupMask = Math.pow(2, index);
  20198. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20199. info.renderingGroupId = index;
  20200. observable.notifyObservers(info, renderingGroupMask);
  20201. }
  20202. // Clear depth/stencil if needed
  20203. if (RenderingManager.AUTOCLEAR) {
  20204. var autoClear = this._autoClearDepthStencil[index];
  20205. if (autoClear && autoClear.autoClear) {
  20206. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20207. }
  20208. }
  20209. if (observable && info) {
  20210. // Fire PREOPAQUE stage
  20211. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20212. observable.notifyObservers(info, renderingGroupMask);
  20213. // Fire PRETRANSPARENT stage
  20214. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20215. observable.notifyObservers(info, renderingGroupMask);
  20216. }
  20217. if (renderingGroup)
  20218. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20219. // Fire POSTTRANSPARENT stage
  20220. if (observable && info) {
  20221. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20222. observable.notifyObservers(info, renderingGroupMask);
  20223. }
  20224. }
  20225. };
  20226. RenderingManager.prototype.reset = function () {
  20227. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20228. var renderingGroup = this._renderingGroups[index];
  20229. if (renderingGroup) {
  20230. renderingGroup.prepare();
  20231. }
  20232. }
  20233. };
  20234. RenderingManager.prototype.dispose = function () {
  20235. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20236. var renderingGroup = this._renderingGroups[index];
  20237. if (renderingGroup) {
  20238. renderingGroup.dispose();
  20239. }
  20240. }
  20241. this._renderingGroups.length = 0;
  20242. };
  20243. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20244. if (this._renderingGroups[renderingGroupId] === undefined) {
  20245. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20246. }
  20247. };
  20248. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20249. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20250. this._prepareRenderingGroup(renderingGroupId);
  20251. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20252. };
  20253. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20254. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20255. this._prepareRenderingGroup(renderingGroupId);
  20256. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20257. };
  20258. /**
  20259. * @param subMesh The submesh to dispatch
  20260. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20261. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20262. */
  20263. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20264. if (mesh === undefined) {
  20265. mesh = subMesh.getMesh();
  20266. }
  20267. var renderingGroupId = mesh.renderingGroupId || 0;
  20268. this._prepareRenderingGroup(renderingGroupId);
  20269. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20270. };
  20271. /**
  20272. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20273. * This allowed control for front to back rendering or reversly depending of the special needs.
  20274. *
  20275. * @param renderingGroupId The rendering group id corresponding to its index
  20276. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20277. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20278. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20279. */
  20280. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20281. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20282. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20283. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20284. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20285. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20286. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20287. if (this._renderingGroups[renderingGroupId]) {
  20288. var group = this._renderingGroups[renderingGroupId];
  20289. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20290. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20291. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20292. }
  20293. };
  20294. /**
  20295. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20296. *
  20297. * @param renderingGroupId The rendering group id corresponding to its index
  20298. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20299. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20300. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20301. */
  20302. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20303. if (depth === void 0) { depth = true; }
  20304. if (stencil === void 0) { stencil = true; }
  20305. this._autoClearDepthStencil[renderingGroupId] = {
  20306. autoClear: autoClearDepthStencil,
  20307. depth: depth,
  20308. stencil: stencil
  20309. };
  20310. };
  20311. /**
  20312. * The max id used for rendering groups (not included)
  20313. */
  20314. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20315. /**
  20316. * The min id used for rendering groups (included)
  20317. */
  20318. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20319. /**
  20320. * Used to globally prevent autoclearing scenes.
  20321. */
  20322. RenderingManager.AUTOCLEAR = true;
  20323. return RenderingManager;
  20324. }());
  20325. BABYLON.RenderingManager = RenderingManager;
  20326. })(BABYLON || (BABYLON = {}));
  20327. //# sourceMappingURL=babylon.renderingManager.js.map
  20328. var BABYLON;
  20329. (function (BABYLON) {
  20330. var RenderingGroup = /** @class */ (function () {
  20331. /**
  20332. * Creates a new rendering group.
  20333. * @param index The rendering group index
  20334. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20335. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20336. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20337. */
  20338. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20339. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20340. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20341. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20342. this.index = index;
  20343. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20344. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20345. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20346. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20347. this._particleSystems = new BABYLON.SmartArray(256);
  20348. this._spriteManagers = new BABYLON.SmartArray(256);
  20349. this._edgesRenderers = new BABYLON.SmartArray(16);
  20350. this._scene = scene;
  20351. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20352. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20353. this.transparentSortCompareFn = transparentSortCompareFn;
  20354. }
  20355. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20356. /**
  20357. * Set the opaque sort comparison function.
  20358. * If null the sub meshes will be render in the order they were created
  20359. */
  20360. set: function (value) {
  20361. this._opaqueSortCompareFn = value;
  20362. if (value) {
  20363. this._renderOpaque = this.renderOpaqueSorted;
  20364. }
  20365. else {
  20366. this._renderOpaque = RenderingGroup.renderUnsorted;
  20367. }
  20368. },
  20369. enumerable: true,
  20370. configurable: true
  20371. });
  20372. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20373. /**
  20374. * Set the alpha test sort comparison function.
  20375. * If null the sub meshes will be render in the order they were created
  20376. */
  20377. set: function (value) {
  20378. this._alphaTestSortCompareFn = value;
  20379. if (value) {
  20380. this._renderAlphaTest = this.renderAlphaTestSorted;
  20381. }
  20382. else {
  20383. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20384. }
  20385. },
  20386. enumerable: true,
  20387. configurable: true
  20388. });
  20389. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20390. /**
  20391. * Set the transparent sort comparison function.
  20392. * If null the sub meshes will be render in the order they were created
  20393. */
  20394. set: function (value) {
  20395. if (value) {
  20396. this._transparentSortCompareFn = value;
  20397. }
  20398. else {
  20399. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20400. }
  20401. this._renderTransparent = this.renderTransparentSorted;
  20402. },
  20403. enumerable: true,
  20404. configurable: true
  20405. });
  20406. /**
  20407. * Render all the sub meshes contained in the group.
  20408. * @param customRenderFunction Used to override the default render behaviour of the group.
  20409. * @returns true if rendered some submeshes.
  20410. */
  20411. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20412. if (customRenderFunction) {
  20413. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20414. return;
  20415. }
  20416. var engine = this._scene.getEngine();
  20417. // Depth only
  20418. if (this._depthOnlySubMeshes.length !== 0) {
  20419. engine.setColorWrite(false);
  20420. this._renderAlphaTest(this._depthOnlySubMeshes);
  20421. engine.setColorWrite(true);
  20422. }
  20423. // Opaque
  20424. if (this._opaqueSubMeshes.length !== 0) {
  20425. this._renderOpaque(this._opaqueSubMeshes);
  20426. }
  20427. // Alpha test
  20428. if (this._alphaTestSubMeshes.length !== 0) {
  20429. this._renderAlphaTest(this._alphaTestSubMeshes);
  20430. }
  20431. var stencilState = engine.getStencilBuffer();
  20432. engine.setStencilBuffer(false);
  20433. // Sprites
  20434. if (renderSprites) {
  20435. this._renderSprites();
  20436. }
  20437. // Particles
  20438. if (renderParticles) {
  20439. this._renderParticles(activeMeshes);
  20440. }
  20441. if (this.onBeforeTransparentRendering) {
  20442. this.onBeforeTransparentRendering();
  20443. }
  20444. // Transparent
  20445. if (this._transparentSubMeshes.length !== 0) {
  20446. this._renderTransparent(this._transparentSubMeshes);
  20447. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20448. }
  20449. // Set back stencil to false in case it changes before the edge renderer.
  20450. engine.setStencilBuffer(false);
  20451. // Edges
  20452. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20453. this._edgesRenderers.data[edgesRendererIndex].render();
  20454. }
  20455. // Restore Stencil state.
  20456. engine.setStencilBuffer(stencilState);
  20457. };
  20458. /**
  20459. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20460. * @param subMeshes The submeshes to render
  20461. */
  20462. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20463. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20464. };
  20465. /**
  20466. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20467. * @param subMeshes The submeshes to render
  20468. */
  20469. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20470. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20471. };
  20472. /**
  20473. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20474. * @param subMeshes The submeshes to render
  20475. */
  20476. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20477. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20478. };
  20479. /**
  20480. * Renders the submeshes in a specified order.
  20481. * @param subMeshes The submeshes to sort before render
  20482. * @param sortCompareFn The comparison function use to sort
  20483. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20484. * @param transparent Specifies to activate blending if true
  20485. */
  20486. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20487. var subIndex = 0;
  20488. var subMesh;
  20489. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20490. for (; subIndex < subMeshes.length; subIndex++) {
  20491. subMesh = subMeshes.data[subIndex];
  20492. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20493. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20494. }
  20495. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20496. if (sortCompareFn) {
  20497. sortedArray.sort(sortCompareFn);
  20498. }
  20499. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20500. subMesh = sortedArray[subIndex];
  20501. if (transparent) {
  20502. var material = subMesh.getMaterial();
  20503. if (material && material.needDepthPrePass) {
  20504. var engine = material.getScene().getEngine();
  20505. engine.setColorWrite(false);
  20506. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20507. subMesh.render(false);
  20508. engine.setColorWrite(true);
  20509. }
  20510. }
  20511. subMesh.render(transparent);
  20512. }
  20513. };
  20514. /**
  20515. * Renders the submeshes in the order they were dispatched (no sort applied).
  20516. * @param subMeshes The submeshes to render
  20517. */
  20518. RenderingGroup.renderUnsorted = function (subMeshes) {
  20519. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20520. var submesh = subMeshes.data[subIndex];
  20521. submesh.render(false);
  20522. }
  20523. };
  20524. /**
  20525. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20526. * are rendered back to front if in the same alpha index.
  20527. *
  20528. * @param a The first submesh
  20529. * @param b The second submesh
  20530. * @returns The result of the comparison
  20531. */
  20532. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20533. // Alpha index first
  20534. if (a._alphaIndex > b._alphaIndex) {
  20535. return 1;
  20536. }
  20537. if (a._alphaIndex < b._alphaIndex) {
  20538. return -1;
  20539. }
  20540. // Then distance to camera
  20541. return RenderingGroup.backToFrontSortCompare(a, b);
  20542. };
  20543. /**
  20544. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20545. * are rendered back to front.
  20546. *
  20547. * @param a The first submesh
  20548. * @param b The second submesh
  20549. * @returns The result of the comparison
  20550. */
  20551. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20552. // Then distance to camera
  20553. if (a._distanceToCamera < b._distanceToCamera) {
  20554. return 1;
  20555. }
  20556. if (a._distanceToCamera > b._distanceToCamera) {
  20557. return -1;
  20558. }
  20559. return 0;
  20560. };
  20561. /**
  20562. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20563. * are rendered front to back (prevent overdraw).
  20564. *
  20565. * @param a The first submesh
  20566. * @param b The second submesh
  20567. * @returns The result of the comparison
  20568. */
  20569. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20570. // Then distance to camera
  20571. if (a._distanceToCamera < b._distanceToCamera) {
  20572. return -1;
  20573. }
  20574. if (a._distanceToCamera > b._distanceToCamera) {
  20575. return 1;
  20576. }
  20577. return 0;
  20578. };
  20579. /**
  20580. * Resets the different lists of submeshes to prepare a new frame.
  20581. */
  20582. RenderingGroup.prototype.prepare = function () {
  20583. this._opaqueSubMeshes.reset();
  20584. this._transparentSubMeshes.reset();
  20585. this._alphaTestSubMeshes.reset();
  20586. this._depthOnlySubMeshes.reset();
  20587. this._particleSystems.reset();
  20588. this._spriteManagers.reset();
  20589. this._edgesRenderers.reset();
  20590. };
  20591. RenderingGroup.prototype.dispose = function () {
  20592. this._opaqueSubMeshes.dispose();
  20593. this._transparentSubMeshes.dispose();
  20594. this._alphaTestSubMeshes.dispose();
  20595. this._depthOnlySubMeshes.dispose();
  20596. this._particleSystems.dispose();
  20597. this._spriteManagers.dispose();
  20598. this._edgesRenderers.dispose();
  20599. };
  20600. /**
  20601. * Inserts the submesh in its correct queue depending on its material.
  20602. * @param subMesh The submesh to dispatch
  20603. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20604. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20605. */
  20606. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20607. // Get mesh and materials if not provided
  20608. if (mesh === undefined) {
  20609. mesh = subMesh.getMesh();
  20610. }
  20611. if (material === undefined) {
  20612. material = subMesh.getMaterial();
  20613. }
  20614. if (material === null || material === undefined) {
  20615. return;
  20616. }
  20617. if (material.needAlphaBlendingForMesh(mesh)) {
  20618. this._transparentSubMeshes.push(subMesh);
  20619. }
  20620. else if (material.needAlphaTesting()) {
  20621. if (material.needDepthPrePass) {
  20622. this._depthOnlySubMeshes.push(subMesh);
  20623. }
  20624. this._alphaTestSubMeshes.push(subMesh);
  20625. }
  20626. else {
  20627. if (material.needDepthPrePass) {
  20628. this._depthOnlySubMeshes.push(subMesh);
  20629. }
  20630. this._opaqueSubMeshes.push(subMesh); // Opaque
  20631. }
  20632. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  20633. this._edgesRenderers.push(mesh._edgesRenderer);
  20634. }
  20635. };
  20636. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  20637. this._spriteManagers.push(spriteManager);
  20638. };
  20639. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  20640. this._particleSystems.push(particleSystem);
  20641. };
  20642. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  20643. if (this._particleSystems.length === 0) {
  20644. return;
  20645. }
  20646. // Particles
  20647. var activeCamera = this._scene.activeCamera;
  20648. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  20649. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  20650. var particleSystem = this._particleSystems.data[particleIndex];
  20651. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  20652. continue;
  20653. }
  20654. var emitter = particleSystem.emitter;
  20655. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  20656. this._scene._activeParticles.addCount(particleSystem.render(), false);
  20657. }
  20658. }
  20659. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  20660. };
  20661. RenderingGroup.prototype._renderSprites = function () {
  20662. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  20663. return;
  20664. }
  20665. // Sprites
  20666. var activeCamera = this._scene.activeCamera;
  20667. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  20668. for (var id = 0; id < this._spriteManagers.length; id++) {
  20669. var spriteManager = this._spriteManagers.data[id];
  20670. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  20671. spriteManager.render();
  20672. }
  20673. }
  20674. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  20675. };
  20676. return RenderingGroup;
  20677. }());
  20678. BABYLON.RenderingGroup = RenderingGroup;
  20679. })(BABYLON || (BABYLON = {}));
  20680. //# sourceMappingURL=babylon.renderingGroup.js.map
  20681. var BABYLON;
  20682. (function (BABYLON) {
  20683. var ClickInfo = /** @class */ (function () {
  20684. function ClickInfo() {
  20685. this._singleClick = false;
  20686. this._doubleClick = false;
  20687. this._hasSwiped = false;
  20688. this._ignore = false;
  20689. }
  20690. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  20691. get: function () {
  20692. return this._singleClick;
  20693. },
  20694. set: function (b) {
  20695. this._singleClick = b;
  20696. },
  20697. enumerable: true,
  20698. configurable: true
  20699. });
  20700. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  20701. get: function () {
  20702. return this._doubleClick;
  20703. },
  20704. set: function (b) {
  20705. this._doubleClick = b;
  20706. },
  20707. enumerable: true,
  20708. configurable: true
  20709. });
  20710. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  20711. get: function () {
  20712. return this._hasSwiped;
  20713. },
  20714. set: function (b) {
  20715. this._hasSwiped = b;
  20716. },
  20717. enumerable: true,
  20718. configurable: true
  20719. });
  20720. Object.defineProperty(ClickInfo.prototype, "ignore", {
  20721. get: function () {
  20722. return this._ignore;
  20723. },
  20724. set: function (b) {
  20725. this._ignore = b;
  20726. },
  20727. enumerable: true,
  20728. configurable: true
  20729. });
  20730. return ClickInfo;
  20731. }());
  20732. /**
  20733. * This class is used by the onRenderingGroupObservable
  20734. */
  20735. var RenderingGroupInfo = /** @class */ (function () {
  20736. function RenderingGroupInfo() {
  20737. }
  20738. /**
  20739. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  20740. * This stage will be fired no matter what
  20741. */
  20742. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  20743. /**
  20744. * Called before opaque object are rendered.
  20745. * This stage will be fired only if there's 3D Opaque content to render
  20746. */
  20747. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  20748. /**
  20749. * Called after the opaque objects are rendered and before the transparent ones
  20750. * This stage will be fired only if there's 3D transparent content to render
  20751. */
  20752. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  20753. /**
  20754. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  20755. * This stage will be fired no matter what
  20756. */
  20757. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  20758. return RenderingGroupInfo;
  20759. }());
  20760. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  20761. /**
  20762. * Represents a scene to be rendered by the engine.
  20763. * @see http://doc.babylonjs.com/page.php?p=21911
  20764. */
  20765. var Scene = /** @class */ (function () {
  20766. /**
  20767. * @constructor
  20768. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  20769. */
  20770. function Scene(engine) {
  20771. // Members
  20772. this.autoClear = true;
  20773. this.autoClearDepthAndStencil = true;
  20774. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20775. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20776. this.forceWireframe = false;
  20777. this._forcePointsCloud = false;
  20778. this.forceShowBoundingBoxes = false;
  20779. this.animationsEnabled = true;
  20780. this.useConstantAnimationDeltaTime = false;
  20781. this.constantlyUpdateMeshUnderPointer = false;
  20782. this.hoverCursor = "pointer";
  20783. this.defaultCursor = "";
  20784. /**
  20785. * This is used to call preventDefault() on pointer down
  20786. * in order to block unwanted artifacts like system double clicks
  20787. */
  20788. this.preventDefaultOnPointerDown = true;
  20789. // Metadata
  20790. this.metadata = null;
  20791. /**
  20792. * An event triggered when the scene is disposed.
  20793. * @type {BABYLON.Observable}
  20794. */
  20795. this.onDisposeObservable = new BABYLON.Observable();
  20796. /**
  20797. * An event triggered before rendering the scene (right after animations and physics)
  20798. * @type {BABYLON.Observable}
  20799. */
  20800. this.onBeforeRenderObservable = new BABYLON.Observable();
  20801. /**
  20802. * An event triggered after rendering the scene
  20803. * @type {BABYLON.Observable}
  20804. */
  20805. this.onAfterRenderObservable = new BABYLON.Observable();
  20806. /**
  20807. * An event triggered before animating the scene
  20808. * @type {BABYLON.Observable}
  20809. */
  20810. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20811. /**
  20812. * An event triggered after animations processing
  20813. * @type {BABYLON.Observable}
  20814. */
  20815. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20816. /**
  20817. * An event triggered before draw calls are ready to be sent
  20818. * @type {BABYLON.Observable}
  20819. */
  20820. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20821. /**
  20822. * An event triggered after draw calls have been sent
  20823. * @type {BABYLON.Observable}
  20824. */
  20825. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20826. /**
  20827. * An event triggered when physic simulation is about to be run
  20828. * @type {BABYLON.Observable}
  20829. */
  20830. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20831. /**
  20832. * An event triggered when physic simulation has been done
  20833. * @type {BABYLON.Observable}
  20834. */
  20835. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20836. /**
  20837. * An event triggered when the scene is ready
  20838. * @type {BABYLON.Observable}
  20839. */
  20840. this.onReadyObservable = new BABYLON.Observable();
  20841. /**
  20842. * An event triggered before rendering a camera
  20843. * @type {BABYLON.Observable}
  20844. */
  20845. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20846. /**
  20847. * An event triggered after rendering a camera
  20848. * @type {BABYLON.Observable}
  20849. */
  20850. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20851. /**
  20852. * An event triggered when active meshes evaluation is about to start
  20853. * @type {BABYLON.Observable}
  20854. */
  20855. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20856. /**
  20857. * An event triggered when active meshes evaluation is done
  20858. * @type {BABYLON.Observable}
  20859. */
  20860. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20861. /**
  20862. * An event triggered when particles rendering is about to start
  20863. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20864. * @type {BABYLON.Observable}
  20865. */
  20866. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20867. /**
  20868. * An event triggered when particles rendering is done
  20869. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20870. * @type {BABYLON.Observable}
  20871. */
  20872. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20873. /**
  20874. * An event triggered when sprites rendering is about to start
  20875. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20876. * @type {BABYLON.Observable}
  20877. */
  20878. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20879. /**
  20880. * An event triggered when sprites rendering is done
  20881. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20882. * @type {BABYLON.Observable}
  20883. */
  20884. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20885. /**
  20886. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  20887. * @type {BABYLON.Observable}
  20888. */
  20889. this.onDataLoadedObservable = new BABYLON.Observable();
  20890. /**
  20891. * An event triggered when a camera is created
  20892. * @type {BABYLON.Observable}
  20893. */
  20894. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20895. /**
  20896. * An event triggered when a camera is removed
  20897. * @type {BABYLON.Observable}
  20898. */
  20899. this.onCameraRemovedObservable = new BABYLON.Observable();
  20900. /**
  20901. * An event triggered when a light is created
  20902. * @type {BABYLON.Observable}
  20903. */
  20904. this.onNewLightAddedObservable = new BABYLON.Observable();
  20905. /**
  20906. * An event triggered when a light is removed
  20907. * @type {BABYLON.Observable}
  20908. */
  20909. this.onLightRemovedObservable = new BABYLON.Observable();
  20910. /**
  20911. * An event triggered when a geometry is created
  20912. * @type {BABYLON.Observable}
  20913. */
  20914. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20915. /**
  20916. * An event triggered when a geometry is removed
  20917. * @type {BABYLON.Observable}
  20918. */
  20919. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20920. /**
  20921. * An event triggered when a transform node is created
  20922. * @type {BABYLON.Observable}
  20923. */
  20924. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  20925. /**
  20926. * An event triggered when a transform node is removed
  20927. * @type {BABYLON.Observable}
  20928. */
  20929. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  20930. /**
  20931. * An event triggered when a mesh is created
  20932. * @type {BABYLON.Observable}
  20933. */
  20934. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20935. /**
  20936. * An event triggered when a mesh is removed
  20937. * @type {BABYLON.Observable}
  20938. */
  20939. this.onMeshRemovedObservable = new BABYLON.Observable();
  20940. /**
  20941. * An event triggered when render targets are about to be rendered
  20942. * Can happen multiple times per frame.
  20943. * @type {BABYLON.Observable}
  20944. */
  20945. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  20946. /**
  20947. * An event triggered when render targets were rendered.
  20948. * Can happen multiple times per frame.
  20949. * @type {BABYLON.Observable}
  20950. */
  20951. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  20952. /**
  20953. * An event triggered before calculating deterministic simulation step
  20954. * @type {BABYLON.Observable}
  20955. */
  20956. this.onBeforeStepObservable = new BABYLON.Observable();
  20957. /**
  20958. * An event triggered after calculating deterministic simulation step
  20959. * @type {BABYLON.Observable}
  20960. */
  20961. this.onAfterStepObservable = new BABYLON.Observable();
  20962. /**
  20963. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20964. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20965. * 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)
  20966. */
  20967. this.onRenderingGroupObservable = new BABYLON.Observable();
  20968. // Animations
  20969. this.animations = [];
  20970. /**
  20971. * 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).
  20972. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  20973. */
  20974. this.onPrePointerObservable = new BABYLON.Observable();
  20975. /**
  20976. * Observable event triggered each time an input event is received from the rendering canvas
  20977. */
  20978. this.onPointerObservable = new BABYLON.Observable();
  20979. this._meshPickProceed = false;
  20980. this._currentPickResult = null;
  20981. this._previousPickResult = null;
  20982. this._totalPointersPressed = 0;
  20983. this._doubleClickOccured = false;
  20984. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  20985. this.cameraToUseForPointers = null;
  20986. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20987. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20988. this._startingPointerTime = 0;
  20989. this._previousStartingPointerTime = 0;
  20990. // Deterministic lockstep
  20991. this._timeAccumulator = 0;
  20992. this._currentStepId = 0;
  20993. this._currentInternalStep = 0;
  20994. // Keyboard
  20995. /**
  20996. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  20997. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  20998. */
  20999. this.onPreKeyboardObservable = new BABYLON.Observable();
  21000. /**
  21001. * Observable event triggered each time an keyboard event is received from the hosting window
  21002. */
  21003. this.onKeyboardObservable = new BABYLON.Observable();
  21004. // Coordinate system
  21005. /**
  21006. * use right-handed coordinate system on this scene.
  21007. * @type {boolean}
  21008. */
  21009. this._useRightHandedSystem = false;
  21010. // Fog
  21011. this._fogEnabled = true;
  21012. this._fogMode = Scene.FOGMODE_NONE;
  21013. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21014. this.fogDensity = 0.1;
  21015. this.fogStart = 0;
  21016. this.fogEnd = 1000.0;
  21017. // Lights
  21018. /**
  21019. * is shadow enabled on this scene.
  21020. * @type {boolean}
  21021. */
  21022. this._shadowsEnabled = true;
  21023. /**
  21024. * is light enabled on this scene.
  21025. * @type {boolean}
  21026. */
  21027. this._lightsEnabled = true;
  21028. /**
  21029. * All of the lights added to this scene.
  21030. * @see BABYLON.Light
  21031. * @type {BABYLON.Light[]}
  21032. */
  21033. this.lights = new Array();
  21034. // Cameras
  21035. /** All of the cameras added to this scene. */
  21036. this.cameras = new Array();
  21037. /** All of the active cameras added to this scene. */
  21038. this.activeCameras = new Array();
  21039. // Meshes
  21040. /**
  21041. * All of the tranform nodes added to this scene.
  21042. * @see BABYLON.TransformNode
  21043. * @type {BABYLON.TransformNode[]}
  21044. */
  21045. this.transformNodes = new Array();
  21046. /**
  21047. * All of the (abstract) meshes added to this scene.
  21048. * @see BABYLON.AbstractMesh
  21049. * @type {BABYLON.AbstractMesh[]}
  21050. */
  21051. this.meshes = new Array();
  21052. /**
  21053. * All of the animation groups added to this scene.
  21054. * @see BABYLON.AnimationGroup
  21055. * @type {BABYLON.AnimationGroup[]}
  21056. */
  21057. this.animationGroups = new Array();
  21058. // Geometries
  21059. this._geometries = new Array();
  21060. this.materials = new Array();
  21061. this.multiMaterials = new Array();
  21062. // Textures
  21063. this._texturesEnabled = true;
  21064. this.textures = new Array();
  21065. // Particles
  21066. this.particlesEnabled = true;
  21067. this.particleSystems = new Array();
  21068. // Sprites
  21069. this.spritesEnabled = true;
  21070. this.spriteManagers = new Array();
  21071. /**
  21072. * The list of layers (background and foreground) of the scene.
  21073. */
  21074. this.layers = new Array();
  21075. /**
  21076. * The list of effect layers (highlights/glow) contained in the scene.
  21077. */
  21078. this.effectLayers = new Array();
  21079. // Skeletons
  21080. this._skeletonsEnabled = true;
  21081. this.skeletons = new Array();
  21082. // Morph targets
  21083. this.morphTargetManagers = new Array();
  21084. // Lens flares
  21085. this.lensFlaresEnabled = true;
  21086. this.lensFlareSystems = new Array();
  21087. // Collisions
  21088. this.collisionsEnabled = true;
  21089. /** Defines the gravity applied to this scene */
  21090. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21091. // Postprocesses
  21092. this.postProcesses = new Array();
  21093. this.postProcessesEnabled = true;
  21094. // Customs render targets
  21095. this.renderTargetsEnabled = true;
  21096. this.dumpNextRenderTargets = false;
  21097. this.customRenderTargets = new Array();
  21098. // Imported meshes
  21099. this.importedMeshesFiles = new Array();
  21100. // Probes
  21101. this.probesEnabled = true;
  21102. this.reflectionProbes = new Array();
  21103. this._actionManagers = new Array();
  21104. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21105. // Procedural textures
  21106. this.proceduralTexturesEnabled = true;
  21107. this._proceduralTextures = new Array();
  21108. this.soundTracks = new Array();
  21109. this._audioEnabled = true;
  21110. this._headphone = false;
  21111. // Performance counters
  21112. this._totalVertices = new BABYLON.PerfCounter();
  21113. this._activeIndices = new BABYLON.PerfCounter();
  21114. this._activeParticles = new BABYLON.PerfCounter();
  21115. this._activeBones = new BABYLON.PerfCounter();
  21116. this._animationTime = 0;
  21117. this.animationTimeScale = 1;
  21118. this._renderId = 0;
  21119. this._executeWhenReadyTimeoutId = -1;
  21120. this._intermediateRendering = false;
  21121. this._viewUpdateFlag = -1;
  21122. this._projectionUpdateFlag = -1;
  21123. this._alternateViewUpdateFlag = -1;
  21124. this._alternateProjectionUpdateFlag = -1;
  21125. this._toBeDisposed = new BABYLON.SmartArray(256);
  21126. this._activeRequests = new Array();
  21127. this._pendingData = new Array();
  21128. this._isDisposed = false;
  21129. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21130. this._activeMeshes = new BABYLON.SmartArray(256);
  21131. this._processedMaterials = new BABYLON.SmartArray(256);
  21132. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21133. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21134. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21135. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21136. this._activeAnimatables = new Array();
  21137. this._transformMatrix = BABYLON.Matrix.Zero();
  21138. this._useAlternateCameraConfiguration = false;
  21139. this._alternateRendering = false;
  21140. this.requireLightSorting = false;
  21141. this._activeMeshesFrozen = false;
  21142. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21143. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21144. this._engine.scenes.push(this);
  21145. this._uid = null;
  21146. this._renderingManager = new BABYLON.RenderingManager(this);
  21147. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21148. if (BABYLON.OutlineRenderer) {
  21149. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21150. }
  21151. if (BABYLON.Tools.IsWindowObjectExist()) {
  21152. this.attachControl();
  21153. }
  21154. //simplification queue
  21155. if (BABYLON.SimplificationQueue) {
  21156. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21157. }
  21158. //collision coordinator initialization. For now legacy per default.
  21159. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21160. // Uniform Buffer
  21161. this._createUbo();
  21162. // Default Image processing definition.
  21163. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21164. }
  21165. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21166. /** The fog is deactivated */
  21167. get: function () {
  21168. return Scene._FOGMODE_NONE;
  21169. },
  21170. enumerable: true,
  21171. configurable: true
  21172. });
  21173. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21174. /** The fog density is following an exponential function */
  21175. get: function () {
  21176. return Scene._FOGMODE_EXP;
  21177. },
  21178. enumerable: true,
  21179. configurable: true
  21180. });
  21181. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21182. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21183. get: function () {
  21184. return Scene._FOGMODE_EXP2;
  21185. },
  21186. enumerable: true,
  21187. configurable: true
  21188. });
  21189. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21190. /** The fog density is following a linear function. */
  21191. get: function () {
  21192. return Scene._FOGMODE_LINEAR;
  21193. },
  21194. enumerable: true,
  21195. configurable: true
  21196. });
  21197. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21198. /**
  21199. * Texture used in all pbr material as the reflection texture.
  21200. * As in the majority of the scene they are the same (exception for multi room and so on),
  21201. * this is easier to reference from here than from all the materials.
  21202. */
  21203. get: function () {
  21204. return this._environmentTexture;
  21205. },
  21206. /**
  21207. * Texture used in all pbr material as the reflection texture.
  21208. * As in the majority of the scene they are the same (exception for multi room and so on),
  21209. * this is easier to set here than in all the materials.
  21210. */
  21211. set: function (value) {
  21212. if (this._environmentTexture === value) {
  21213. return;
  21214. }
  21215. this._environmentTexture = value;
  21216. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21217. },
  21218. enumerable: true,
  21219. configurable: true
  21220. });
  21221. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21222. /**
  21223. * Default image processing configuration used either in the rendering
  21224. * Forward main pass or through the imageProcessingPostProcess if present.
  21225. * As in the majority of the scene they are the same (exception for multi camera),
  21226. * this is easier to reference from here than from all the materials and post process.
  21227. *
  21228. * No setter as we it is a shared configuration, you can set the values instead.
  21229. */
  21230. get: function () {
  21231. return this._imageProcessingConfiguration;
  21232. },
  21233. enumerable: true,
  21234. configurable: true
  21235. });
  21236. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21237. get: function () {
  21238. return this._forcePointsCloud;
  21239. },
  21240. set: function (value) {
  21241. if (this._forcePointsCloud === value) {
  21242. return;
  21243. }
  21244. this._forcePointsCloud = value;
  21245. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21246. },
  21247. enumerable: true,
  21248. configurable: true
  21249. });
  21250. Object.defineProperty(Scene.prototype, "onDispose", {
  21251. /** A function to be executed when this scene is disposed. */
  21252. set: function (callback) {
  21253. if (this._onDisposeObserver) {
  21254. this.onDisposeObservable.remove(this._onDisposeObserver);
  21255. }
  21256. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21257. },
  21258. enumerable: true,
  21259. configurable: true
  21260. });
  21261. Object.defineProperty(Scene.prototype, "beforeRender", {
  21262. /** A function to be executed before rendering this scene */
  21263. set: function (callback) {
  21264. if (this._onBeforeRenderObserver) {
  21265. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21266. }
  21267. if (callback) {
  21268. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21269. }
  21270. },
  21271. enumerable: true,
  21272. configurable: true
  21273. });
  21274. Object.defineProperty(Scene.prototype, "afterRender", {
  21275. /** A function to be executed after rendering this scene */
  21276. set: function (callback) {
  21277. if (this._onAfterRenderObserver) {
  21278. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21279. }
  21280. if (callback) {
  21281. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21282. }
  21283. },
  21284. enumerable: true,
  21285. configurable: true
  21286. });
  21287. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21288. set: function (callback) {
  21289. if (this._onBeforeCameraRenderObserver) {
  21290. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21291. }
  21292. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21293. },
  21294. enumerable: true,
  21295. configurable: true
  21296. });
  21297. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21298. set: function (callback) {
  21299. if (this._onAfterCameraRenderObserver) {
  21300. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21301. }
  21302. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21303. },
  21304. enumerable: true,
  21305. configurable: true
  21306. });
  21307. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21308. get: function () {
  21309. if (!this._gamepadManager) {
  21310. this._gamepadManager = new BABYLON.GamepadManager(this);
  21311. }
  21312. return this._gamepadManager;
  21313. },
  21314. enumerable: true,
  21315. configurable: true
  21316. });
  21317. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21318. get: function () {
  21319. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21320. },
  21321. enumerable: true,
  21322. configurable: true
  21323. });
  21324. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21325. get: function () {
  21326. return this._useRightHandedSystem;
  21327. },
  21328. set: function (value) {
  21329. if (this._useRightHandedSystem === value) {
  21330. return;
  21331. }
  21332. this._useRightHandedSystem = value;
  21333. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21334. },
  21335. enumerable: true,
  21336. configurable: true
  21337. });
  21338. Scene.prototype.setStepId = function (newStepId) {
  21339. this._currentStepId = newStepId;
  21340. };
  21341. ;
  21342. Scene.prototype.getStepId = function () {
  21343. return this._currentStepId;
  21344. };
  21345. ;
  21346. Scene.prototype.getInternalStep = function () {
  21347. return this._currentInternalStep;
  21348. };
  21349. ;
  21350. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21351. get: function () {
  21352. return this._fogEnabled;
  21353. },
  21354. /**
  21355. * is fog enabled on this scene.
  21356. */
  21357. set: function (value) {
  21358. if (this._fogEnabled === value) {
  21359. return;
  21360. }
  21361. this._fogEnabled = value;
  21362. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21363. },
  21364. enumerable: true,
  21365. configurable: true
  21366. });
  21367. Object.defineProperty(Scene.prototype, "fogMode", {
  21368. get: function () {
  21369. return this._fogMode;
  21370. },
  21371. set: function (value) {
  21372. if (this._fogMode === value) {
  21373. return;
  21374. }
  21375. this._fogMode = value;
  21376. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21377. },
  21378. enumerable: true,
  21379. configurable: true
  21380. });
  21381. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21382. get: function () {
  21383. return this._shadowsEnabled;
  21384. },
  21385. set: function (value) {
  21386. if (this._shadowsEnabled === value) {
  21387. return;
  21388. }
  21389. this._shadowsEnabled = value;
  21390. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21391. },
  21392. enumerable: true,
  21393. configurable: true
  21394. });
  21395. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21396. get: function () {
  21397. return this._lightsEnabled;
  21398. },
  21399. set: function (value) {
  21400. if (this._lightsEnabled === value) {
  21401. return;
  21402. }
  21403. this._lightsEnabled = value;
  21404. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21405. },
  21406. enumerable: true,
  21407. configurable: true
  21408. });
  21409. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21410. /** The default material used on meshes when no material is affected */
  21411. get: function () {
  21412. if (!this._defaultMaterial) {
  21413. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21414. }
  21415. return this._defaultMaterial;
  21416. },
  21417. /** The default material used on meshes when no material is affected */
  21418. set: function (value) {
  21419. this._defaultMaterial = value;
  21420. },
  21421. enumerable: true,
  21422. configurable: true
  21423. });
  21424. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21425. get: function () {
  21426. return this._texturesEnabled;
  21427. },
  21428. set: function (value) {
  21429. if (this._texturesEnabled === value) {
  21430. return;
  21431. }
  21432. this._texturesEnabled = value;
  21433. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21434. },
  21435. enumerable: true,
  21436. configurable: true
  21437. });
  21438. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21439. get: function () {
  21440. return this._skeletonsEnabled;
  21441. },
  21442. set: function (value) {
  21443. if (this._skeletonsEnabled === value) {
  21444. return;
  21445. }
  21446. this._skeletonsEnabled = value;
  21447. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21448. },
  21449. enumerable: true,
  21450. configurable: true
  21451. });
  21452. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21453. get: function () {
  21454. if (!this._postProcessRenderPipelineManager) {
  21455. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21456. }
  21457. return this._postProcessRenderPipelineManager;
  21458. },
  21459. enumerable: true,
  21460. configurable: true
  21461. });
  21462. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21463. get: function () {
  21464. if (!this._mainSoundTrack) {
  21465. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21466. }
  21467. return this._mainSoundTrack;
  21468. },
  21469. enumerable: true,
  21470. configurable: true
  21471. });
  21472. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21473. get: function () {
  21474. return this._alternateRendering;
  21475. },
  21476. enumerable: true,
  21477. configurable: true
  21478. });
  21479. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21480. get: function () {
  21481. return this._frustumPlanes;
  21482. },
  21483. enumerable: true,
  21484. configurable: true
  21485. });
  21486. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21487. /**
  21488. * Gets the current geometry buffer associated to the scene.
  21489. */
  21490. get: function () {
  21491. return this._geometryBufferRenderer;
  21492. },
  21493. /**
  21494. * Sets the current geometry buffer for the scene.
  21495. */
  21496. set: function (geometryBufferRenderer) {
  21497. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21498. this._geometryBufferRenderer = geometryBufferRenderer;
  21499. }
  21500. },
  21501. enumerable: true,
  21502. configurable: true
  21503. });
  21504. Object.defineProperty(Scene.prototype, "debugLayer", {
  21505. // Properties
  21506. get: function () {
  21507. if (!this._debugLayer) {
  21508. this._debugLayer = new BABYLON.DebugLayer(this);
  21509. }
  21510. return this._debugLayer;
  21511. },
  21512. enumerable: true,
  21513. configurable: true
  21514. });
  21515. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21516. get: function () {
  21517. return this._workerCollisions;
  21518. },
  21519. set: function (enabled) {
  21520. if (!BABYLON.CollisionCoordinatorLegacy) {
  21521. return;
  21522. }
  21523. enabled = (enabled && !!Worker);
  21524. this._workerCollisions = enabled;
  21525. if (this.collisionCoordinator) {
  21526. this.collisionCoordinator.destroy();
  21527. }
  21528. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21529. this.collisionCoordinator.init(this);
  21530. },
  21531. enumerable: true,
  21532. configurable: true
  21533. });
  21534. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21535. get: function () {
  21536. return this._selectionOctree;
  21537. },
  21538. enumerable: true,
  21539. configurable: true
  21540. });
  21541. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21542. /**
  21543. * The mesh that is currently under the pointer.
  21544. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21545. */
  21546. get: function () {
  21547. return this._pointerOverMesh;
  21548. },
  21549. enumerable: true,
  21550. configurable: true
  21551. });
  21552. Object.defineProperty(Scene.prototype, "pointerX", {
  21553. /**
  21554. * Current on-screen X position of the pointer
  21555. * @return {number} X position of the pointer
  21556. */
  21557. get: function () {
  21558. return this._pointerX;
  21559. },
  21560. enumerable: true,
  21561. configurable: true
  21562. });
  21563. Object.defineProperty(Scene.prototype, "pointerY", {
  21564. /**
  21565. * Current on-screen Y position of the pointer
  21566. * @return {number} Y position of the pointer
  21567. */
  21568. get: function () {
  21569. return this._pointerY;
  21570. },
  21571. enumerable: true,
  21572. configurable: true
  21573. });
  21574. Scene.prototype.getCachedMaterial = function () {
  21575. return this._cachedMaterial;
  21576. };
  21577. Scene.prototype.getCachedEffect = function () {
  21578. return this._cachedEffect;
  21579. };
  21580. Scene.prototype.getCachedVisibility = function () {
  21581. return this._cachedVisibility;
  21582. };
  21583. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21584. if (visibility === void 0) { visibility = 1; }
  21585. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21586. };
  21587. Scene.prototype.getBoundingBoxRenderer = function () {
  21588. if (!this._boundingBoxRenderer) {
  21589. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21590. }
  21591. return this._boundingBoxRenderer;
  21592. };
  21593. Scene.prototype.getOutlineRenderer = function () {
  21594. return this._outlineRenderer;
  21595. };
  21596. Scene.prototype.getEngine = function () {
  21597. return this._engine;
  21598. };
  21599. Scene.prototype.getTotalVertices = function () {
  21600. return this._totalVertices.current;
  21601. };
  21602. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21603. get: function () {
  21604. return this._totalVertices;
  21605. },
  21606. enumerable: true,
  21607. configurable: true
  21608. });
  21609. Scene.prototype.getActiveIndices = function () {
  21610. return this._activeIndices.current;
  21611. };
  21612. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21613. get: function () {
  21614. return this._activeIndices;
  21615. },
  21616. enumerable: true,
  21617. configurable: true
  21618. });
  21619. Scene.prototype.getActiveParticles = function () {
  21620. return this._activeParticles.current;
  21621. };
  21622. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21623. get: function () {
  21624. return this._activeParticles;
  21625. },
  21626. enumerable: true,
  21627. configurable: true
  21628. });
  21629. Scene.prototype.getActiveBones = function () {
  21630. return this._activeBones.current;
  21631. };
  21632. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  21633. get: function () {
  21634. return this._activeBones;
  21635. },
  21636. enumerable: true,
  21637. configurable: true
  21638. });
  21639. // Stats
  21640. Scene.prototype.getInterFramePerfCounter = function () {
  21641. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21642. return 0;
  21643. };
  21644. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  21645. get: function () {
  21646. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21647. return null;
  21648. },
  21649. enumerable: true,
  21650. configurable: true
  21651. });
  21652. Scene.prototype.getLastFrameDuration = function () {
  21653. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  21654. return 0;
  21655. };
  21656. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  21657. get: function () {
  21658. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21659. return null;
  21660. },
  21661. enumerable: true,
  21662. configurable: true
  21663. });
  21664. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  21665. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  21666. return 0;
  21667. };
  21668. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  21669. get: function () {
  21670. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21671. return null;
  21672. },
  21673. enumerable: true,
  21674. configurable: true
  21675. });
  21676. Scene.prototype.getActiveMeshes = function () {
  21677. return this._activeMeshes;
  21678. };
  21679. Scene.prototype.getRenderTargetsDuration = function () {
  21680. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  21681. return 0;
  21682. };
  21683. Scene.prototype.getRenderDuration = function () {
  21684. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  21685. return 0;
  21686. };
  21687. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  21688. get: function () {
  21689. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21690. return null;
  21691. },
  21692. enumerable: true,
  21693. configurable: true
  21694. });
  21695. Scene.prototype.getParticlesDuration = function () {
  21696. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  21697. return 0;
  21698. };
  21699. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  21700. get: function () {
  21701. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21702. return null;
  21703. },
  21704. enumerable: true,
  21705. configurable: true
  21706. });
  21707. Scene.prototype.getSpritesDuration = function () {
  21708. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  21709. return 0;
  21710. };
  21711. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  21712. get: function () {
  21713. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  21714. return null;
  21715. },
  21716. enumerable: true,
  21717. configurable: true
  21718. });
  21719. Scene.prototype.getAnimationRatio = function () {
  21720. return this._animationRatio;
  21721. };
  21722. Scene.prototype.getRenderId = function () {
  21723. return this._renderId;
  21724. };
  21725. Scene.prototype.incrementRenderId = function () {
  21726. this._renderId++;
  21727. };
  21728. Scene.prototype._updatePointerPosition = function (evt) {
  21729. var canvasRect = this._engine.getRenderingCanvasClientRect();
  21730. if (!canvasRect) {
  21731. return;
  21732. }
  21733. this._pointerX = evt.clientX - canvasRect.left;
  21734. this._pointerY = evt.clientY - canvasRect.top;
  21735. this._unTranslatedPointerX = this._pointerX;
  21736. this._unTranslatedPointerY = this._pointerY;
  21737. };
  21738. Scene.prototype._createUbo = function () {
  21739. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21740. this._sceneUbo.addUniform("viewProjection", 16);
  21741. this._sceneUbo.addUniform("view", 16);
  21742. };
  21743. Scene.prototype._createAlternateUbo = function () {
  21744. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21745. this._alternateSceneUbo.addUniform("viewProjection", 16);
  21746. this._alternateSceneUbo.addUniform("view", 16);
  21747. };
  21748. // Pointers handling
  21749. /**
  21750. * Use this method to simulate a pointer move on a mesh
  21751. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21752. */
  21753. Scene.prototype.simulatePointerMove = function (pickResult) {
  21754. var evt = new PointerEvent("pointermove");
  21755. return this._processPointerMove(pickResult, evt);
  21756. };
  21757. Scene.prototype._processPointerMove = function (pickResult, evt) {
  21758. var canvas = this._engine.getRenderingCanvas();
  21759. if (!canvas) {
  21760. return this;
  21761. }
  21762. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21763. this.setPointerOverSprite(null);
  21764. this.setPointerOverMesh(pickResult.pickedMesh);
  21765. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  21766. if (this._pointerOverMesh.actionManager.hoverCursor) {
  21767. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  21768. }
  21769. else {
  21770. canvas.style.cursor = this.hoverCursor;
  21771. }
  21772. }
  21773. else {
  21774. canvas.style.cursor = this.defaultCursor;
  21775. }
  21776. }
  21777. else {
  21778. this.setPointerOverMesh(null);
  21779. // Sprites
  21780. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  21781. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21782. this.setPointerOverSprite(pickResult.pickedSprite);
  21783. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  21784. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  21785. }
  21786. else {
  21787. canvas.style.cursor = this.hoverCursor;
  21788. }
  21789. }
  21790. else {
  21791. this.setPointerOverSprite(null);
  21792. // Restore pointer
  21793. canvas.style.cursor = this.defaultCursor;
  21794. }
  21795. }
  21796. if (pickResult) {
  21797. if (this.onPointerMove) {
  21798. this.onPointerMove(evt, pickResult);
  21799. }
  21800. if (this.onPointerObservable.hasObservers()) {
  21801. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21802. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21803. this.onPointerObservable.notifyObservers(pi, type);
  21804. }
  21805. }
  21806. return this;
  21807. };
  21808. /**
  21809. * Use this method to simulate a pointer down on a mesh
  21810. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21811. */
  21812. Scene.prototype.simulatePointerDown = function (pickResult) {
  21813. var evt = new PointerEvent("pointerdown");
  21814. return this._processPointerDown(pickResult, evt);
  21815. };
  21816. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21817. var _this = this;
  21818. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21819. this._pickedDownMesh = pickResult.pickedMesh;
  21820. var actionManager = pickResult.pickedMesh.actionManager;
  21821. if (actionManager) {
  21822. if (actionManager.hasPickTriggers) {
  21823. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21824. switch (evt.button) {
  21825. case 0:
  21826. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21827. break;
  21828. case 1:
  21829. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21830. break;
  21831. case 2:
  21832. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21833. break;
  21834. }
  21835. }
  21836. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21837. window.setTimeout(function () {
  21838. 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);
  21839. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21840. if (_this._totalPointersPressed !== 0 &&
  21841. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21842. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21843. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21844. _this._startingPointerTime = 0;
  21845. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21846. }
  21847. }
  21848. }, Scene.LongPressDelay);
  21849. }
  21850. }
  21851. }
  21852. if (pickResult) {
  21853. if (this.onPointerDown) {
  21854. this.onPointerDown(evt, pickResult);
  21855. }
  21856. if (this.onPointerObservable.hasObservers()) {
  21857. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21858. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21859. this.onPointerObservable.notifyObservers(pi, type);
  21860. }
  21861. }
  21862. return this;
  21863. };
  21864. /**
  21865. * Use this method to simulate a pointer up on a mesh
  21866. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21867. */
  21868. Scene.prototype.simulatePointerUp = function (pickResult) {
  21869. var evt = new PointerEvent("pointerup");
  21870. var clickInfo = new ClickInfo();
  21871. clickInfo.singleClick = true;
  21872. clickInfo.ignore = true;
  21873. return this._processPointerUp(pickResult, evt, clickInfo);
  21874. };
  21875. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21876. if (pickResult && pickResult && pickResult.pickedMesh) {
  21877. this._pickedUpMesh = pickResult.pickedMesh;
  21878. if (this._pickedDownMesh === this._pickedUpMesh) {
  21879. if (this.onPointerPick) {
  21880. this.onPointerPick(evt, pickResult);
  21881. }
  21882. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21883. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21884. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21885. this.onPointerObservable.notifyObservers(pi, type);
  21886. }
  21887. }
  21888. if (pickResult.pickedMesh.actionManager) {
  21889. if (clickInfo.ignore) {
  21890. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21891. }
  21892. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  21893. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21894. }
  21895. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21896. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21897. }
  21898. }
  21899. }
  21900. if (this._pickedDownMesh &&
  21901. this._pickedDownMesh.actionManager &&
  21902. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21903. this._pickedDownMesh !== this._pickedUpMesh) {
  21904. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21905. }
  21906. if (this.onPointerUp) {
  21907. this.onPointerUp(evt, pickResult);
  21908. }
  21909. if (this.onPointerObservable.hasObservers()) {
  21910. if (!clickInfo.ignore) {
  21911. if (!clickInfo.hasSwiped) {
  21912. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21913. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21914. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21915. this.onPointerObservable.notifyObservers(pi, type);
  21916. }
  21917. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21918. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21919. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21920. this.onPointerObservable.notifyObservers(pi, type);
  21921. }
  21922. }
  21923. }
  21924. else {
  21925. var type = BABYLON.PointerEventTypes.POINTERUP;
  21926. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21927. this.onPointerObservable.notifyObservers(pi, type);
  21928. }
  21929. }
  21930. return this;
  21931. };
  21932. /**
  21933. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21934. * @param attachUp defines if you want to attach events to pointerup
  21935. * @param attachDown defines if you want to attach events to pointerdown
  21936. * @param attachMove defines if you want to attach events to pointermove
  21937. */
  21938. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21939. var _this = this;
  21940. if (attachUp === void 0) { attachUp = true; }
  21941. if (attachDown === void 0) { attachDown = true; }
  21942. if (attachMove === void 0) { attachMove = true; }
  21943. this._initActionManager = function (act, clickInfo) {
  21944. if (!_this._meshPickProceed) {
  21945. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21946. _this._currentPickResult = pickResult;
  21947. if (pickResult) {
  21948. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21949. }
  21950. _this._meshPickProceed = true;
  21951. }
  21952. return act;
  21953. };
  21954. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21955. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21956. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21957. btn !== _this._previousButtonPressed) {
  21958. _this._doubleClickOccured = false;
  21959. clickInfo.singleClick = true;
  21960. clickInfo.ignore = false;
  21961. cb(clickInfo, _this._currentPickResult);
  21962. }
  21963. };
  21964. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21965. var clickInfo = new ClickInfo();
  21966. _this._currentPickResult = null;
  21967. var act = null;
  21968. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  21969. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  21970. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21971. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  21972. act = _this._initActionManager(act, clickInfo);
  21973. if (act)
  21974. checkPicking = act.hasPickTriggers;
  21975. }
  21976. if (checkPicking) {
  21977. var btn = evt.button;
  21978. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21979. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21980. if (!clickInfo.hasSwiped) {
  21981. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21982. if (!checkSingleClickImmediately) {
  21983. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  21984. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21985. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21986. act = _this._initActionManager(act, clickInfo);
  21987. if (act)
  21988. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21989. }
  21990. }
  21991. if (checkSingleClickImmediately) {
  21992. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21993. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21994. btn !== _this._previousButtonPressed) {
  21995. clickInfo.singleClick = true;
  21996. cb(clickInfo, _this._currentPickResult);
  21997. }
  21998. }
  21999. else {
  22000. // wait that no double click has been raised during the double click delay
  22001. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22002. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22003. }
  22004. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22005. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22006. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22007. act = _this._initActionManager(act, clickInfo);
  22008. if (act)
  22009. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22010. }
  22011. if (checkDoubleClick) {
  22012. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22013. if (btn === _this._previousButtonPressed &&
  22014. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22015. !_this._doubleClickOccured) {
  22016. // pointer has not moved for 2 clicks, it's a double click
  22017. if (!clickInfo.hasSwiped &&
  22018. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22019. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22020. _this._previousStartingPointerTime = 0;
  22021. _this._doubleClickOccured = true;
  22022. clickInfo.doubleClick = true;
  22023. clickInfo.ignore = false;
  22024. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22025. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22026. }
  22027. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22028. cb(clickInfo, _this._currentPickResult);
  22029. }
  22030. else {
  22031. _this._doubleClickOccured = false;
  22032. _this._previousStartingPointerTime = _this._startingPointerTime;
  22033. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22034. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22035. _this._previousButtonPressed = btn;
  22036. if (Scene.ExclusiveDoubleClickMode) {
  22037. if (_this._previousDelayedSimpleClickTimeout) {
  22038. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22039. }
  22040. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22041. cb(clickInfo, _this._previousPickResult);
  22042. }
  22043. else {
  22044. cb(clickInfo, _this._currentPickResult);
  22045. }
  22046. }
  22047. }
  22048. else {
  22049. _this._doubleClickOccured = false;
  22050. _this._previousStartingPointerTime = _this._startingPointerTime;
  22051. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22052. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22053. _this._previousButtonPressed = btn;
  22054. }
  22055. }
  22056. }
  22057. }
  22058. clickInfo.ignore = true;
  22059. cb(clickInfo, _this._currentPickResult);
  22060. };
  22061. this._spritePredicate = function (sprite) {
  22062. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22063. };
  22064. this._onPointerMove = function (evt) {
  22065. _this._updatePointerPosition(evt);
  22066. // PreObservable support
  22067. if (_this.onPrePointerObservable.hasObservers()) {
  22068. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22069. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22070. _this.onPrePointerObservable.notifyObservers(pi, type);
  22071. if (pi.skipOnPointerObservable) {
  22072. return;
  22073. }
  22074. }
  22075. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22076. return;
  22077. }
  22078. if (!_this.pointerMovePredicate) {
  22079. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22080. }
  22081. // Meshes
  22082. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22083. _this._processPointerMove(pickResult, evt);
  22084. };
  22085. this._onPointerDown = function (evt) {
  22086. _this._totalPointersPressed++;
  22087. _this._pickedDownMesh = null;
  22088. _this._meshPickProceed = false;
  22089. _this._updatePointerPosition(evt);
  22090. if (_this.preventDefaultOnPointerDown && canvas) {
  22091. evt.preventDefault();
  22092. canvas.focus();
  22093. }
  22094. // PreObservable support
  22095. if (_this.onPrePointerObservable.hasObservers()) {
  22096. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22097. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22098. _this.onPrePointerObservable.notifyObservers(pi, type);
  22099. if (pi.skipOnPointerObservable) {
  22100. return;
  22101. }
  22102. }
  22103. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22104. return;
  22105. }
  22106. _this._startingPointerPosition.x = _this._pointerX;
  22107. _this._startingPointerPosition.y = _this._pointerY;
  22108. _this._startingPointerTime = new Date().getTime();
  22109. if (!_this.pointerDownPredicate) {
  22110. _this.pointerDownPredicate = function (mesh) {
  22111. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22112. };
  22113. }
  22114. // Meshes
  22115. _this._pickedDownMesh = null;
  22116. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22117. _this._processPointerDown(pickResult, evt);
  22118. // Sprites
  22119. _this._pickedDownSprite = null;
  22120. if (_this.spriteManagers.length > 0) {
  22121. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22122. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22123. if (pickResult.pickedSprite.actionManager) {
  22124. _this._pickedDownSprite = pickResult.pickedSprite;
  22125. switch (evt.button) {
  22126. case 0:
  22127. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22128. break;
  22129. case 1:
  22130. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22131. break;
  22132. case 2:
  22133. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22134. break;
  22135. }
  22136. if (pickResult.pickedSprite.actionManager) {
  22137. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22138. }
  22139. }
  22140. }
  22141. }
  22142. };
  22143. this._onPointerUp = function (evt) {
  22144. if (_this._totalPointersPressed === 0) {
  22145. return; // So we need to test it the pointer down was pressed before.
  22146. }
  22147. _this._totalPointersPressed--;
  22148. _this._pickedUpMesh = null;
  22149. _this._meshPickProceed = false;
  22150. _this._updatePointerPosition(evt);
  22151. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22152. // PreObservable support
  22153. if (_this.onPrePointerObservable.hasObservers()) {
  22154. if (!clickInfo.ignore) {
  22155. if (!clickInfo.hasSwiped) {
  22156. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22157. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22158. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22159. _this.onPrePointerObservable.notifyObservers(pi, type);
  22160. if (pi.skipOnPointerObservable) {
  22161. return;
  22162. }
  22163. }
  22164. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22165. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22166. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22167. _this.onPrePointerObservable.notifyObservers(pi, type);
  22168. if (pi.skipOnPointerObservable) {
  22169. return;
  22170. }
  22171. }
  22172. }
  22173. }
  22174. else {
  22175. var type = BABYLON.PointerEventTypes.POINTERUP;
  22176. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22177. _this.onPrePointerObservable.notifyObservers(pi, type);
  22178. if (pi.skipOnPointerObservable) {
  22179. return;
  22180. }
  22181. }
  22182. }
  22183. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22184. return;
  22185. }
  22186. if (!_this.pointerUpPredicate) {
  22187. _this.pointerUpPredicate = function (mesh) {
  22188. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22189. };
  22190. }
  22191. // Meshes
  22192. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22193. _this._initActionManager(null, clickInfo);
  22194. }
  22195. if (!pickResult) {
  22196. pickResult = _this._currentPickResult;
  22197. }
  22198. _this._processPointerUp(pickResult, evt, clickInfo);
  22199. // Sprites
  22200. if (_this.spriteManagers.length > 0) {
  22201. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22202. if (spritePickResult) {
  22203. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22204. if (spritePickResult.pickedSprite.actionManager) {
  22205. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22206. if (spritePickResult.pickedSprite.actionManager) {
  22207. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22208. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22209. }
  22210. }
  22211. }
  22212. }
  22213. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22214. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22215. }
  22216. }
  22217. }
  22218. _this._previousPickResult = _this._currentPickResult;
  22219. });
  22220. };
  22221. this._onKeyDown = function (evt) {
  22222. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22223. if (_this.onPreKeyboardObservable.hasObservers()) {
  22224. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22225. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22226. if (pi.skipOnPointerObservable) {
  22227. return;
  22228. }
  22229. }
  22230. if (_this.onKeyboardObservable.hasObservers()) {
  22231. var pi = new BABYLON.KeyboardInfo(type, evt);
  22232. _this.onKeyboardObservable.notifyObservers(pi, type);
  22233. }
  22234. if (_this.actionManager) {
  22235. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22236. }
  22237. };
  22238. this._onKeyUp = function (evt) {
  22239. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22240. if (_this.onPreKeyboardObservable.hasObservers()) {
  22241. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22242. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22243. if (pi.skipOnPointerObservable) {
  22244. return;
  22245. }
  22246. }
  22247. if (_this.onKeyboardObservable.hasObservers()) {
  22248. var pi = new BABYLON.KeyboardInfo(type, evt);
  22249. _this.onKeyboardObservable.notifyObservers(pi, type);
  22250. }
  22251. if (_this.actionManager) {
  22252. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22253. }
  22254. };
  22255. var engine = this.getEngine();
  22256. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22257. if (!canvas) {
  22258. return;
  22259. }
  22260. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22261. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22262. });
  22263. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22264. if (!canvas) {
  22265. return;
  22266. }
  22267. canvas.removeEventListener("keydown", _this._onKeyDown);
  22268. canvas.removeEventListener("keyup", _this._onKeyUp);
  22269. });
  22270. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22271. var canvas = this._engine.getRenderingCanvas();
  22272. if (!canvas) {
  22273. return;
  22274. }
  22275. if (attachMove) {
  22276. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22277. // Wheel
  22278. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22279. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22280. }
  22281. if (attachDown) {
  22282. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22283. }
  22284. if (attachUp) {
  22285. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22286. }
  22287. canvas.tabIndex = 1;
  22288. };
  22289. Scene.prototype.detachControl = function () {
  22290. var engine = this.getEngine();
  22291. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22292. var canvas = engine.getRenderingCanvas();
  22293. if (!canvas) {
  22294. return;
  22295. }
  22296. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22297. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22298. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22299. if (this._onCanvasBlurObserver) {
  22300. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22301. }
  22302. if (this._onCanvasFocusObserver) {
  22303. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22304. }
  22305. // Wheel
  22306. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22307. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22308. // Keyboard
  22309. canvas.removeEventListener("keydown", this._onKeyDown);
  22310. canvas.removeEventListener("keyup", this._onKeyUp);
  22311. // Observables
  22312. this.onKeyboardObservable.clear();
  22313. this.onPreKeyboardObservable.clear();
  22314. this.onPointerObservable.clear();
  22315. this.onPrePointerObservable.clear();
  22316. };
  22317. /**
  22318. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22319. * Delay loaded resources are not taking in account
  22320. * @return true if all required resources are ready
  22321. */
  22322. Scene.prototype.isReady = function () {
  22323. if (this._isDisposed) {
  22324. return false;
  22325. }
  22326. if (this._pendingData.length > 0) {
  22327. return false;
  22328. }
  22329. var index;
  22330. var engine = this.getEngine();
  22331. // Geometries
  22332. for (index = 0; index < this._geometries.length; index++) {
  22333. var geometry = this._geometries[index];
  22334. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22335. return false;
  22336. }
  22337. }
  22338. // Meshes
  22339. for (index = 0; index < this.meshes.length; index++) {
  22340. var mesh = this.meshes[index];
  22341. if (!mesh.isEnabled()) {
  22342. continue;
  22343. }
  22344. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22345. continue;
  22346. }
  22347. if (!mesh.isReady()) {
  22348. return false;
  22349. }
  22350. // Effect layers
  22351. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22352. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22353. var layer = _a[_i];
  22354. if (!layer.hasMesh(mesh)) {
  22355. continue;
  22356. }
  22357. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22358. var subMesh = _c[_b];
  22359. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22360. return false;
  22361. }
  22362. }
  22363. }
  22364. }
  22365. return true;
  22366. };
  22367. Scene.prototype.resetCachedMaterial = function () {
  22368. this._cachedMaterial = null;
  22369. this._cachedEffect = null;
  22370. this._cachedVisibility = null;
  22371. };
  22372. Scene.prototype.registerBeforeRender = function (func) {
  22373. this.onBeforeRenderObservable.add(func);
  22374. };
  22375. Scene.prototype.unregisterBeforeRender = function (func) {
  22376. this.onBeforeRenderObservable.removeCallback(func);
  22377. };
  22378. Scene.prototype.registerAfterRender = function (func) {
  22379. this.onAfterRenderObservable.add(func);
  22380. };
  22381. Scene.prototype.unregisterAfterRender = function (func) {
  22382. this.onAfterRenderObservable.removeCallback(func);
  22383. };
  22384. Scene.prototype._executeOnceBeforeRender = function (func) {
  22385. var _this = this;
  22386. var execFunc = function () {
  22387. func();
  22388. setTimeout(function () {
  22389. _this.unregisterBeforeRender(execFunc);
  22390. });
  22391. };
  22392. this.registerBeforeRender(execFunc);
  22393. };
  22394. /**
  22395. * The provided function will run before render once and will be disposed afterwards.
  22396. * A timeout delay can be provided so that the function will be executed in N ms.
  22397. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22398. * @param func The function to be executed.
  22399. * @param timeout optional delay in ms
  22400. */
  22401. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22402. var _this = this;
  22403. if (timeout !== undefined) {
  22404. setTimeout(function () {
  22405. _this._executeOnceBeforeRender(func);
  22406. }, timeout);
  22407. }
  22408. else {
  22409. this._executeOnceBeforeRender(func);
  22410. }
  22411. };
  22412. Scene.prototype._addPendingData = function (data) {
  22413. this._pendingData.push(data);
  22414. };
  22415. Scene.prototype._removePendingData = function (data) {
  22416. var wasLoading = this.isLoading;
  22417. var index = this._pendingData.indexOf(data);
  22418. if (index !== -1) {
  22419. this._pendingData.splice(index, 1);
  22420. }
  22421. if (wasLoading && !this.isLoading) {
  22422. this.onDataLoadedObservable.notifyObservers(this);
  22423. }
  22424. };
  22425. Scene.prototype.getWaitingItemsCount = function () {
  22426. return this._pendingData.length;
  22427. };
  22428. Object.defineProperty(Scene.prototype, "isLoading", {
  22429. get: function () {
  22430. return this._pendingData.length > 0;
  22431. },
  22432. enumerable: true,
  22433. configurable: true
  22434. });
  22435. /**
  22436. * Registers a function to be executed when the scene is ready.
  22437. * @param {Function} func - the function to be executed.
  22438. */
  22439. Scene.prototype.executeWhenReady = function (func) {
  22440. var _this = this;
  22441. this.onReadyObservable.add(func);
  22442. if (this._executeWhenReadyTimeoutId !== -1) {
  22443. return;
  22444. }
  22445. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22446. _this._checkIsReady();
  22447. }, 150);
  22448. };
  22449. /**
  22450. * Returns a promise that resolves when the scene is ready.
  22451. * @returns A promise that resolves when the scene is ready.
  22452. */
  22453. Scene.prototype.whenReadyAsync = function () {
  22454. var _this = this;
  22455. return new Promise(function (resolve) {
  22456. _this.executeWhenReady(function () {
  22457. resolve();
  22458. });
  22459. });
  22460. };
  22461. Scene.prototype._checkIsReady = function () {
  22462. var _this = this;
  22463. if (this.isReady()) {
  22464. this.onReadyObservable.notifyObservers(this);
  22465. this.onReadyObservable.clear();
  22466. this._executeWhenReadyTimeoutId = -1;
  22467. return;
  22468. }
  22469. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22470. _this._checkIsReady();
  22471. }, 150);
  22472. };
  22473. // Animations
  22474. /**
  22475. * Will start the animation sequence of a given target
  22476. * @param target - the target
  22477. * @param {number} from - from which frame should animation start
  22478. * @param {number} to - till which frame should animation run.
  22479. * @param {boolean} [loop] - should the animation loop
  22480. * @param {number} [speedRatio] - the speed in which to run the animation
  22481. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22482. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22483. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22484. * See BABYLON.Animatable
  22485. */
  22486. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22487. if (speedRatio === void 0) { speedRatio = 1.0; }
  22488. if (from > to && speedRatio > 0) {
  22489. speedRatio *= -1;
  22490. }
  22491. this.stopAnimation(target);
  22492. if (!animatable) {
  22493. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22494. }
  22495. // Local animations
  22496. if (target.animations) {
  22497. animatable.appendAnimations(target, target.animations);
  22498. }
  22499. // Children animations
  22500. if (target.getAnimatables) {
  22501. var animatables = target.getAnimatables();
  22502. for (var index = 0; index < animatables.length; index++) {
  22503. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22504. }
  22505. }
  22506. animatable.reset();
  22507. return animatable;
  22508. };
  22509. /**
  22510. * Begin a new animation on a given node
  22511. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22512. * @param {BABYLON.Animation[]} defines the list of animations to start
  22513. * @param {number} from defines the initial value
  22514. * @param {number} to defines the final value
  22515. * @param {boolean} loop defines if you want animation to loop (off by default)
  22516. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22517. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22518. * @returns the list of created animatables
  22519. */
  22520. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22521. if (speedRatio === undefined) {
  22522. speedRatio = 1.0;
  22523. }
  22524. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22525. return animatable;
  22526. };
  22527. /**
  22528. * Begin a new animation on a given node and its hierarchy
  22529. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22530. * @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.
  22531. * @param {BABYLON.Animation[]} defines the list of animations to start
  22532. * @param {number} from defines the initial value
  22533. * @param {number} to defines the final value
  22534. * @param {boolean} loop defines if you want animation to loop (off by default)
  22535. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22536. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22537. * @returns the list of animatables created for all nodes
  22538. */
  22539. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22540. var children = target.getDescendants(directDescendantsOnly);
  22541. var result = [];
  22542. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22543. var child = children_1[_i];
  22544. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22545. }
  22546. return result;
  22547. };
  22548. Scene.prototype.getAnimatableByTarget = function (target) {
  22549. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22550. if (this._activeAnimatables[index].target === target) {
  22551. return this._activeAnimatables[index];
  22552. }
  22553. }
  22554. return null;
  22555. };
  22556. Object.defineProperty(Scene.prototype, "animatables", {
  22557. get: function () {
  22558. return this._activeAnimatables;
  22559. },
  22560. enumerable: true,
  22561. configurable: true
  22562. });
  22563. /**
  22564. * Will stop the animation of the given target
  22565. * @param target - the target
  22566. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22567. * @see beginAnimation
  22568. */
  22569. Scene.prototype.stopAnimation = function (target, animationName) {
  22570. var animatable = this.getAnimatableByTarget(target);
  22571. if (animatable) {
  22572. animatable.stop(animationName);
  22573. }
  22574. };
  22575. /**
  22576. * Stops and removes all animations that have been applied to the scene
  22577. */
  22578. Scene.prototype.stopAllAnimations = function () {
  22579. if (this._activeAnimatables) {
  22580. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22581. this._activeAnimatables[i].stop();
  22582. }
  22583. this._activeAnimatables = [];
  22584. }
  22585. };
  22586. Scene.prototype._animate = function () {
  22587. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22588. return;
  22589. }
  22590. // Getting time
  22591. var now = BABYLON.Tools.Now;
  22592. if (!this._animationTimeLast) {
  22593. if (this._pendingData.length > 0) {
  22594. return;
  22595. }
  22596. this._animationTimeLast = now;
  22597. }
  22598. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22599. this._animationTime += deltaTime;
  22600. this._animationTimeLast = now;
  22601. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22602. this._activeAnimatables[index]._animate(this._animationTime);
  22603. }
  22604. };
  22605. // Matrix
  22606. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22607. this._useAlternateCameraConfiguration = active;
  22608. };
  22609. Scene.prototype.getViewMatrix = function () {
  22610. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22611. };
  22612. Scene.prototype.getProjectionMatrix = function () {
  22613. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22614. };
  22615. Scene.prototype.getTransformMatrix = function () {
  22616. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22617. };
  22618. Scene.prototype.setTransformMatrix = function (view, projection) {
  22619. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22620. return;
  22621. }
  22622. this._viewUpdateFlag = view.updateFlag;
  22623. this._projectionUpdateFlag = projection.updateFlag;
  22624. this._viewMatrix = view;
  22625. this._projectionMatrix = projection;
  22626. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22627. // Update frustum
  22628. if (!this._frustumPlanes) {
  22629. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22630. }
  22631. else {
  22632. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22633. }
  22634. if (this.activeCamera && this.activeCamera._alternateCamera) {
  22635. var otherCamera = this.activeCamera._alternateCamera;
  22636. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  22637. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  22638. }
  22639. if (this._sceneUbo.useUbo) {
  22640. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  22641. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  22642. this._sceneUbo.update();
  22643. }
  22644. };
  22645. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  22646. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  22647. return;
  22648. }
  22649. this._alternateViewUpdateFlag = view.updateFlag;
  22650. this._alternateProjectionUpdateFlag = projection.updateFlag;
  22651. this._alternateViewMatrix = view;
  22652. this._alternateProjectionMatrix = projection;
  22653. if (!this._alternateTransformMatrix) {
  22654. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  22655. }
  22656. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  22657. if (!this._alternateSceneUbo) {
  22658. this._createAlternateUbo();
  22659. }
  22660. if (this._alternateSceneUbo.useUbo) {
  22661. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  22662. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  22663. this._alternateSceneUbo.update();
  22664. }
  22665. };
  22666. Scene.prototype.getSceneUniformBuffer = function () {
  22667. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  22668. };
  22669. // Methods
  22670. Scene.prototype.getUniqueId = function () {
  22671. var result = Scene._uniqueIdCounter;
  22672. Scene._uniqueIdCounter++;
  22673. return result;
  22674. };
  22675. Scene.prototype.addMesh = function (newMesh) {
  22676. this.meshes.push(newMesh);
  22677. //notify the collision coordinator
  22678. if (this.collisionCoordinator) {
  22679. this.collisionCoordinator.onMeshAdded(newMesh);
  22680. }
  22681. newMesh._resyncLightSources();
  22682. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  22683. };
  22684. Scene.prototype.removeMesh = function (toRemove) {
  22685. var index = this.meshes.indexOf(toRemove);
  22686. if (index !== -1) {
  22687. // Remove from the scene if mesh found
  22688. this.meshes.splice(index, 1);
  22689. }
  22690. this.onMeshRemovedObservable.notifyObservers(toRemove);
  22691. return index;
  22692. };
  22693. Scene.prototype.addTransformNode = function (newTransformNode) {
  22694. this.transformNodes.push(newTransformNode);
  22695. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  22696. };
  22697. Scene.prototype.removeTransformNode = function (toRemove) {
  22698. var index = this.transformNodes.indexOf(toRemove);
  22699. if (index !== -1) {
  22700. // Remove from the scene if found
  22701. this.transformNodes.splice(index, 1);
  22702. }
  22703. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  22704. return index;
  22705. };
  22706. Scene.prototype.removeSkeleton = function (toRemove) {
  22707. var index = this.skeletons.indexOf(toRemove);
  22708. if (index !== -1) {
  22709. // Remove from the scene if found
  22710. this.skeletons.splice(index, 1);
  22711. }
  22712. return index;
  22713. };
  22714. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  22715. var index = this.morphTargetManagers.indexOf(toRemove);
  22716. if (index !== -1) {
  22717. // Remove from the scene if found
  22718. this.morphTargetManagers.splice(index, 1);
  22719. }
  22720. return index;
  22721. };
  22722. Scene.prototype.removeLight = function (toRemove) {
  22723. var index = this.lights.indexOf(toRemove);
  22724. if (index !== -1) {
  22725. // Remove from meshes
  22726. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22727. var mesh = _a[_i];
  22728. mesh._removeLightSource(toRemove);
  22729. }
  22730. // Remove from the scene if mesh found
  22731. this.lights.splice(index, 1);
  22732. this.sortLightsByPriority();
  22733. }
  22734. this.onLightRemovedObservable.notifyObservers(toRemove);
  22735. return index;
  22736. };
  22737. Scene.prototype.removeCamera = function (toRemove) {
  22738. var index = this.cameras.indexOf(toRemove);
  22739. if (index !== -1) {
  22740. // Remove from the scene if mesh found
  22741. this.cameras.splice(index, 1);
  22742. }
  22743. // Remove from activeCameras
  22744. var index2 = this.activeCameras.indexOf(toRemove);
  22745. if (index2 !== -1) {
  22746. // Remove from the scene if mesh found
  22747. this.activeCameras.splice(index2, 1);
  22748. }
  22749. // Reset the activeCamera
  22750. if (this.activeCamera === toRemove) {
  22751. if (this.cameras.length > 0) {
  22752. this.activeCamera = this.cameras[0];
  22753. }
  22754. else {
  22755. this.activeCamera = null;
  22756. }
  22757. }
  22758. this.onCameraRemovedObservable.notifyObservers(toRemove);
  22759. return index;
  22760. };
  22761. Scene.prototype.removeParticleSystem = function (toRemove) {
  22762. var index = this.particleSystems.indexOf(toRemove);
  22763. if (index !== -1) {
  22764. this.particleSystems.splice(index, 1);
  22765. }
  22766. return index;
  22767. };
  22768. ;
  22769. Scene.prototype.removeAnimation = function (toRemove) {
  22770. var index = this.animations.indexOf(toRemove);
  22771. if (index !== -1) {
  22772. this.animations.splice(index, 1);
  22773. }
  22774. return index;
  22775. };
  22776. ;
  22777. Scene.prototype.removeMultiMaterial = function (toRemove) {
  22778. var index = this.multiMaterials.indexOf(toRemove);
  22779. if (index !== -1) {
  22780. this.multiMaterials.splice(index, 1);
  22781. }
  22782. return index;
  22783. };
  22784. ;
  22785. Scene.prototype.removeMaterial = function (toRemove) {
  22786. var index = this.materials.indexOf(toRemove);
  22787. if (index !== -1) {
  22788. this.materials.splice(index, 1);
  22789. }
  22790. return index;
  22791. };
  22792. ;
  22793. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  22794. var index = this.lensFlareSystems.indexOf(toRemove);
  22795. if (index !== -1) {
  22796. this.lensFlareSystems.splice(index, 1);
  22797. }
  22798. return index;
  22799. };
  22800. ;
  22801. Scene.prototype.removeActionManager = function (toRemove) {
  22802. var index = this._actionManagers.indexOf(toRemove);
  22803. if (index !== -1) {
  22804. this._actionManagers.splice(index, 1);
  22805. }
  22806. return index;
  22807. };
  22808. ;
  22809. Scene.prototype.addLight = function (newLight) {
  22810. this.lights.push(newLight);
  22811. this.sortLightsByPriority();
  22812. // Add light to all meshes (To support if the light is removed and then readded)
  22813. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22814. var mesh = _a[_i];
  22815. if (mesh._lightSources.indexOf(newLight) === -1) {
  22816. mesh._lightSources.push(newLight);
  22817. mesh._resyncLightSources();
  22818. }
  22819. }
  22820. this.onNewLightAddedObservable.notifyObservers(newLight);
  22821. };
  22822. Scene.prototype.sortLightsByPriority = function () {
  22823. if (this.requireLightSorting) {
  22824. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22825. }
  22826. };
  22827. Scene.prototype.addCamera = function (newCamera) {
  22828. this.cameras.push(newCamera);
  22829. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22830. };
  22831. Scene.prototype.addSkeleton = function (newSkeleton) {
  22832. this.skeletons.push(newSkeleton);
  22833. };
  22834. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22835. this.particleSystems.push(newParticleSystem);
  22836. };
  22837. Scene.prototype.addAnimation = function (newAnimation) {
  22838. this.animations.push(newAnimation);
  22839. };
  22840. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22841. this.multiMaterials.push(newMultiMaterial);
  22842. };
  22843. Scene.prototype.addMaterial = function (newMaterial) {
  22844. this.materials.push(newMaterial);
  22845. };
  22846. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22847. this.morphTargetManagers.push(newMorphTargetManager);
  22848. };
  22849. Scene.prototype.addGeometry = function (newGeometrie) {
  22850. this._geometries.push(newGeometrie);
  22851. };
  22852. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22853. this.lensFlareSystems.push(newLensFlareSystem);
  22854. };
  22855. Scene.prototype.addActionManager = function (newActionManager) {
  22856. this._actionManagers.push(newActionManager);
  22857. };
  22858. /**
  22859. * Switch active camera
  22860. * @param {Camera} newCamera - new active camera
  22861. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22862. */
  22863. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22864. if (attachControl === void 0) { attachControl = true; }
  22865. var canvas = this._engine.getRenderingCanvas();
  22866. if (!canvas) {
  22867. return;
  22868. }
  22869. if (this.activeCamera) {
  22870. this.activeCamera.detachControl(canvas);
  22871. }
  22872. this.activeCamera = newCamera;
  22873. if (attachControl) {
  22874. newCamera.attachControl(canvas);
  22875. }
  22876. };
  22877. /**
  22878. * sets the active camera of the scene using its ID
  22879. * @param {string} id - the camera's ID
  22880. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22881. * @see activeCamera
  22882. */
  22883. Scene.prototype.setActiveCameraByID = function (id) {
  22884. var camera = this.getCameraByID(id);
  22885. if (camera) {
  22886. this.activeCamera = camera;
  22887. return camera;
  22888. }
  22889. return null;
  22890. };
  22891. /**
  22892. * sets the active camera of the scene using its name
  22893. * @param {string} name - the camera's name
  22894. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22895. * @see activeCamera
  22896. */
  22897. Scene.prototype.setActiveCameraByName = function (name) {
  22898. var camera = this.getCameraByName(name);
  22899. if (camera) {
  22900. this.activeCamera = camera;
  22901. return camera;
  22902. }
  22903. return null;
  22904. };
  22905. /**
  22906. * get an animation group using its name
  22907. * @param {string} the material's name
  22908. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  22909. */
  22910. Scene.prototype.getAnimationGroupByName = function (name) {
  22911. for (var index = 0; index < this.animationGroups.length; index++) {
  22912. if (this.animationGroups[index].name === name) {
  22913. return this.animationGroups[index];
  22914. }
  22915. }
  22916. return null;
  22917. };
  22918. /**
  22919. * get a material using its id
  22920. * @param {string} the material's ID
  22921. * @return {BABYLON.Material|null} the material or null if none found.
  22922. */
  22923. Scene.prototype.getMaterialByID = function (id) {
  22924. for (var index = 0; index < this.materials.length; index++) {
  22925. if (this.materials[index].id === id) {
  22926. return this.materials[index];
  22927. }
  22928. }
  22929. return null;
  22930. };
  22931. /**
  22932. * get a material using its name
  22933. * @param {string} the material's name
  22934. * @return {BABYLON.Material|null} the material or null if none found.
  22935. */
  22936. Scene.prototype.getMaterialByName = function (name) {
  22937. for (var index = 0; index < this.materials.length; index++) {
  22938. if (this.materials[index].name === name) {
  22939. return this.materials[index];
  22940. }
  22941. }
  22942. return null;
  22943. };
  22944. Scene.prototype.getLensFlareSystemByName = function (name) {
  22945. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22946. if (this.lensFlareSystems[index].name === name) {
  22947. return this.lensFlareSystems[index];
  22948. }
  22949. }
  22950. return null;
  22951. };
  22952. Scene.prototype.getLensFlareSystemByID = function (id) {
  22953. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22954. if (this.lensFlareSystems[index].id === id) {
  22955. return this.lensFlareSystems[index];
  22956. }
  22957. }
  22958. return null;
  22959. };
  22960. Scene.prototype.getCameraByID = function (id) {
  22961. for (var index = 0; index < this.cameras.length; index++) {
  22962. if (this.cameras[index].id === id) {
  22963. return this.cameras[index];
  22964. }
  22965. }
  22966. return null;
  22967. };
  22968. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  22969. for (var index = 0; index < this.cameras.length; index++) {
  22970. if (this.cameras[index].uniqueId === uniqueId) {
  22971. return this.cameras[index];
  22972. }
  22973. }
  22974. return null;
  22975. };
  22976. /**
  22977. * get a camera using its name
  22978. * @param {string} the camera's name
  22979. * @return {BABYLON.Camera|null} the camera or null if none found.
  22980. */
  22981. Scene.prototype.getCameraByName = function (name) {
  22982. for (var index = 0; index < this.cameras.length; index++) {
  22983. if (this.cameras[index].name === name) {
  22984. return this.cameras[index];
  22985. }
  22986. }
  22987. return null;
  22988. };
  22989. /**
  22990. * get a bone using its id
  22991. * @param {string} the bone's id
  22992. * @return {BABYLON.Bone|null} the bone or null if not found
  22993. */
  22994. Scene.prototype.getBoneByID = function (id) {
  22995. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22996. var skeleton = this.skeletons[skeletonIndex];
  22997. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22998. if (skeleton.bones[boneIndex].id === id) {
  22999. return skeleton.bones[boneIndex];
  23000. }
  23001. }
  23002. }
  23003. return null;
  23004. };
  23005. /**
  23006. * get a bone using its id
  23007. * @param {string} the bone's name
  23008. * @return {BABYLON.Bone|null} the bone or null if not found
  23009. */
  23010. Scene.prototype.getBoneByName = function (name) {
  23011. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23012. var skeleton = this.skeletons[skeletonIndex];
  23013. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23014. if (skeleton.bones[boneIndex].name === name) {
  23015. return skeleton.bones[boneIndex];
  23016. }
  23017. }
  23018. }
  23019. return null;
  23020. };
  23021. /**
  23022. * get a light node using its name
  23023. * @param {string} the light's name
  23024. * @return {BABYLON.Light|null} the light or null if none found.
  23025. */
  23026. Scene.prototype.getLightByName = function (name) {
  23027. for (var index = 0; index < this.lights.length; index++) {
  23028. if (this.lights[index].name === name) {
  23029. return this.lights[index];
  23030. }
  23031. }
  23032. return null;
  23033. };
  23034. /**
  23035. * get a light node using its ID
  23036. * @param {string} the light's id
  23037. * @return {BABYLON.Light|null} the light or null if none found.
  23038. */
  23039. Scene.prototype.getLightByID = function (id) {
  23040. for (var index = 0; index < this.lights.length; index++) {
  23041. if (this.lights[index].id === id) {
  23042. return this.lights[index];
  23043. }
  23044. }
  23045. return null;
  23046. };
  23047. /**
  23048. * get a light node using its scene-generated unique ID
  23049. * @param {number} the light's unique id
  23050. * @return {BABYLON.Light|null} the light or null if none found.
  23051. */
  23052. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23053. for (var index = 0; index < this.lights.length; index++) {
  23054. if (this.lights[index].uniqueId === uniqueId) {
  23055. return this.lights[index];
  23056. }
  23057. }
  23058. return null;
  23059. };
  23060. /**
  23061. * get a particle system by id
  23062. * @param id {number} the particle system id
  23063. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23064. */
  23065. Scene.prototype.getParticleSystemByID = function (id) {
  23066. for (var index = 0; index < this.particleSystems.length; index++) {
  23067. if (this.particleSystems[index].id === id) {
  23068. return this.particleSystems[index];
  23069. }
  23070. }
  23071. return null;
  23072. };
  23073. /**
  23074. * get a geometry using its ID
  23075. * @param {string} the geometry's id
  23076. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23077. */
  23078. Scene.prototype.getGeometryByID = function (id) {
  23079. for (var index = 0; index < this._geometries.length; index++) {
  23080. if (this._geometries[index].id === id) {
  23081. return this._geometries[index];
  23082. }
  23083. }
  23084. return null;
  23085. };
  23086. /**
  23087. * add a new geometry to this scene.
  23088. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23089. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23090. * @return {boolean} was the geometry added or not
  23091. */
  23092. Scene.prototype.pushGeometry = function (geometry, force) {
  23093. if (!force && this.getGeometryByID(geometry.id)) {
  23094. return false;
  23095. }
  23096. this._geometries.push(geometry);
  23097. //notify the collision coordinator
  23098. if (this.collisionCoordinator) {
  23099. this.collisionCoordinator.onGeometryAdded(geometry);
  23100. }
  23101. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23102. return true;
  23103. };
  23104. /**
  23105. * Removes an existing geometry
  23106. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23107. * @return {boolean} was the geometry removed or not
  23108. */
  23109. Scene.prototype.removeGeometry = function (geometry) {
  23110. var index = this._geometries.indexOf(geometry);
  23111. if (index > -1) {
  23112. this._geometries.splice(index, 1);
  23113. //notify the collision coordinator
  23114. if (this.collisionCoordinator) {
  23115. this.collisionCoordinator.onGeometryDeleted(geometry);
  23116. }
  23117. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23118. return true;
  23119. }
  23120. return false;
  23121. };
  23122. Scene.prototype.getGeometries = function () {
  23123. return this._geometries;
  23124. };
  23125. /**
  23126. * Get the first added mesh found of a given ID
  23127. * @param {string} id - the id to search for
  23128. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23129. */
  23130. Scene.prototype.getMeshByID = function (id) {
  23131. for (var index = 0; index < this.meshes.length; index++) {
  23132. if (this.meshes[index].id === id) {
  23133. return this.meshes[index];
  23134. }
  23135. }
  23136. return null;
  23137. };
  23138. Scene.prototype.getMeshesByID = function (id) {
  23139. return this.meshes.filter(function (m) {
  23140. return m.id === id;
  23141. });
  23142. };
  23143. /**
  23144. * Get the first added transform node found of a given ID
  23145. * @param {string} id - the id to search for
  23146. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23147. */
  23148. Scene.prototype.getTransformNodeByID = function (id) {
  23149. for (var index = 0; index < this.transformNodes.length; index++) {
  23150. if (this.transformNodes[index].id === id) {
  23151. return this.transformNodes[index];
  23152. }
  23153. }
  23154. return null;
  23155. };
  23156. Scene.prototype.getTransformNodesByID = function (id) {
  23157. return this.transformNodes.filter(function (m) {
  23158. return m.id === id;
  23159. });
  23160. };
  23161. /**
  23162. * Get a mesh with its auto-generated unique id
  23163. * @param {number} uniqueId - the unique id to search for
  23164. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23165. */
  23166. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23167. for (var index = 0; index < this.meshes.length; index++) {
  23168. if (this.meshes[index].uniqueId === uniqueId) {
  23169. return this.meshes[index];
  23170. }
  23171. }
  23172. return null;
  23173. };
  23174. /**
  23175. * Get a the last added mesh found of a given ID
  23176. * @param {string} id - the id to search for
  23177. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23178. */
  23179. Scene.prototype.getLastMeshByID = function (id) {
  23180. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23181. if (this.meshes[index].id === id) {
  23182. return this.meshes[index];
  23183. }
  23184. }
  23185. return null;
  23186. };
  23187. /**
  23188. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23189. * @param {string} id - the id to search for
  23190. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23191. */
  23192. Scene.prototype.getLastEntryByID = function (id) {
  23193. var index;
  23194. for (index = this.meshes.length - 1; index >= 0; index--) {
  23195. if (this.meshes[index].id === id) {
  23196. return this.meshes[index];
  23197. }
  23198. }
  23199. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23200. if (this.transformNodes[index].id === id) {
  23201. return this.transformNodes[index];
  23202. }
  23203. }
  23204. for (index = this.cameras.length - 1; index >= 0; index--) {
  23205. if (this.cameras[index].id === id) {
  23206. return this.cameras[index];
  23207. }
  23208. }
  23209. for (index = this.lights.length - 1; index >= 0; index--) {
  23210. if (this.lights[index].id === id) {
  23211. return this.lights[index];
  23212. }
  23213. }
  23214. return null;
  23215. };
  23216. Scene.prototype.getNodeByID = function (id) {
  23217. var mesh = this.getMeshByID(id);
  23218. if (mesh) {
  23219. return mesh;
  23220. }
  23221. var light = this.getLightByID(id);
  23222. if (light) {
  23223. return light;
  23224. }
  23225. var camera = this.getCameraByID(id);
  23226. if (camera) {
  23227. return camera;
  23228. }
  23229. var bone = this.getBoneByID(id);
  23230. return bone;
  23231. };
  23232. Scene.prototype.getNodeByName = function (name) {
  23233. var mesh = this.getMeshByName(name);
  23234. if (mesh) {
  23235. return mesh;
  23236. }
  23237. var light = this.getLightByName(name);
  23238. if (light) {
  23239. return light;
  23240. }
  23241. var camera = this.getCameraByName(name);
  23242. if (camera) {
  23243. return camera;
  23244. }
  23245. var bone = this.getBoneByName(name);
  23246. return bone;
  23247. };
  23248. Scene.prototype.getMeshByName = function (name) {
  23249. for (var index = 0; index < this.meshes.length; index++) {
  23250. if (this.meshes[index].name === name) {
  23251. return this.meshes[index];
  23252. }
  23253. }
  23254. return null;
  23255. };
  23256. Scene.prototype.getTransformNodeByName = function (name) {
  23257. for (var index = 0; index < this.transformNodes.length; index++) {
  23258. if (this.transformNodes[index].name === name) {
  23259. return this.transformNodes[index];
  23260. }
  23261. }
  23262. return null;
  23263. };
  23264. Scene.prototype.getSoundByName = function (name) {
  23265. var index;
  23266. if (BABYLON.AudioEngine) {
  23267. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23268. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23269. return this.mainSoundTrack.soundCollection[index];
  23270. }
  23271. }
  23272. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23273. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23274. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23275. return this.soundTracks[sdIndex].soundCollection[index];
  23276. }
  23277. }
  23278. }
  23279. }
  23280. return null;
  23281. };
  23282. Scene.prototype.getLastSkeletonByID = function (id) {
  23283. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23284. if (this.skeletons[index].id === id) {
  23285. return this.skeletons[index];
  23286. }
  23287. }
  23288. return null;
  23289. };
  23290. Scene.prototype.getSkeletonById = function (id) {
  23291. for (var index = 0; index < this.skeletons.length; index++) {
  23292. if (this.skeletons[index].id === id) {
  23293. return this.skeletons[index];
  23294. }
  23295. }
  23296. return null;
  23297. };
  23298. Scene.prototype.getSkeletonByName = function (name) {
  23299. for (var index = 0; index < this.skeletons.length; index++) {
  23300. if (this.skeletons[index].name === name) {
  23301. return this.skeletons[index];
  23302. }
  23303. }
  23304. return null;
  23305. };
  23306. Scene.prototype.getMorphTargetManagerById = function (id) {
  23307. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23308. if (this.morphTargetManagers[index].uniqueId === id) {
  23309. return this.morphTargetManagers[index];
  23310. }
  23311. }
  23312. return null;
  23313. };
  23314. Scene.prototype.isActiveMesh = function (mesh) {
  23315. return (this._activeMeshes.indexOf(mesh) !== -1);
  23316. };
  23317. /**
  23318. * Return a the first highlight layer of the scene with a given name.
  23319. * @param name The name of the highlight layer to look for.
  23320. * @return The highlight layer if found otherwise null.
  23321. */
  23322. Scene.prototype.getHighlightLayerByName = function (name) {
  23323. for (var index = 0; index < this.effectLayers.length; index++) {
  23324. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23325. return this.effectLayers[index];
  23326. }
  23327. }
  23328. return null;
  23329. };
  23330. /**
  23331. * Return a the first highlight layer of the scene with a given name.
  23332. * @param name The name of the highlight layer to look for.
  23333. * @return The highlight layer if found otherwise null.
  23334. */
  23335. Scene.prototype.getGlowLayerByName = function (name) {
  23336. for (var index = 0; index < this.effectLayers.length; index++) {
  23337. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23338. return this.effectLayers[index];
  23339. }
  23340. }
  23341. return null;
  23342. };
  23343. Object.defineProperty(Scene.prototype, "uid", {
  23344. /**
  23345. * Return a unique id as a string which can serve as an identifier for the scene
  23346. */
  23347. get: function () {
  23348. if (!this._uid) {
  23349. this._uid = BABYLON.Tools.RandomId();
  23350. }
  23351. return this._uid;
  23352. },
  23353. enumerable: true,
  23354. configurable: true
  23355. });
  23356. /**
  23357. * Add an externaly attached data from its key.
  23358. * This method call will fail and return false, if such key already exists.
  23359. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23360. * @param key the unique key that identifies the data
  23361. * @param data the data object to associate to the key for this Engine instance
  23362. * @return true if no such key were already present and the data was added successfully, false otherwise
  23363. */
  23364. Scene.prototype.addExternalData = function (key, data) {
  23365. if (!this._externalData) {
  23366. this._externalData = new BABYLON.StringDictionary();
  23367. }
  23368. return this._externalData.add(key, data);
  23369. };
  23370. /**
  23371. * Get an externaly attached data from its key
  23372. * @param key the unique key that identifies the data
  23373. * @return the associated data, if present (can be null), or undefined if not present
  23374. */
  23375. Scene.prototype.getExternalData = function (key) {
  23376. if (!this._externalData) {
  23377. return null;
  23378. }
  23379. return this._externalData.get(key);
  23380. };
  23381. /**
  23382. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23383. * @param key the unique key that identifies the data
  23384. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23385. * @return the associated data, can be null if the factory returned null.
  23386. */
  23387. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23388. if (!this._externalData) {
  23389. this._externalData = new BABYLON.StringDictionary();
  23390. }
  23391. return this._externalData.getOrAddWithFactory(key, factory);
  23392. };
  23393. /**
  23394. * Remove an externaly attached data from the Engine instance
  23395. * @param key the unique key that identifies the data
  23396. * @return true if the data was successfully removed, false if it doesn't exist
  23397. */
  23398. Scene.prototype.removeExternalData = function (key) {
  23399. return this._externalData.remove(key);
  23400. };
  23401. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23402. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23403. if (mesh.showSubMeshesBoundingBox) {
  23404. var boundingInfo = subMesh.getBoundingInfo();
  23405. if (boundingInfo !== null && boundingInfo !== undefined) {
  23406. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23407. }
  23408. }
  23409. var material = subMesh.getMaterial();
  23410. if (material !== null && material !== undefined) {
  23411. // Render targets
  23412. if (material.getRenderTargetTextures !== undefined) {
  23413. if (this._processedMaterials.indexOf(material) === -1) {
  23414. this._processedMaterials.push(material);
  23415. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23416. }
  23417. }
  23418. // Dispatch
  23419. this._activeIndices.addCount(subMesh.indexCount, false);
  23420. this._renderingManager.dispatch(subMesh, mesh, material);
  23421. }
  23422. }
  23423. };
  23424. Scene.prototype._isInIntermediateRendering = function () {
  23425. return this._intermediateRendering;
  23426. };
  23427. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23428. this._activeMeshCandidateProvider = provider;
  23429. };
  23430. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23431. return this._activeMeshCandidateProvider;
  23432. };
  23433. /**
  23434. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23435. */
  23436. Scene.prototype.freezeActiveMeshes = function () {
  23437. this._evaluateActiveMeshes();
  23438. this._activeMeshesFrozen = true;
  23439. return this;
  23440. };
  23441. /**
  23442. * Use this function to restart evaluating active meshes on every frame
  23443. */
  23444. Scene.prototype.unfreezeActiveMeshes = function () {
  23445. this._activeMeshesFrozen = false;
  23446. return this;
  23447. };
  23448. Scene.prototype._evaluateActiveMeshes = function () {
  23449. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23450. return;
  23451. }
  23452. if (!this.activeCamera) {
  23453. return;
  23454. }
  23455. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23456. this.activeCamera._activeMeshes.reset();
  23457. this._activeMeshes.reset();
  23458. this._renderingManager.reset();
  23459. this._processedMaterials.reset();
  23460. this._activeParticleSystems.reset();
  23461. this._activeSkeletons.reset();
  23462. this._softwareSkinnedMeshes.reset();
  23463. if (this._boundingBoxRenderer) {
  23464. this._boundingBoxRenderer.reset();
  23465. }
  23466. // Meshes
  23467. var meshes;
  23468. var len;
  23469. var checkIsEnabled = true;
  23470. // Determine mesh candidates
  23471. if (this._activeMeshCandidateProvider !== undefined) {
  23472. // Use _activeMeshCandidateProvider
  23473. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23474. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23475. if (meshes !== undefined) {
  23476. len = meshes.length;
  23477. }
  23478. else {
  23479. len = 0;
  23480. }
  23481. }
  23482. else if (this._selectionOctree !== undefined) {
  23483. // Octree
  23484. var selection = this._selectionOctree.select(this._frustumPlanes);
  23485. meshes = selection.data;
  23486. len = selection.length;
  23487. }
  23488. else {
  23489. // Full scene traversal
  23490. len = this.meshes.length;
  23491. meshes = this.meshes;
  23492. }
  23493. // Check each mesh
  23494. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23495. mesh = meshes[meshIndex];
  23496. if (mesh.isBlocked) {
  23497. continue;
  23498. }
  23499. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23500. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23501. continue;
  23502. }
  23503. mesh.computeWorldMatrix();
  23504. // Intersections
  23505. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23506. this._meshesForIntersections.pushNoDuplicate(mesh);
  23507. }
  23508. // Switch to current LOD
  23509. meshLOD = mesh.getLOD(this.activeCamera);
  23510. if (meshLOD === undefined || meshLOD === null) {
  23511. continue;
  23512. }
  23513. mesh._preActivate();
  23514. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23515. this._activeMeshes.push(mesh);
  23516. this.activeCamera._activeMeshes.push(mesh);
  23517. mesh._activate(this._renderId);
  23518. if (meshLOD !== mesh) {
  23519. meshLOD._activate(this._renderId);
  23520. }
  23521. this._activeMesh(mesh, meshLOD);
  23522. }
  23523. }
  23524. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23525. // Particle systems
  23526. if (this.particlesEnabled) {
  23527. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23528. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23529. var particleSystem = this.particleSystems[particleIndex];
  23530. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23531. continue;
  23532. }
  23533. var emitter = particleSystem.emitter;
  23534. if (!emitter.position || emitter.isEnabled()) {
  23535. this._activeParticleSystems.push(particleSystem);
  23536. particleSystem.animate();
  23537. this._renderingManager.dispatchParticles(particleSystem);
  23538. }
  23539. }
  23540. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23541. }
  23542. };
  23543. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23544. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23545. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23546. mesh.skeleton.prepare();
  23547. }
  23548. if (!mesh.computeBonesUsingShaders) {
  23549. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23550. }
  23551. }
  23552. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23553. var boundingInfo = sourceMesh.getBoundingInfo();
  23554. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23555. }
  23556. if (mesh !== undefined && mesh !== null
  23557. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23558. // Submeshes Octrees
  23559. var len;
  23560. var subMeshes;
  23561. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23562. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23563. len = intersections.length;
  23564. subMeshes = intersections.data;
  23565. }
  23566. else {
  23567. subMeshes = mesh.subMeshes;
  23568. len = subMeshes.length;
  23569. }
  23570. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23571. subMesh = subMeshes[subIndex];
  23572. this._evaluateSubMesh(subMesh, mesh);
  23573. }
  23574. }
  23575. };
  23576. Scene.prototype.updateTransformMatrix = function (force) {
  23577. if (!this.activeCamera) {
  23578. return;
  23579. }
  23580. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23581. };
  23582. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23583. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23584. };
  23585. Scene.prototype._renderForCamera = function (camera) {
  23586. if (camera && camera._skipRendering) {
  23587. return;
  23588. }
  23589. var engine = this._engine;
  23590. this.activeCamera = camera;
  23591. if (!this.activeCamera)
  23592. throw new Error("Active camera not set");
  23593. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23594. // Viewport
  23595. engine.setViewport(this.activeCamera.viewport);
  23596. // Camera
  23597. this.resetCachedMaterial();
  23598. this._renderId++;
  23599. this.activeCamera.update();
  23600. this.updateTransformMatrix();
  23601. if (camera._alternateCamera) {
  23602. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23603. this._alternateRendering = true;
  23604. }
  23605. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23606. // Meshes
  23607. this._evaluateActiveMeshes();
  23608. // Software skinning
  23609. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23610. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23611. mesh.applySkeleton(mesh.skeleton);
  23612. }
  23613. // Render targets
  23614. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23615. var needsRestoreFrameBuffer = false;
  23616. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23617. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23618. }
  23619. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23620. this._intermediateRendering = true;
  23621. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23622. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  23623. var renderTarget = this._renderTargets.data[renderIndex];
  23624. if (renderTarget._shouldRender()) {
  23625. this._renderId++;
  23626. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  23627. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  23628. }
  23629. }
  23630. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23631. this._intermediateRendering = false;
  23632. this._renderId++;
  23633. needsRestoreFrameBuffer = true; // Restore back buffer
  23634. }
  23635. // Render EffecttLayer Texture
  23636. var stencilState = this._engine.getStencilBuffer();
  23637. var renderEffects = false;
  23638. var needStencil = false;
  23639. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  23640. this._intermediateRendering = true;
  23641. for (var i = 0; i < this.effectLayers.length; i++) {
  23642. var effectLayer = this.effectLayers[i];
  23643. if (effectLayer.shouldRender() &&
  23644. (!effectLayer.camera ||
  23645. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  23646. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  23647. renderEffects = true;
  23648. needStencil = needStencil || effectLayer.needStencil();
  23649. var renderTarget = effectLayer._mainTexture;
  23650. if (renderTarget._shouldRender()) {
  23651. this._renderId++;
  23652. renderTarget.render(false, false);
  23653. needsRestoreFrameBuffer = true;
  23654. }
  23655. }
  23656. }
  23657. this._intermediateRendering = false;
  23658. this._renderId++;
  23659. }
  23660. if (needsRestoreFrameBuffer) {
  23661. engine.restoreDefaultFramebuffer(); // Restore back buffer
  23662. }
  23663. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23664. // Prepare Frame
  23665. this.postProcessManager._prepareFrame();
  23666. // Backgrounds
  23667. var layerIndex;
  23668. var layer;
  23669. if (this.layers.length) {
  23670. engine.setDepthBuffer(false);
  23671. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23672. layer = this.layers[layerIndex];
  23673. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23674. layer.render();
  23675. }
  23676. }
  23677. engine.setDepthBuffer(true);
  23678. }
  23679. // Activate effect Layer stencil
  23680. if (needStencil) {
  23681. this._engine.setStencilBuffer(true);
  23682. }
  23683. // Render
  23684. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  23685. this._renderingManager.render(null, null, true, true);
  23686. this.onAfterDrawPhaseObservable.notifyObservers(this);
  23687. // Restore effect Layer stencil
  23688. if (needStencil) {
  23689. this._engine.setStencilBuffer(stencilState);
  23690. }
  23691. // Bounding boxes
  23692. if (this._boundingBoxRenderer) {
  23693. this._boundingBoxRenderer.render();
  23694. }
  23695. // Lens flares
  23696. if (this.lensFlaresEnabled) {
  23697. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23698. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  23699. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  23700. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  23701. lensFlareSystem.render();
  23702. }
  23703. }
  23704. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23705. }
  23706. // Foregrounds
  23707. if (this.layers.length) {
  23708. engine.setDepthBuffer(false);
  23709. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23710. layer = this.layers[layerIndex];
  23711. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23712. layer.render();
  23713. }
  23714. }
  23715. engine.setDepthBuffer(true);
  23716. }
  23717. // Effect Layer
  23718. if (renderEffects) {
  23719. engine.setDepthBuffer(false);
  23720. for (var i = 0; i < this.effectLayers.length; i++) {
  23721. if (this.effectLayers[i].shouldRender()) {
  23722. this.effectLayers[i].render();
  23723. }
  23724. }
  23725. engine.setDepthBuffer(true);
  23726. }
  23727. // Finalize frame
  23728. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  23729. // Reset some special arrays
  23730. this._renderTargets.reset();
  23731. this._alternateRendering = false;
  23732. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  23733. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23734. };
  23735. Scene.prototype._processSubCameras = function (camera) {
  23736. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  23737. this._renderForCamera(camera);
  23738. return;
  23739. }
  23740. // Update camera
  23741. if (this.activeCamera) {
  23742. this.activeCamera.update();
  23743. }
  23744. // rig cameras
  23745. for (var index = 0; index < camera._rigCameras.length; index++) {
  23746. this._renderForCamera(camera._rigCameras[index]);
  23747. }
  23748. this.activeCamera = camera;
  23749. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  23750. };
  23751. Scene.prototype._checkIntersections = function () {
  23752. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  23753. var sourceMesh = this._meshesForIntersections.data[index];
  23754. if (!sourceMesh.actionManager) {
  23755. continue;
  23756. }
  23757. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  23758. var action = sourceMesh.actionManager.actions[actionIndex];
  23759. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23760. var parameters = action.getTriggerParameter();
  23761. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  23762. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  23763. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  23764. if (areIntersecting && currentIntersectionInProgress === -1) {
  23765. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  23766. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23767. sourceMesh._intersectionsInProgress.push(otherMesh);
  23768. }
  23769. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23770. sourceMesh._intersectionsInProgress.push(otherMesh);
  23771. }
  23772. }
  23773. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  23774. //They intersected, and now they don't.
  23775. //is this trigger an exit trigger? execute an event.
  23776. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23777. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23778. }
  23779. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  23780. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23781. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  23782. }
  23783. }
  23784. }
  23785. }
  23786. }
  23787. };
  23788. Scene.prototype.render = function () {
  23789. if (this.isDisposed) {
  23790. return;
  23791. }
  23792. this._activeParticles.fetchNewFrame();
  23793. this._totalVertices.fetchNewFrame();
  23794. this._activeIndices.fetchNewFrame();
  23795. this._activeBones.fetchNewFrame();
  23796. this._meshesForIntersections.reset();
  23797. this.resetCachedMaterial();
  23798. this.onBeforeAnimationsObservable.notifyObservers(this);
  23799. // Actions
  23800. if (this.actionManager) {
  23801. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  23802. }
  23803. //Simplification Queue
  23804. if (this.simplificationQueue && !this.simplificationQueue.running) {
  23805. this.simplificationQueue.executeNext();
  23806. }
  23807. if (this._engine.isDeterministicLockStep()) {
  23808. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  23809. var defaultFPS = (60.0 / 1000.0);
  23810. var defaultFrameTime = 1000 / 60; // frame time in MS
  23811. if (this._physicsEngine) {
  23812. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  23813. }
  23814. var stepsTaken = 0;
  23815. var maxSubSteps = this._engine.getLockstepMaxSteps();
  23816. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  23817. internalSteps = Math.min(internalSteps, maxSubSteps);
  23818. do {
  23819. this.onBeforeStepObservable.notifyObservers(this);
  23820. // Animations
  23821. this._animationRatio = defaultFrameTime * defaultFPS;
  23822. this._animate();
  23823. this.onAfterAnimationsObservable.notifyObservers(this);
  23824. // Physics
  23825. if (this._physicsEngine) {
  23826. this.onBeforePhysicsObservable.notifyObservers(this);
  23827. this._physicsEngine._step(defaultFrameTime / 1000);
  23828. this.onAfterPhysicsObservable.notifyObservers(this);
  23829. }
  23830. this.onAfterStepObservable.notifyObservers(this);
  23831. this._currentStepId++;
  23832. stepsTaken++;
  23833. deltaTime -= defaultFrameTime;
  23834. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23835. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23836. }
  23837. else {
  23838. // Animations
  23839. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23840. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23841. this._animate();
  23842. this.onAfterAnimationsObservable.notifyObservers(this);
  23843. // Physics
  23844. if (this._physicsEngine) {
  23845. this.onBeforePhysicsObservable.notifyObservers(this);
  23846. this._physicsEngine._step(deltaTime / 1000.0);
  23847. this.onAfterPhysicsObservable.notifyObservers(this);
  23848. }
  23849. }
  23850. // update gamepad manager
  23851. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23852. this._gamepadManager._checkGamepadsStatus();
  23853. }
  23854. // Before render
  23855. this.onBeforeRenderObservable.notifyObservers(this);
  23856. // Customs render targets
  23857. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23858. var engine = this.getEngine();
  23859. var currentActiveCamera = this.activeCamera;
  23860. if (this.renderTargetsEnabled) {
  23861. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23862. this._intermediateRendering = true;
  23863. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23864. var renderTarget = this.customRenderTargets[customIndex];
  23865. if (renderTarget._shouldRender()) {
  23866. this._renderId++;
  23867. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23868. if (!this.activeCamera)
  23869. throw new Error("Active camera not set");
  23870. // Viewport
  23871. engine.setViewport(this.activeCamera.viewport);
  23872. // Camera
  23873. this.updateTransformMatrix();
  23874. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23875. }
  23876. }
  23877. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23878. this._intermediateRendering = false;
  23879. this._renderId++;
  23880. }
  23881. // Restore back buffer
  23882. if (this.customRenderTargets.length > 0) {
  23883. engine.restoreDefaultFramebuffer();
  23884. }
  23885. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23886. this.activeCamera = currentActiveCamera;
  23887. // Procedural textures
  23888. if (this.proceduralTexturesEnabled) {
  23889. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23890. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  23891. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  23892. if (proceduralTexture._shouldRender()) {
  23893. proceduralTexture.render();
  23894. }
  23895. }
  23896. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23897. }
  23898. // Clear
  23899. if (this.autoClearDepthAndStencil || this.autoClear) {
  23900. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  23901. }
  23902. // Shadows
  23903. if (this.shadowsEnabled) {
  23904. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  23905. var light = this.lights[lightIndex];
  23906. var shadowGenerator = light.getShadowGenerator();
  23907. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  23908. var shadowMap = (shadowGenerator.getShadowMap());
  23909. if (this.textures.indexOf(shadowMap) !== -1) {
  23910. this._renderTargets.push(shadowMap);
  23911. }
  23912. }
  23913. }
  23914. }
  23915. // Depth renderer
  23916. if (this._depthRenderer) {
  23917. this._renderTargets.push(this._depthRenderer.getDepthMap());
  23918. }
  23919. // Geometry renderer
  23920. if (this._geometryBufferRenderer) {
  23921. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  23922. }
  23923. // RenderPipeline
  23924. if (this._postProcessRenderPipelineManager) {
  23925. this._postProcessRenderPipelineManager.update();
  23926. }
  23927. // Multi-cameras?
  23928. if (this.activeCameras.length > 0) {
  23929. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  23930. if (cameraIndex > 0) {
  23931. this._engine.clear(null, false, true, true);
  23932. }
  23933. this._processSubCameras(this.activeCameras[cameraIndex]);
  23934. }
  23935. }
  23936. else {
  23937. if (!this.activeCamera) {
  23938. throw new Error("No camera defined");
  23939. }
  23940. this._processSubCameras(this.activeCamera);
  23941. }
  23942. // Intersection checks
  23943. this._checkIntersections();
  23944. // Update the audio listener attached to the camera
  23945. if (BABYLON.AudioEngine) {
  23946. this._updateAudioParameters();
  23947. }
  23948. // After render
  23949. if (this.afterRender) {
  23950. this.afterRender();
  23951. }
  23952. this.onAfterRenderObservable.notifyObservers(this);
  23953. // Cleaning
  23954. for (var index = 0; index < this._toBeDisposed.length; index++) {
  23955. var data = this._toBeDisposed.data[index];
  23956. if (data) {
  23957. data.dispose();
  23958. }
  23959. this._toBeDisposed[index] = null;
  23960. }
  23961. this._toBeDisposed.reset();
  23962. if (this.dumpNextRenderTargets) {
  23963. this.dumpNextRenderTargets = false;
  23964. }
  23965. this._activeBones.addCount(0, true);
  23966. this._activeIndices.addCount(0, true);
  23967. this._activeParticles.addCount(0, true);
  23968. };
  23969. Scene.prototype._updateAudioParameters = function () {
  23970. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  23971. return;
  23972. }
  23973. var listeningCamera;
  23974. var audioEngine = BABYLON.Engine.audioEngine;
  23975. if (this.activeCameras.length > 0) {
  23976. listeningCamera = this.activeCameras[0];
  23977. }
  23978. else {
  23979. listeningCamera = this.activeCamera;
  23980. }
  23981. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  23982. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  23983. // for VR cameras
  23984. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  23985. listeningCamera = listeningCamera.rigCameras[0];
  23986. }
  23987. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  23988. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  23989. cameraDirection.normalize();
  23990. // To avoid some errors on GearVR
  23991. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  23992. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  23993. }
  23994. var i;
  23995. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23996. var sound = this.mainSoundTrack.soundCollection[i];
  23997. if (sound.useCustomAttenuation) {
  23998. sound.updateDistanceFromListener();
  23999. }
  24000. }
  24001. for (i = 0; i < this.soundTracks.length; i++) {
  24002. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24003. sound = this.soundTracks[i].soundCollection[j];
  24004. if (sound.useCustomAttenuation) {
  24005. sound.updateDistanceFromListener();
  24006. }
  24007. }
  24008. }
  24009. }
  24010. };
  24011. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24012. // Audio
  24013. get: function () {
  24014. return this._audioEnabled;
  24015. },
  24016. set: function (value) {
  24017. this._audioEnabled = value;
  24018. if (BABYLON.AudioEngine) {
  24019. if (this._audioEnabled) {
  24020. this._enableAudio();
  24021. }
  24022. else {
  24023. this._disableAudio();
  24024. }
  24025. }
  24026. },
  24027. enumerable: true,
  24028. configurable: true
  24029. });
  24030. Scene.prototype._disableAudio = function () {
  24031. var i;
  24032. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24033. this.mainSoundTrack.soundCollection[i].pause();
  24034. }
  24035. for (i = 0; i < this.soundTracks.length; i++) {
  24036. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24037. this.soundTracks[i].soundCollection[j].pause();
  24038. }
  24039. }
  24040. };
  24041. Scene.prototype._enableAudio = function () {
  24042. var i;
  24043. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24044. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24045. this.mainSoundTrack.soundCollection[i].play();
  24046. }
  24047. }
  24048. for (i = 0; i < this.soundTracks.length; i++) {
  24049. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24050. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24051. this.soundTracks[i].soundCollection[j].play();
  24052. }
  24053. }
  24054. }
  24055. };
  24056. Object.defineProperty(Scene.prototype, "headphone", {
  24057. get: function () {
  24058. return this._headphone;
  24059. },
  24060. set: function (value) {
  24061. this._headphone = value;
  24062. if (BABYLON.AudioEngine) {
  24063. if (this._headphone) {
  24064. this._switchAudioModeForHeadphones();
  24065. }
  24066. else {
  24067. this._switchAudioModeForNormalSpeakers();
  24068. }
  24069. }
  24070. },
  24071. enumerable: true,
  24072. configurable: true
  24073. });
  24074. Scene.prototype._switchAudioModeForHeadphones = function () {
  24075. this.mainSoundTrack.switchPanningModelToHRTF();
  24076. for (var i = 0; i < this.soundTracks.length; i++) {
  24077. this.soundTracks[i].switchPanningModelToHRTF();
  24078. }
  24079. };
  24080. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24081. this.mainSoundTrack.switchPanningModelToEqualPower();
  24082. for (var i = 0; i < this.soundTracks.length; i++) {
  24083. this.soundTracks[i].switchPanningModelToEqualPower();
  24084. }
  24085. };
  24086. Scene.prototype.enableDepthRenderer = function () {
  24087. if (this._depthRenderer) {
  24088. return this._depthRenderer;
  24089. }
  24090. this._depthRenderer = new BABYLON.DepthRenderer(this);
  24091. return this._depthRenderer;
  24092. };
  24093. Scene.prototype.disableDepthRenderer = function () {
  24094. if (!this._depthRenderer) {
  24095. return;
  24096. }
  24097. this._depthRenderer.dispose();
  24098. this._depthRenderer = null;
  24099. };
  24100. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24101. if (ratio === void 0) { ratio = 1; }
  24102. if (this._geometryBufferRenderer) {
  24103. return this._geometryBufferRenderer;
  24104. }
  24105. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24106. if (!this._geometryBufferRenderer.isSupported) {
  24107. this._geometryBufferRenderer = null;
  24108. }
  24109. return this._geometryBufferRenderer;
  24110. };
  24111. Scene.prototype.disableGeometryBufferRenderer = function () {
  24112. if (!this._geometryBufferRenderer) {
  24113. return;
  24114. }
  24115. this._geometryBufferRenderer.dispose();
  24116. this._geometryBufferRenderer = null;
  24117. };
  24118. Scene.prototype.freezeMaterials = function () {
  24119. for (var i = 0; i < this.materials.length; i++) {
  24120. this.materials[i].freeze();
  24121. }
  24122. };
  24123. Scene.prototype.unfreezeMaterials = function () {
  24124. for (var i = 0; i < this.materials.length; i++) {
  24125. this.materials[i].unfreeze();
  24126. }
  24127. };
  24128. Scene.prototype.dispose = function () {
  24129. this.beforeRender = null;
  24130. this.afterRender = null;
  24131. this.skeletons = [];
  24132. this.morphTargetManagers = [];
  24133. this.importedMeshesFiles = new Array();
  24134. this.stopAllAnimations();
  24135. this.resetCachedMaterial();
  24136. if (this._depthRenderer) {
  24137. this._depthRenderer.dispose();
  24138. }
  24139. if (this._gamepadManager) {
  24140. this._gamepadManager.dispose();
  24141. this._gamepadManager = null;
  24142. }
  24143. // Smart arrays
  24144. if (this.activeCamera) {
  24145. this.activeCamera._activeMeshes.dispose();
  24146. this.activeCamera = null;
  24147. }
  24148. this._activeMeshes.dispose();
  24149. this._renderingManager.dispose();
  24150. this._processedMaterials.dispose();
  24151. this._activeParticleSystems.dispose();
  24152. this._activeSkeletons.dispose();
  24153. this._softwareSkinnedMeshes.dispose();
  24154. this._renderTargets.dispose();
  24155. if (this._boundingBoxRenderer) {
  24156. this._boundingBoxRenderer.dispose();
  24157. }
  24158. this._meshesForIntersections.dispose();
  24159. this._toBeDisposed.dispose();
  24160. // Abort active requests
  24161. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24162. var request = _a[_i];
  24163. request.abort();
  24164. }
  24165. // Debug layer
  24166. if (this._debugLayer) {
  24167. this._debugLayer.hide();
  24168. }
  24169. // Events
  24170. this.onDisposeObservable.notifyObservers(this);
  24171. this.onDisposeObservable.clear();
  24172. this.onBeforeRenderObservable.clear();
  24173. this.onAfterRenderObservable.clear();
  24174. this.OnBeforeRenderTargetsRenderObservable.clear();
  24175. this.OnAfterRenderTargetsRenderObservable.clear();
  24176. this.onAfterStepObservable.clear();
  24177. this.onBeforeStepObservable.clear();
  24178. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24179. this.onAfterActiveMeshesEvaluationObservable.clear();
  24180. this.onBeforeParticlesRenderingObservable.clear();
  24181. this.onAfterParticlesRenderingObservable.clear();
  24182. this.onBeforeSpritesRenderingObservable.clear();
  24183. this.onAfterSpritesRenderingObservable.clear();
  24184. this.onBeforeDrawPhaseObservable.clear();
  24185. this.onAfterDrawPhaseObservable.clear();
  24186. this.onBeforePhysicsObservable.clear();
  24187. this.onAfterPhysicsObservable.clear();
  24188. this.onBeforeAnimationsObservable.clear();
  24189. this.onAfterAnimationsObservable.clear();
  24190. this.onDataLoadedObservable.clear();
  24191. this.detachControl();
  24192. // Release sounds & sounds tracks
  24193. if (BABYLON.AudioEngine) {
  24194. this.disposeSounds();
  24195. }
  24196. // VR Helper
  24197. if (this.VRHelper) {
  24198. this.VRHelper.dispose();
  24199. }
  24200. // Detach cameras
  24201. var canvas = this._engine.getRenderingCanvas();
  24202. if (canvas) {
  24203. var index;
  24204. for (index = 0; index < this.cameras.length; index++) {
  24205. this.cameras[index].detachControl(canvas);
  24206. }
  24207. }
  24208. // Release animation groups
  24209. while (this.animationGroups.length) {
  24210. this.animationGroups[0].dispose();
  24211. }
  24212. // Release lights
  24213. while (this.lights.length) {
  24214. this.lights[0].dispose();
  24215. }
  24216. // Release meshes
  24217. while (this.meshes.length) {
  24218. this.meshes[0].dispose(true);
  24219. }
  24220. while (this.transformNodes.length) {
  24221. this.removeTransformNode(this.transformNodes[0]);
  24222. }
  24223. // Release cameras
  24224. while (this.cameras.length) {
  24225. this.cameras[0].dispose();
  24226. }
  24227. // Release materials
  24228. if (this.defaultMaterial) {
  24229. this.defaultMaterial.dispose();
  24230. }
  24231. while (this.multiMaterials.length) {
  24232. this.multiMaterials[0].dispose();
  24233. }
  24234. while (this.materials.length) {
  24235. this.materials[0].dispose();
  24236. }
  24237. // Release particles
  24238. while (this.particleSystems.length) {
  24239. this.particleSystems[0].dispose();
  24240. }
  24241. // Release sprites
  24242. while (this.spriteManagers.length) {
  24243. this.spriteManagers[0].dispose();
  24244. }
  24245. // Release postProcesses
  24246. while (this.postProcesses.length) {
  24247. this.postProcesses[0].dispose();
  24248. }
  24249. // Release layers
  24250. while (this.layers.length) {
  24251. this.layers[0].dispose();
  24252. }
  24253. while (this.effectLayers.length) {
  24254. this.effectLayers[0].dispose();
  24255. }
  24256. // Release textures
  24257. while (this.textures.length) {
  24258. this.textures[0].dispose();
  24259. }
  24260. // Release UBO
  24261. this._sceneUbo.dispose();
  24262. if (this._alternateSceneUbo) {
  24263. this._alternateSceneUbo.dispose();
  24264. }
  24265. // Post-processes
  24266. this.postProcessManager.dispose();
  24267. if (this._postProcessRenderPipelineManager) {
  24268. this._postProcessRenderPipelineManager.dispose();
  24269. }
  24270. // Physics
  24271. if (this._physicsEngine) {
  24272. this.disablePhysicsEngine();
  24273. }
  24274. // Remove from engine
  24275. index = this._engine.scenes.indexOf(this);
  24276. if (index > -1) {
  24277. this._engine.scenes.splice(index, 1);
  24278. }
  24279. this._engine.wipeCaches(true);
  24280. this._isDisposed = true;
  24281. };
  24282. Object.defineProperty(Scene.prototype, "isDisposed", {
  24283. get: function () {
  24284. return this._isDisposed;
  24285. },
  24286. enumerable: true,
  24287. configurable: true
  24288. });
  24289. // Release sounds & sounds tracks
  24290. Scene.prototype.disposeSounds = function () {
  24291. if (!this._mainSoundTrack) {
  24292. return;
  24293. }
  24294. this.mainSoundTrack.dispose();
  24295. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24296. this.soundTracks[scIndex].dispose();
  24297. }
  24298. };
  24299. // Octrees
  24300. Scene.prototype.getWorldExtends = function () {
  24301. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24302. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24303. for (var index = 0; index < this.meshes.length; index++) {
  24304. var mesh = this.meshes[index];
  24305. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24306. continue;
  24307. }
  24308. mesh.computeWorldMatrix(true);
  24309. var boundingInfo = mesh.getBoundingInfo();
  24310. var minBox = boundingInfo.boundingBox.minimumWorld;
  24311. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24312. BABYLON.Tools.CheckExtends(minBox, min, max);
  24313. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24314. }
  24315. return {
  24316. min: min,
  24317. max: max
  24318. };
  24319. };
  24320. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24321. if (maxCapacity === void 0) { maxCapacity = 64; }
  24322. if (maxDepth === void 0) { maxDepth = 2; }
  24323. if (!this._selectionOctree) {
  24324. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24325. }
  24326. var worldExtends = this.getWorldExtends();
  24327. // Update octree
  24328. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24329. return this._selectionOctree;
  24330. };
  24331. // Picking
  24332. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24333. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24334. var result = BABYLON.Ray.Zero();
  24335. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24336. return result;
  24337. };
  24338. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24339. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24340. var engine = this._engine;
  24341. if (!camera) {
  24342. if (!this.activeCamera)
  24343. throw new Error("Active camera not set");
  24344. camera = this.activeCamera;
  24345. }
  24346. var cameraViewport = camera.viewport;
  24347. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24348. // Moving coordinates to local viewport world
  24349. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24350. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24351. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24352. return this;
  24353. };
  24354. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24355. var result = BABYLON.Ray.Zero();
  24356. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24357. return result;
  24358. };
  24359. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24360. if (!BABYLON.PickingInfo) {
  24361. return this;
  24362. }
  24363. var engine = this._engine;
  24364. if (!camera) {
  24365. if (!this.activeCamera)
  24366. throw new Error("Active camera not set");
  24367. camera = this.activeCamera;
  24368. }
  24369. var cameraViewport = camera.viewport;
  24370. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24371. var identity = BABYLON.Matrix.Identity();
  24372. // Moving coordinates to local viewport world
  24373. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24374. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24375. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24376. return this;
  24377. };
  24378. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24379. if (!BABYLON.PickingInfo) {
  24380. return null;
  24381. }
  24382. var pickingInfo = null;
  24383. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24384. var mesh = this.meshes[meshIndex];
  24385. if (predicate) {
  24386. if (!predicate(mesh)) {
  24387. continue;
  24388. }
  24389. }
  24390. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24391. continue;
  24392. }
  24393. var world = mesh.getWorldMatrix();
  24394. var ray = rayFunction(world);
  24395. var result = mesh.intersects(ray, fastCheck);
  24396. if (!result || !result.hit)
  24397. continue;
  24398. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24399. continue;
  24400. pickingInfo = result;
  24401. if (fastCheck) {
  24402. break;
  24403. }
  24404. }
  24405. return pickingInfo || new BABYLON.PickingInfo();
  24406. };
  24407. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24408. if (!BABYLON.PickingInfo) {
  24409. return null;
  24410. }
  24411. var pickingInfos = new Array();
  24412. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24413. var mesh = this.meshes[meshIndex];
  24414. if (predicate) {
  24415. if (!predicate(mesh)) {
  24416. continue;
  24417. }
  24418. }
  24419. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24420. continue;
  24421. }
  24422. var world = mesh.getWorldMatrix();
  24423. var ray = rayFunction(world);
  24424. var result = mesh.intersects(ray, false);
  24425. if (!result || !result.hit)
  24426. continue;
  24427. pickingInfos.push(result);
  24428. }
  24429. return pickingInfos;
  24430. };
  24431. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24432. if (!BABYLON.PickingInfo) {
  24433. return null;
  24434. }
  24435. var pickingInfo = null;
  24436. if (!camera) {
  24437. if (!this.activeCamera) {
  24438. return null;
  24439. }
  24440. camera = this.activeCamera;
  24441. }
  24442. if (this.spriteManagers.length > 0) {
  24443. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24444. var spriteManager = this.spriteManagers[spriteIndex];
  24445. if (!spriteManager.isPickable) {
  24446. continue;
  24447. }
  24448. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24449. if (!result || !result.hit)
  24450. continue;
  24451. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24452. continue;
  24453. pickingInfo = result;
  24454. if (fastCheck) {
  24455. break;
  24456. }
  24457. }
  24458. }
  24459. return pickingInfo || new BABYLON.PickingInfo();
  24460. };
  24461. /** Launch a ray to try to pick a mesh in the scene
  24462. * @param x position on screen
  24463. * @param y position on screen
  24464. * @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
  24465. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24466. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24467. */
  24468. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24469. var _this = this;
  24470. if (!BABYLON.PickingInfo) {
  24471. return null;
  24472. }
  24473. return this._internalPick(function (world) {
  24474. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24475. return _this._tempPickingRay;
  24476. }, predicate, fastCheck);
  24477. };
  24478. /** Launch a ray to try to pick a sprite in the scene
  24479. * @param x position on screen
  24480. * @param y position on screen
  24481. * @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
  24482. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24483. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24484. */
  24485. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24486. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24487. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24488. };
  24489. /** Use the given ray to pick a mesh in the scene
  24490. * @param ray The ray to use to pick meshes
  24491. * @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
  24492. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24493. */
  24494. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24495. var _this = this;
  24496. return this._internalPick(function (world) {
  24497. if (!_this._pickWithRayInverseMatrix) {
  24498. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24499. }
  24500. world.invertToRef(_this._pickWithRayInverseMatrix);
  24501. if (!_this._cachedRayForTransform) {
  24502. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24503. }
  24504. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24505. return _this._cachedRayForTransform;
  24506. }, predicate, fastCheck);
  24507. };
  24508. /**
  24509. * Launch a ray to try to pick a mesh in the scene
  24510. * @param x X position on screen
  24511. * @param y Y position on screen
  24512. * @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
  24513. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24514. */
  24515. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24516. var _this = this;
  24517. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24518. };
  24519. /**
  24520. * Launch a ray to try to pick a mesh in the scene
  24521. * @param ray Ray to use
  24522. * @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
  24523. */
  24524. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24525. var _this = this;
  24526. return this._internalMultiPick(function (world) {
  24527. if (!_this._pickWithRayInverseMatrix) {
  24528. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24529. }
  24530. world.invertToRef(_this._pickWithRayInverseMatrix);
  24531. if (!_this._cachedRayForTransform) {
  24532. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24533. }
  24534. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24535. return _this._cachedRayForTransform;
  24536. }, predicate);
  24537. };
  24538. Scene.prototype.setPointerOverMesh = function (mesh) {
  24539. if (this._pointerOverMesh === mesh) {
  24540. return;
  24541. }
  24542. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24543. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24544. }
  24545. this._pointerOverMesh = mesh;
  24546. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24547. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24548. }
  24549. };
  24550. Scene.prototype.getPointerOverMesh = function () {
  24551. return this._pointerOverMesh;
  24552. };
  24553. Scene.prototype.setPointerOverSprite = function (sprite) {
  24554. if (this._pointerOverSprite === sprite) {
  24555. return;
  24556. }
  24557. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24558. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24559. }
  24560. this._pointerOverSprite = sprite;
  24561. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24562. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24563. }
  24564. };
  24565. Scene.prototype.getPointerOverSprite = function () {
  24566. return this._pointerOverSprite;
  24567. };
  24568. // Physics
  24569. Scene.prototype.getPhysicsEngine = function () {
  24570. return this._physicsEngine;
  24571. };
  24572. /**
  24573. * Enables physics to the current scene
  24574. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24575. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24576. * @return {boolean} was the physics engine initialized
  24577. */
  24578. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24579. if (gravity === void 0) { gravity = null; }
  24580. if (this._physicsEngine) {
  24581. return true;
  24582. }
  24583. try {
  24584. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24585. return true;
  24586. }
  24587. catch (e) {
  24588. BABYLON.Tools.Error(e.message);
  24589. return false;
  24590. }
  24591. };
  24592. Scene.prototype.disablePhysicsEngine = function () {
  24593. if (!this._physicsEngine) {
  24594. return;
  24595. }
  24596. this._physicsEngine.dispose();
  24597. this._physicsEngine = null;
  24598. };
  24599. Scene.prototype.isPhysicsEnabled = function () {
  24600. return this._physicsEngine !== undefined;
  24601. };
  24602. Scene.prototype.deleteCompoundImpostor = function (compound) {
  24603. var mesh = compound.parts[0].mesh;
  24604. if (mesh.physicsImpostor) {
  24605. mesh.physicsImpostor.dispose();
  24606. mesh.physicsImpostor = null;
  24607. }
  24608. };
  24609. // Misc.
  24610. Scene.prototype._rebuildGeometries = function () {
  24611. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  24612. var geometry = _a[_i];
  24613. geometry._rebuild();
  24614. }
  24615. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  24616. var mesh = _c[_b];
  24617. mesh._rebuild();
  24618. }
  24619. if (this.postProcessManager) {
  24620. this.postProcessManager._rebuild();
  24621. }
  24622. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  24623. var layer = _e[_d];
  24624. layer._rebuild();
  24625. }
  24626. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  24627. var effectLayer = _g[_f];
  24628. effectLayer._rebuild();
  24629. }
  24630. if (this._boundingBoxRenderer) {
  24631. this._boundingBoxRenderer._rebuild();
  24632. }
  24633. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  24634. var system = _j[_h];
  24635. system.rebuild();
  24636. }
  24637. if (this._postProcessRenderPipelineManager) {
  24638. this._postProcessRenderPipelineManager._rebuild();
  24639. }
  24640. };
  24641. Scene.prototype._rebuildTextures = function () {
  24642. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  24643. var texture = _a[_i];
  24644. texture._rebuild();
  24645. }
  24646. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24647. };
  24648. /**
  24649. * Creates a default light for the scene.
  24650. * @param replace Whether to replace the existing lights in the scene.
  24651. */
  24652. Scene.prototype.createDefaultLight = function (replace) {
  24653. if (replace === void 0) { replace = false; }
  24654. // Dispose existing light in replace mode.
  24655. if (replace) {
  24656. if (this.lights) {
  24657. for (var i = 0; i < this.lights.length; i++) {
  24658. this.lights[i].dispose();
  24659. }
  24660. }
  24661. }
  24662. // Light
  24663. if (this.lights.length === 0) {
  24664. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  24665. }
  24666. };
  24667. /**
  24668. * Creates a default camera for the scene.
  24669. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  24670. * @param replace Whether to replace the existing active camera in the scene.
  24671. * @param attachCameraControls Whether to attach camera controls to the canvas.
  24672. */
  24673. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  24674. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24675. if (replace === void 0) { replace = false; }
  24676. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24677. // Dispose existing camera in replace mode.
  24678. if (replace) {
  24679. if (this.activeCamera) {
  24680. this.activeCamera.dispose();
  24681. this.activeCamera = null;
  24682. }
  24683. }
  24684. // Camera
  24685. if (!this.activeCamera) {
  24686. var worldExtends = this.getWorldExtends();
  24687. var worldSize = worldExtends.max.subtract(worldExtends.min);
  24688. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  24689. var camera;
  24690. var radius = worldSize.length() * 1.5;
  24691. // empty scene scenario!
  24692. if (!isFinite(radius)) {
  24693. radius = 1;
  24694. worldCenter.copyFromFloats(0, 0, 0);
  24695. }
  24696. if (createArcRotateCamera) {
  24697. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  24698. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  24699. arcRotateCamera.wheelPrecision = 100 / radius;
  24700. camera = arcRotateCamera;
  24701. }
  24702. else {
  24703. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  24704. freeCamera.setTarget(worldCenter);
  24705. camera = freeCamera;
  24706. }
  24707. camera.minZ = radius * 0.01;
  24708. camera.maxZ = radius * 1000;
  24709. camera.speed = radius * 0.2;
  24710. this.activeCamera = camera;
  24711. var canvas = this.getEngine().getRenderingCanvas();
  24712. if (attachCameraControls && canvas) {
  24713. camera.attachControl(canvas);
  24714. }
  24715. }
  24716. };
  24717. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  24718. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24719. if (replace === void 0) { replace = false; }
  24720. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24721. this.createDefaultLight(replace);
  24722. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  24723. };
  24724. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  24725. if (pbr === void 0) { pbr = false; }
  24726. if (scale === void 0) { scale = 1000; }
  24727. if (blur === void 0) { blur = 0; }
  24728. if (environmentTexture) {
  24729. this.environmentTexture = environmentTexture;
  24730. }
  24731. if (!this.environmentTexture) {
  24732. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  24733. return null;
  24734. }
  24735. // Skybox
  24736. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  24737. if (pbr) {
  24738. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  24739. hdrSkyboxMaterial.backFaceCulling = false;
  24740. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24741. if (hdrSkyboxMaterial.reflectionTexture) {
  24742. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24743. }
  24744. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  24745. hdrSkyboxMaterial.disableLighting = true;
  24746. hdrSkyboxMaterial.twoSidedLighting = true;
  24747. hdrSkybox.infiniteDistance = true;
  24748. hdrSkybox.material = hdrSkyboxMaterial;
  24749. }
  24750. else {
  24751. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  24752. skyboxMaterial.backFaceCulling = false;
  24753. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24754. if (skyboxMaterial.reflectionTexture) {
  24755. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24756. }
  24757. skyboxMaterial.disableLighting = true;
  24758. hdrSkybox.infiniteDistance = true;
  24759. hdrSkybox.material = skyboxMaterial;
  24760. }
  24761. return hdrSkybox;
  24762. };
  24763. Scene.prototype.createDefaultEnvironment = function (options) {
  24764. if (BABYLON.EnvironmentHelper) {
  24765. return new BABYLON.EnvironmentHelper(options, this);
  24766. }
  24767. return null;
  24768. };
  24769. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  24770. if (webVROptions === void 0) { webVROptions = {}; }
  24771. return new BABYLON.VRExperienceHelper(this, webVROptions);
  24772. };
  24773. // Tags
  24774. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  24775. if (tagsQuery === undefined) {
  24776. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  24777. return list;
  24778. }
  24779. var listByTags = [];
  24780. forEach = forEach || (function (item) { return; });
  24781. for (var i in list) {
  24782. var item = list[i];
  24783. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  24784. listByTags.push(item);
  24785. forEach(item);
  24786. }
  24787. }
  24788. return listByTags;
  24789. };
  24790. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  24791. return this._getByTags(this.meshes, tagsQuery, forEach);
  24792. };
  24793. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  24794. return this._getByTags(this.cameras, tagsQuery, forEach);
  24795. };
  24796. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  24797. return this._getByTags(this.lights, tagsQuery, forEach);
  24798. };
  24799. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  24800. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  24801. };
  24802. /**
  24803. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24804. * This allowed control for front to back rendering or reversly depending of the special needs.
  24805. *
  24806. * @param renderingGroupId The rendering group id corresponding to its index
  24807. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24808. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24809. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24810. */
  24811. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24812. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24813. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24814. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24815. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24816. };
  24817. /**
  24818. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24819. *
  24820. * @param renderingGroupId The rendering group id corresponding to its index
  24821. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24822. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24823. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24824. */
  24825. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24826. if (depth === void 0) { depth = true; }
  24827. if (stencil === void 0) { stencil = true; }
  24828. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24829. };
  24830. /**
  24831. * Will flag all materials as dirty to trigger new shader compilation
  24832. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24833. */
  24834. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24835. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24836. var material = _a[_i];
  24837. if (predicate && !predicate(material)) {
  24838. continue;
  24839. }
  24840. material.markAsDirty(flag);
  24841. }
  24842. };
  24843. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24844. var _this = this;
  24845. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24846. this._activeRequests.push(request);
  24847. request.onCompleteObservable.add(function (request) {
  24848. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24849. });
  24850. return request;
  24851. };
  24852. /** @ignore */
  24853. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24854. var _this = this;
  24855. return new Promise(function (resolve, reject) {
  24856. _this._loadFile(url, function (data) {
  24857. resolve(data);
  24858. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24859. reject(exception);
  24860. });
  24861. });
  24862. };
  24863. // Statics
  24864. Scene._FOGMODE_NONE = 0;
  24865. Scene._FOGMODE_EXP = 1;
  24866. Scene._FOGMODE_EXP2 = 2;
  24867. Scene._FOGMODE_LINEAR = 3;
  24868. Scene._uniqueIdCounter = 0;
  24869. Scene.MinDeltaTime = 1.0;
  24870. Scene.MaxDeltaTime = 1000.0;
  24871. /** The distance in pixel that you have to move to prevent some events */
  24872. Scene.DragMovementThreshold = 10; // in pixels
  24873. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24874. Scene.LongPressDelay = 500; // in milliseconds
  24875. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24876. Scene.DoubleClickDelay = 300; // in milliseconds
  24877. /** If you need to check double click without raising a single click at first click, enable this flag */
  24878. Scene.ExclusiveDoubleClickMode = false;
  24879. return Scene;
  24880. }());
  24881. BABYLON.Scene = Scene;
  24882. })(BABYLON || (BABYLON = {}));
  24883. //# sourceMappingURL=babylon.scene.js.map
  24884. var BABYLON;
  24885. (function (BABYLON) {
  24886. /**
  24887. * Set of assets to keep when moving a scene into an asset container.
  24888. */
  24889. var KeepAssets = /** @class */ (function () {
  24890. function KeepAssets() {
  24891. /**
  24892. * Cameras to keep.
  24893. */
  24894. this.cameras = new Array();
  24895. /**
  24896. * Lights to keep.
  24897. */
  24898. this.lights = new Array();
  24899. /**
  24900. * Meshes to keep.
  24901. */
  24902. this.meshes = new Array();
  24903. /**
  24904. * Skeletons to keep.
  24905. */
  24906. this.skeletons = new Array();
  24907. /**
  24908. * ParticleSystems to keep.
  24909. */
  24910. this.particleSystems = new Array();
  24911. /**
  24912. * Animations to keep.
  24913. */
  24914. this.animations = new Array();
  24915. /**
  24916. * MultiMaterials to keep.
  24917. */
  24918. this.multiMaterials = new Array();
  24919. /**
  24920. * Materials to keep.
  24921. */
  24922. this.materials = new Array();
  24923. /**
  24924. * MorphTargetManagers to keep.
  24925. */
  24926. this.morphTargetManagers = new Array();
  24927. /**
  24928. * Geometries to keep.
  24929. */
  24930. this.geometries = new Array();
  24931. /**
  24932. * TransformNodes to keep.
  24933. */
  24934. this.transformNodes = new Array();
  24935. /**
  24936. * LensFlareSystems to keep.
  24937. */
  24938. this.lensFlareSystems = new Array();
  24939. /**
  24940. * ShadowGenerators to keep.
  24941. */
  24942. this.shadowGenerators = new Array();
  24943. /**
  24944. * ActionManagers to keep.
  24945. */
  24946. this.actionManagers = new Array();
  24947. /**
  24948. * Sounds to keep.
  24949. */
  24950. this.sounds = new Array();
  24951. }
  24952. return KeepAssets;
  24953. }());
  24954. BABYLON.KeepAssets = KeepAssets;
  24955. /**
  24956. * Container with a set of assets that can be added or removed from a scene.
  24957. */
  24958. var AssetContainer = /** @class */ (function () {
  24959. /**
  24960. * Instantiates an AssetContainer.
  24961. * @param scene The scene the AssetContainer belongs to.
  24962. */
  24963. function AssetContainer(scene) {
  24964. // Objects
  24965. /**
  24966. * Cameras populated in the container.
  24967. */
  24968. this.cameras = new Array();
  24969. /**
  24970. * Lights populated in the container.
  24971. */
  24972. this.lights = new Array();
  24973. /**
  24974. * Meshes populated in the container.
  24975. */
  24976. this.meshes = new Array();
  24977. /**
  24978. * Skeletons populated in the container.
  24979. */
  24980. this.skeletons = new Array();
  24981. /**
  24982. * ParticleSystems populated in the container.
  24983. */
  24984. this.particleSystems = new Array();
  24985. /**
  24986. * Animations populated in the container.
  24987. */
  24988. this.animations = new Array();
  24989. /**
  24990. * MultiMaterials populated in the container.
  24991. */
  24992. this.multiMaterials = new Array();
  24993. /**
  24994. * Materials populated in the container.
  24995. */
  24996. this.materials = new Array();
  24997. /**
  24998. * MorphTargetManagers populated in the container.
  24999. */
  25000. this.morphTargetManagers = new Array();
  25001. /**
  25002. * Geometries populated in the container.
  25003. */
  25004. this.geometries = new Array();
  25005. /**
  25006. * TransformNodes populated in the container.
  25007. */
  25008. this.transformNodes = new Array();
  25009. /**
  25010. * LensFlareSystems populated in the container.
  25011. */
  25012. this.lensFlareSystems = new Array();
  25013. /**
  25014. * ShadowGenerators populated in the container.
  25015. */
  25016. this.shadowGenerators = new Array();
  25017. /**
  25018. * ActionManagers populated in the container.
  25019. */
  25020. this.actionManagers = new Array();
  25021. /**
  25022. * Sounds populated in the container.
  25023. */
  25024. this.sounds = new Array();
  25025. this.scene = scene;
  25026. }
  25027. /**
  25028. * Adds all the assets from the container to the scene.
  25029. */
  25030. AssetContainer.prototype.addAllToScene = function () {
  25031. var _this = this;
  25032. this.cameras.forEach(function (o) {
  25033. _this.scene.addCamera(o);
  25034. });
  25035. this.lights.forEach(function (o) {
  25036. _this.scene.addLight(o);
  25037. });
  25038. this.meshes.forEach(function (o) {
  25039. _this.scene.addMesh(o);
  25040. });
  25041. this.skeletons.forEach(function (o) {
  25042. _this.scene.addSkeleton(o);
  25043. });
  25044. this.particleSystems.forEach(function (o) {
  25045. _this.scene.addParticleSystem(o);
  25046. });
  25047. this.animations.forEach(function (o) {
  25048. _this.scene.addAnimation(o);
  25049. });
  25050. this.multiMaterials.forEach(function (o) {
  25051. _this.scene.addMultiMaterial(o);
  25052. });
  25053. this.materials.forEach(function (o) {
  25054. _this.scene.addMaterial(o);
  25055. });
  25056. this.morphTargetManagers.forEach(function (o) {
  25057. _this.scene.addMorphTargetManager(o);
  25058. });
  25059. this.geometries.forEach(function (o) {
  25060. _this.scene.addGeometry(o);
  25061. });
  25062. this.transformNodes.forEach(function (o) {
  25063. _this.scene.addTransformNode(o);
  25064. });
  25065. this.lensFlareSystems.forEach(function (o) {
  25066. _this.scene.addLensFlareSystem(o);
  25067. });
  25068. this.actionManagers.forEach(function (o) {
  25069. _this.scene.addActionManager(o);
  25070. });
  25071. this.sounds.forEach(function (o) {
  25072. o.play();
  25073. o.autoplay = true;
  25074. _this.scene.mainSoundTrack.AddSound(o);
  25075. });
  25076. };
  25077. /**
  25078. * Removes all the assets in the container from the scene
  25079. */
  25080. AssetContainer.prototype.removeAllFromScene = function () {
  25081. var _this = this;
  25082. this.cameras.forEach(function (o) {
  25083. _this.scene.removeCamera(o);
  25084. });
  25085. this.lights.forEach(function (o) {
  25086. _this.scene.removeLight(o);
  25087. });
  25088. this.meshes.forEach(function (o) {
  25089. _this.scene.removeMesh(o);
  25090. });
  25091. this.skeletons.forEach(function (o) {
  25092. _this.scene.removeSkeleton(o);
  25093. });
  25094. this.particleSystems.forEach(function (o) {
  25095. _this.scene.removeParticleSystem(o);
  25096. });
  25097. this.animations.forEach(function (o) {
  25098. _this.scene.removeAnimation(o);
  25099. });
  25100. this.multiMaterials.forEach(function (o) {
  25101. _this.scene.removeMultiMaterial(o);
  25102. });
  25103. this.materials.forEach(function (o) {
  25104. _this.scene.removeMaterial(o);
  25105. });
  25106. this.morphTargetManagers.forEach(function (o) {
  25107. _this.scene.removeMorphTargetManager(o);
  25108. });
  25109. this.geometries.forEach(function (o) {
  25110. _this.scene.removeGeometry(o);
  25111. });
  25112. this.transformNodes.forEach(function (o) {
  25113. _this.scene.removeTransformNode(o);
  25114. });
  25115. this.lensFlareSystems.forEach(function (o) {
  25116. _this.scene.removeLensFlareSystem(o);
  25117. });
  25118. this.actionManagers.forEach(function (o) {
  25119. _this.scene.removeActionManager(o);
  25120. });
  25121. this.sounds.forEach(function (o) {
  25122. o.stop();
  25123. o.autoplay = false;
  25124. _this.scene.mainSoundTrack.RemoveSound(o);
  25125. });
  25126. };
  25127. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25128. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25129. var asset = sourceAssets_1[_i];
  25130. var move = true;
  25131. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25132. var keepAsset = keepAssets_1[_a];
  25133. if (asset === keepAsset) {
  25134. move = false;
  25135. break;
  25136. }
  25137. }
  25138. if (move) {
  25139. targetAssets.push(asset);
  25140. }
  25141. }
  25142. };
  25143. /**
  25144. * Removes all the assets contained in the scene and adds them to the container.
  25145. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25146. */
  25147. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25148. if (keepAssets === undefined) {
  25149. keepAssets = new KeepAssets();
  25150. }
  25151. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25152. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25153. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25154. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25155. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25156. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25157. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25158. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25159. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25160. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25161. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25162. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25163. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25164. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25165. this.removeAllFromScene();
  25166. };
  25167. return AssetContainer;
  25168. }());
  25169. BABYLON.AssetContainer = AssetContainer;
  25170. })(BABYLON || (BABYLON = {}));
  25171. //# sourceMappingURL=babylon.assetContainer.js.map
  25172. var BABYLON;
  25173. (function (BABYLON) {
  25174. var Buffer = /** @class */ (function () {
  25175. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25176. if (instanced === void 0) { instanced = false; }
  25177. if (engine instanceof BABYLON.Mesh) {
  25178. this._engine = engine.getScene().getEngine();
  25179. }
  25180. else {
  25181. this._engine = engine;
  25182. }
  25183. this._updatable = updatable;
  25184. this._data = data;
  25185. this._strideSize = stride;
  25186. if (!postponeInternalCreation) {
  25187. this.create();
  25188. }
  25189. this._instanced = instanced;
  25190. this._instanceDivisor = instanced ? 1 : 0;
  25191. }
  25192. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  25193. // a lot of these parameters are ignored as they are overriden by the buffer
  25194. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  25195. };
  25196. // Properties
  25197. Buffer.prototype.isUpdatable = function () {
  25198. return this._updatable;
  25199. };
  25200. Buffer.prototype.getData = function () {
  25201. return this._data;
  25202. };
  25203. Buffer.prototype.getBuffer = function () {
  25204. return this._buffer;
  25205. };
  25206. Buffer.prototype.getStrideSize = function () {
  25207. return this._strideSize;
  25208. };
  25209. Buffer.prototype.getIsInstanced = function () {
  25210. return this._instanced;
  25211. };
  25212. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  25213. get: function () {
  25214. return this._instanceDivisor;
  25215. },
  25216. set: function (value) {
  25217. this._instanceDivisor = value;
  25218. if (value == 0) {
  25219. this._instanced = false;
  25220. }
  25221. else {
  25222. this._instanced = true;
  25223. }
  25224. },
  25225. enumerable: true,
  25226. configurable: true
  25227. });
  25228. // Methods
  25229. Buffer.prototype.create = function (data) {
  25230. if (data === void 0) { data = null; }
  25231. if (!data && this._buffer) {
  25232. return; // nothing to do
  25233. }
  25234. data = data || this._data;
  25235. if (!data) {
  25236. return;
  25237. }
  25238. if (!this._buffer) {
  25239. if (this._updatable) {
  25240. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25241. this._data = data;
  25242. }
  25243. else {
  25244. this._buffer = this._engine.createVertexBuffer(data);
  25245. }
  25246. }
  25247. else if (this._updatable) {
  25248. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25249. this._data = data;
  25250. }
  25251. };
  25252. Buffer.prototype._rebuild = function () {
  25253. this._buffer = null;
  25254. this.create(this._data);
  25255. };
  25256. Buffer.prototype.update = function (data) {
  25257. this.create(data);
  25258. };
  25259. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25260. if (!this._buffer) {
  25261. return;
  25262. }
  25263. if (this._updatable) {
  25264. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25265. this._data = null;
  25266. }
  25267. };
  25268. Buffer.prototype.dispose = function () {
  25269. if (!this._buffer) {
  25270. return;
  25271. }
  25272. if (this._engine._releaseBuffer(this._buffer)) {
  25273. this._buffer = null;
  25274. }
  25275. };
  25276. return Buffer;
  25277. }());
  25278. BABYLON.Buffer = Buffer;
  25279. })(BABYLON || (BABYLON = {}));
  25280. //# sourceMappingURL=babylon.buffer.js.map
  25281. var BABYLON;
  25282. (function (BABYLON) {
  25283. var VertexBuffer = /** @class */ (function () {
  25284. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25285. if (!stride) {
  25286. stride = VertexBuffer.DeduceStride(kind);
  25287. }
  25288. if (data instanceof BABYLON.Buffer) {
  25289. if (!stride) {
  25290. stride = data.getStrideSize();
  25291. }
  25292. this._buffer = data;
  25293. this._ownsBuffer = false;
  25294. }
  25295. else {
  25296. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25297. this._ownsBuffer = true;
  25298. }
  25299. this._stride = stride;
  25300. this._offset = offset ? offset : 0;
  25301. this._size = size ? size : stride;
  25302. this._kind = kind;
  25303. }
  25304. VertexBuffer.prototype._rebuild = function () {
  25305. if (!this._buffer) {
  25306. return;
  25307. }
  25308. this._buffer._rebuild();
  25309. };
  25310. /**
  25311. * Returns the kind of the VertexBuffer (string).
  25312. */
  25313. VertexBuffer.prototype.getKind = function () {
  25314. return this._kind;
  25315. };
  25316. // Properties
  25317. /**
  25318. * Boolean : is the VertexBuffer updatable ?
  25319. */
  25320. VertexBuffer.prototype.isUpdatable = function () {
  25321. return this._buffer.isUpdatable();
  25322. };
  25323. /**
  25324. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25325. */
  25326. VertexBuffer.prototype.getData = function () {
  25327. return this._buffer.getData();
  25328. };
  25329. /**
  25330. * Returns the WebGLBuffer associated to the VertexBuffer.
  25331. */
  25332. VertexBuffer.prototype.getBuffer = function () {
  25333. return this._buffer.getBuffer();
  25334. };
  25335. /**
  25336. * Returns the stride of the VertexBuffer (integer).
  25337. */
  25338. VertexBuffer.prototype.getStrideSize = function () {
  25339. return this._stride;
  25340. };
  25341. /**
  25342. * Returns the offset (integer).
  25343. */
  25344. VertexBuffer.prototype.getOffset = function () {
  25345. return this._offset;
  25346. };
  25347. /**
  25348. * Returns the VertexBuffer total size (integer).
  25349. */
  25350. VertexBuffer.prototype.getSize = function () {
  25351. return this._size;
  25352. };
  25353. /**
  25354. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25355. */
  25356. VertexBuffer.prototype.getIsInstanced = function () {
  25357. return this._buffer.getIsInstanced();
  25358. };
  25359. /**
  25360. * Returns the instancing divisor, zero for non-instanced (integer).
  25361. */
  25362. VertexBuffer.prototype.getInstanceDivisor = function () {
  25363. return this._buffer.instanceDivisor;
  25364. };
  25365. // Methods
  25366. /**
  25367. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25368. * Returns the created WebGLBuffer.
  25369. */
  25370. VertexBuffer.prototype.create = function (data) {
  25371. return this._buffer.create(data);
  25372. };
  25373. /**
  25374. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25375. * This function will create a new buffer if the current one is not updatable
  25376. * Returns the updated WebGLBuffer.
  25377. */
  25378. VertexBuffer.prototype.update = function (data) {
  25379. return this._buffer.update(data);
  25380. };
  25381. /**
  25382. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25383. * Returns the directly updated WebGLBuffer.
  25384. */
  25385. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25386. return this._buffer.updateDirectly(data, offset);
  25387. };
  25388. /**
  25389. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25390. */
  25391. VertexBuffer.prototype.dispose = function () {
  25392. if (this._ownsBuffer) {
  25393. this._buffer.dispose();
  25394. }
  25395. };
  25396. Object.defineProperty(VertexBuffer, "PositionKind", {
  25397. get: function () {
  25398. return VertexBuffer._PositionKind;
  25399. },
  25400. enumerable: true,
  25401. configurable: true
  25402. });
  25403. Object.defineProperty(VertexBuffer, "NormalKind", {
  25404. get: function () {
  25405. return VertexBuffer._NormalKind;
  25406. },
  25407. enumerable: true,
  25408. configurable: true
  25409. });
  25410. Object.defineProperty(VertexBuffer, "TangentKind", {
  25411. get: function () {
  25412. return VertexBuffer._TangentKind;
  25413. },
  25414. enumerable: true,
  25415. configurable: true
  25416. });
  25417. Object.defineProperty(VertexBuffer, "UVKind", {
  25418. get: function () {
  25419. return VertexBuffer._UVKind;
  25420. },
  25421. enumerable: true,
  25422. configurable: true
  25423. });
  25424. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25425. get: function () {
  25426. return VertexBuffer._UV2Kind;
  25427. },
  25428. enumerable: true,
  25429. configurable: true
  25430. });
  25431. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25432. get: function () {
  25433. return VertexBuffer._UV3Kind;
  25434. },
  25435. enumerable: true,
  25436. configurable: true
  25437. });
  25438. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25439. get: function () {
  25440. return VertexBuffer._UV4Kind;
  25441. },
  25442. enumerable: true,
  25443. configurable: true
  25444. });
  25445. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25446. get: function () {
  25447. return VertexBuffer._UV5Kind;
  25448. },
  25449. enumerable: true,
  25450. configurable: true
  25451. });
  25452. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25453. get: function () {
  25454. return VertexBuffer._UV6Kind;
  25455. },
  25456. enumerable: true,
  25457. configurable: true
  25458. });
  25459. Object.defineProperty(VertexBuffer, "ColorKind", {
  25460. get: function () {
  25461. return VertexBuffer._ColorKind;
  25462. },
  25463. enumerable: true,
  25464. configurable: true
  25465. });
  25466. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25467. get: function () {
  25468. return VertexBuffer._MatricesIndicesKind;
  25469. },
  25470. enumerable: true,
  25471. configurable: true
  25472. });
  25473. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25474. get: function () {
  25475. return VertexBuffer._MatricesWeightsKind;
  25476. },
  25477. enumerable: true,
  25478. configurable: true
  25479. });
  25480. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25481. get: function () {
  25482. return VertexBuffer._MatricesIndicesExtraKind;
  25483. },
  25484. enumerable: true,
  25485. configurable: true
  25486. });
  25487. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25488. get: function () {
  25489. return VertexBuffer._MatricesWeightsExtraKind;
  25490. },
  25491. enumerable: true,
  25492. configurable: true
  25493. });
  25494. /**
  25495. * Deduces the stride given a kind.
  25496. * @param kind The kind string to deduce
  25497. * @returns The deduced stride
  25498. */
  25499. VertexBuffer.DeduceStride = function (kind) {
  25500. switch (kind) {
  25501. case VertexBuffer.PositionKind:
  25502. return 3;
  25503. case VertexBuffer.NormalKind:
  25504. return 3;
  25505. case VertexBuffer.UVKind:
  25506. case VertexBuffer.UV2Kind:
  25507. case VertexBuffer.UV3Kind:
  25508. case VertexBuffer.UV4Kind:
  25509. case VertexBuffer.UV5Kind:
  25510. case VertexBuffer.UV6Kind:
  25511. return 2;
  25512. case VertexBuffer.TangentKind:
  25513. case VertexBuffer.ColorKind:
  25514. return 4;
  25515. case VertexBuffer.MatricesIndicesKind:
  25516. case VertexBuffer.MatricesIndicesExtraKind:
  25517. return 4;
  25518. case VertexBuffer.MatricesWeightsKind:
  25519. case VertexBuffer.MatricesWeightsExtraKind:
  25520. return 4;
  25521. default:
  25522. throw new Error("Invalid kind '" + kind + "'");
  25523. }
  25524. };
  25525. // Enums
  25526. VertexBuffer._PositionKind = "position";
  25527. VertexBuffer._NormalKind = "normal";
  25528. VertexBuffer._TangentKind = "tangent";
  25529. VertexBuffer._UVKind = "uv";
  25530. VertexBuffer._UV2Kind = "uv2";
  25531. VertexBuffer._UV3Kind = "uv3";
  25532. VertexBuffer._UV4Kind = "uv4";
  25533. VertexBuffer._UV5Kind = "uv5";
  25534. VertexBuffer._UV6Kind = "uv6";
  25535. VertexBuffer._ColorKind = "color";
  25536. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25537. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25538. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25539. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25540. return VertexBuffer;
  25541. }());
  25542. BABYLON.VertexBuffer = VertexBuffer;
  25543. })(BABYLON || (BABYLON = {}));
  25544. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25545. var BABYLON;
  25546. (function (BABYLON) {
  25547. /**
  25548. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25549. */
  25550. var DummyInternalTextureTracker = /** @class */ (function () {
  25551. function DummyInternalTextureTracker() {
  25552. /**
  25553. * Gets or set the previous tracker in the list
  25554. */
  25555. this.previous = null;
  25556. /**
  25557. * Gets or set the next tracker in the list
  25558. */
  25559. this.next = null;
  25560. }
  25561. return DummyInternalTextureTracker;
  25562. }());
  25563. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25564. })(BABYLON || (BABYLON = {}));
  25565. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  25566. var BABYLON;
  25567. (function (BABYLON) {
  25568. /**
  25569. * Class used to store data associated with WebGL texture data for the engine
  25570. * This class should not be used directly
  25571. */
  25572. var InternalTexture = /** @class */ (function () {
  25573. /**
  25574. * Creates a new InternalTexture
  25575. * @param engine defines the engine to use
  25576. * @param dataSource defines the type of data that will be used
  25577. */
  25578. function InternalTexture(engine, dataSource) {
  25579. /**
  25580. * Observable called when the texture is loaded
  25581. */
  25582. this.onLoadedObservable = new BABYLON.Observable();
  25583. /**
  25584. * Gets or set the previous tracker in the list
  25585. */
  25586. this.previous = null;
  25587. /**
  25588. * Gets or set the next tracker in the list
  25589. */
  25590. this.next = null;
  25591. // Private
  25592. /** @ignore */
  25593. this._initialSlot = -1;
  25594. /** @ignore */
  25595. this._designatedSlot = -1;
  25596. /** @ignore */
  25597. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  25598. /** @ignore */
  25599. this._references = 1;
  25600. this._engine = engine;
  25601. this._dataSource = dataSource;
  25602. this._webGLTexture = engine._createTexture();
  25603. }
  25604. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  25605. /**
  25606. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  25607. */
  25608. get: function () {
  25609. return this._dataSource;
  25610. },
  25611. enumerable: true,
  25612. configurable: true
  25613. });
  25614. /**
  25615. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  25616. */
  25617. InternalTexture.prototype.incrementReferences = function () {
  25618. this._references++;
  25619. };
  25620. /**
  25621. * Change the size of the texture (not the size of the content)
  25622. * @param width defines the new width
  25623. * @param height defines the new height
  25624. * @param depth defines the new depth (1 by default)
  25625. */
  25626. InternalTexture.prototype.updateSize = function (width, height, depth) {
  25627. if (depth === void 0) { depth = 1; }
  25628. this.width = width;
  25629. this.height = height;
  25630. this.depth = depth;
  25631. this.baseWidth = width;
  25632. this.baseHeight = height;
  25633. this.baseDepth = depth;
  25634. this._size = width * height * depth;
  25635. };
  25636. /** @ignore */
  25637. InternalTexture.prototype._rebuild = function () {
  25638. var _this = this;
  25639. var proxy;
  25640. this.isReady = false;
  25641. this._cachedCoordinatesMode = null;
  25642. this._cachedWrapU = null;
  25643. this._cachedWrapV = null;
  25644. this._cachedAnisotropicFilteringLevel = null;
  25645. switch (this._dataSource) {
  25646. case InternalTexture.DATASOURCE_TEMP:
  25647. return;
  25648. case InternalTexture.DATASOURCE_URL:
  25649. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  25650. _this.isReady = true;
  25651. }, null, this._buffer, undefined, this.format);
  25652. proxy._swapAndDie(this);
  25653. return;
  25654. case InternalTexture.DATASOURCE_RAW:
  25655. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25656. proxy._swapAndDie(this);
  25657. this.isReady = true;
  25658. return;
  25659. case InternalTexture.DATASOURCE_RAW3D:
  25660. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25661. proxy._swapAndDie(this);
  25662. this.isReady = true;
  25663. return;
  25664. case InternalTexture.DATASOURCE_DYNAMIC:
  25665. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  25666. proxy._swapAndDie(this);
  25667. // The engine will make sure to update content so no need to flag it as isReady = true
  25668. return;
  25669. case InternalTexture.DATASOURCE_RENDERTARGET:
  25670. var options = new BABYLON.RenderTargetCreationOptions();
  25671. options.generateDepthBuffer = this._generateDepthBuffer;
  25672. options.generateMipMaps = this.generateMipMaps;
  25673. options.generateStencilBuffer = this._generateStencilBuffer;
  25674. options.samplingMode = this.samplingMode;
  25675. options.type = this.type;
  25676. if (this.isCube) {
  25677. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  25678. }
  25679. else {
  25680. var size = {
  25681. width: this.width,
  25682. height: this.height
  25683. };
  25684. proxy = this._engine.createRenderTargetTexture(size, options);
  25685. }
  25686. proxy._swapAndDie(this);
  25687. this.isReady = true;
  25688. return;
  25689. case InternalTexture.DATASOURCE_CUBE:
  25690. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  25691. _this.isReady = true;
  25692. }, null, this.format, this._extension);
  25693. proxy._swapAndDie(this);
  25694. return;
  25695. case InternalTexture.DATASOURCE_CUBERAW:
  25696. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25697. proxy._swapAndDie(this);
  25698. this.isReady = true;
  25699. return;
  25700. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  25701. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  25702. if (proxy) {
  25703. proxy._swapAndDie(_this);
  25704. }
  25705. _this.isReady = true;
  25706. }, null, this.format, this._extension);
  25707. return;
  25708. }
  25709. };
  25710. InternalTexture.prototype._swapAndDie = function (target) {
  25711. target._webGLTexture = this._webGLTexture;
  25712. if (this._framebuffer) {
  25713. target._framebuffer = this._framebuffer;
  25714. }
  25715. if (this._depthStencilBuffer) {
  25716. target._depthStencilBuffer = this._depthStencilBuffer;
  25717. }
  25718. if (this._lodTextureHigh) {
  25719. if (target._lodTextureHigh) {
  25720. target._lodTextureHigh.dispose();
  25721. }
  25722. target._lodTextureHigh = this._lodTextureHigh;
  25723. }
  25724. if (this._lodTextureMid) {
  25725. if (target._lodTextureMid) {
  25726. target._lodTextureMid.dispose();
  25727. }
  25728. target._lodTextureMid = this._lodTextureMid;
  25729. }
  25730. if (this._lodTextureLow) {
  25731. if (target._lodTextureLow) {
  25732. target._lodTextureLow.dispose();
  25733. }
  25734. target._lodTextureLow = this._lodTextureLow;
  25735. }
  25736. var cache = this._engine.getLoadedTexturesCache();
  25737. var index = cache.indexOf(this);
  25738. if (index !== -1) {
  25739. cache.splice(index, 1);
  25740. }
  25741. };
  25742. /**
  25743. * Dispose the current allocated resources
  25744. */
  25745. InternalTexture.prototype.dispose = function () {
  25746. if (!this._webGLTexture) {
  25747. return;
  25748. }
  25749. this._references--;
  25750. if (this._references === 0) {
  25751. this._engine._releaseTexture(this);
  25752. this._webGLTexture = null;
  25753. this.previous = null;
  25754. this.next = null;
  25755. }
  25756. };
  25757. /**
  25758. * The source of the texture data is unknown
  25759. */
  25760. InternalTexture.DATASOURCE_UNKNOWN = 0;
  25761. /**
  25762. * Texture data comes from an URL
  25763. */
  25764. InternalTexture.DATASOURCE_URL = 1;
  25765. /**
  25766. * Texture data is only used for temporary storage
  25767. */
  25768. InternalTexture.DATASOURCE_TEMP = 2;
  25769. /**
  25770. * Texture data comes from raw data (ArrayBuffer)
  25771. */
  25772. InternalTexture.DATASOURCE_RAW = 3;
  25773. /**
  25774. * Texture content is dynamic (video or dynamic texture)
  25775. */
  25776. InternalTexture.DATASOURCE_DYNAMIC = 4;
  25777. /**
  25778. * Texture content is generated by rendering to it
  25779. */
  25780. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  25781. /**
  25782. * Texture content is part of a multi render target process
  25783. */
  25784. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  25785. /**
  25786. * Texture data comes from a cube data file
  25787. */
  25788. InternalTexture.DATASOURCE_CUBE = 7;
  25789. /**
  25790. * Texture data comes from a raw cube data
  25791. */
  25792. InternalTexture.DATASOURCE_CUBERAW = 8;
  25793. /**
  25794. * Texture data come from a prefiltered cube data file
  25795. */
  25796. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  25797. /**
  25798. * Texture content is raw 3D data
  25799. */
  25800. InternalTexture.DATASOURCE_RAW3D = 10;
  25801. return InternalTexture;
  25802. }());
  25803. BABYLON.InternalTexture = InternalTexture;
  25804. })(BABYLON || (BABYLON = {}));
  25805. //# sourceMappingURL=babylon.internalTexture.js.map
  25806. var BABYLON;
  25807. (function (BABYLON) {
  25808. var BaseTexture = /** @class */ (function () {
  25809. function BaseTexture(scene) {
  25810. this._hasAlpha = false;
  25811. this.getAlphaFromRGB = false;
  25812. this.level = 1;
  25813. this.coordinatesIndex = 0;
  25814. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  25815. /*
  25816. * How a texture is mapped.
  25817. *
  25818. * | Value | Type | Description |
  25819. * | ----- | ----------------------------------- | ----------- |
  25820. * | 0 | EXPLICIT_MODE | |
  25821. * | 1 | SPHERICAL_MODE | |
  25822. * | 2 | PLANAR_MODE | |
  25823. * | 3 | CUBIC_MODE | |
  25824. * | 4 | PROJECTION_MODE | |
  25825. * | 5 | SKYBOX_MODE | |
  25826. * | 6 | INVCUBIC_MODE | |
  25827. * | 7 | EQUIRECTANGULAR_MODE | |
  25828. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  25829. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  25830. */
  25831. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25832. /*
  25833. * | Value | Type | Description |
  25834. * | ----- | ------------------ | ----------- |
  25835. * | 0 | CLAMP_ADDRESSMODE | |
  25836. * | 1 | WRAP_ADDRESSMODE | |
  25837. * | 2 | MIRROR_ADDRESSMODE | |
  25838. */
  25839. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25840. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  25841. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  25842. this.isCube = false;
  25843. this.is3D = false;
  25844. this.gammaSpace = true;
  25845. this.invertZ = false;
  25846. this.lodLevelInAlpha = false;
  25847. this.lodGenerationOffset = 0.0;
  25848. this.lodGenerationScale = 0.8;
  25849. this.isRenderTarget = false;
  25850. this.animations = new Array();
  25851. /**
  25852. * An event triggered when the texture is disposed.
  25853. * @type {BABYLON.Observable}
  25854. */
  25855. this.onDisposeObservable = new BABYLON.Observable();
  25856. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25857. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25858. if (this._scene) {
  25859. this._scene.textures.push(this);
  25860. }
  25861. this._uid = null;
  25862. }
  25863. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  25864. get: function () {
  25865. return this._hasAlpha;
  25866. },
  25867. set: function (value) {
  25868. if (this._hasAlpha === value) {
  25869. return;
  25870. }
  25871. this._hasAlpha = value;
  25872. if (this._scene) {
  25873. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  25874. }
  25875. },
  25876. enumerable: true,
  25877. configurable: true
  25878. });
  25879. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  25880. get: function () {
  25881. return this._coordinatesMode;
  25882. },
  25883. set: function (value) {
  25884. if (this._coordinatesMode === value) {
  25885. return;
  25886. }
  25887. this._coordinatesMode = value;
  25888. if (this._scene) {
  25889. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25890. }
  25891. },
  25892. enumerable: true,
  25893. configurable: true
  25894. });
  25895. Object.defineProperty(BaseTexture.prototype, "uid", {
  25896. get: function () {
  25897. if (!this._uid) {
  25898. this._uid = BABYLON.Tools.RandomId();
  25899. }
  25900. return this._uid;
  25901. },
  25902. enumerable: true,
  25903. configurable: true
  25904. });
  25905. BaseTexture.prototype.toString = function () {
  25906. return this.name;
  25907. };
  25908. BaseTexture.prototype.getClassName = function () {
  25909. return "BaseTexture";
  25910. };
  25911. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  25912. set: function (callback) {
  25913. if (this._onDisposeObserver) {
  25914. this.onDisposeObservable.remove(this._onDisposeObserver);
  25915. }
  25916. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25917. },
  25918. enumerable: true,
  25919. configurable: true
  25920. });
  25921. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  25922. get: function () {
  25923. return true;
  25924. },
  25925. enumerable: true,
  25926. configurable: true
  25927. });
  25928. BaseTexture.prototype.getScene = function () {
  25929. return this._scene;
  25930. };
  25931. BaseTexture.prototype.getTextureMatrix = function () {
  25932. return BABYLON.Matrix.IdentityReadOnly;
  25933. };
  25934. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  25935. return BABYLON.Matrix.IdentityReadOnly;
  25936. };
  25937. BaseTexture.prototype.getInternalTexture = function () {
  25938. return this._texture;
  25939. };
  25940. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  25941. return !this.isBlocking || this.isReady();
  25942. };
  25943. BaseTexture.prototype.isReady = function () {
  25944. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25945. this.delayLoad();
  25946. return false;
  25947. }
  25948. if (this._texture) {
  25949. return this._texture.isReady;
  25950. }
  25951. return false;
  25952. };
  25953. BaseTexture.prototype.getSize = function () {
  25954. if (this._texture && this._texture.width) {
  25955. return new BABYLON.Size(this._texture.width, this._texture.height);
  25956. }
  25957. if (this._texture && this._texture._size) {
  25958. return new BABYLON.Size(this._texture._size, this._texture._size);
  25959. }
  25960. return BABYLON.Size.Zero();
  25961. };
  25962. BaseTexture.prototype.getBaseSize = function () {
  25963. if (!this.isReady() || !this._texture)
  25964. return BABYLON.Size.Zero();
  25965. if (this._texture._size) {
  25966. return new BABYLON.Size(this._texture._size, this._texture._size);
  25967. }
  25968. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  25969. };
  25970. BaseTexture.prototype.scale = function (ratio) {
  25971. };
  25972. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  25973. get: function () {
  25974. return false;
  25975. },
  25976. enumerable: true,
  25977. configurable: true
  25978. });
  25979. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  25980. if (!this._scene) {
  25981. return null;
  25982. }
  25983. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  25984. for (var index = 0; index < texturesCache.length; index++) {
  25985. var texturesCacheEntry = texturesCache[index];
  25986. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  25987. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  25988. texturesCacheEntry.incrementReferences();
  25989. return texturesCacheEntry;
  25990. }
  25991. }
  25992. }
  25993. return null;
  25994. };
  25995. BaseTexture.prototype._rebuild = function () {
  25996. };
  25997. BaseTexture.prototype.delayLoad = function () {
  25998. };
  25999. BaseTexture.prototype.clone = function () {
  26000. return null;
  26001. };
  26002. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26003. get: function () {
  26004. if (!this._texture) {
  26005. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26006. }
  26007. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26008. },
  26009. enumerable: true,
  26010. configurable: true
  26011. });
  26012. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26013. get: function () {
  26014. if (!this._texture) {
  26015. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26016. }
  26017. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26018. },
  26019. enumerable: true,
  26020. configurable: true
  26021. });
  26022. BaseTexture.prototype.readPixels = function (faceIndex) {
  26023. if (faceIndex === void 0) { faceIndex = 0; }
  26024. if (!this._texture) {
  26025. return null;
  26026. }
  26027. var size = this.getSize();
  26028. var scene = this.getScene();
  26029. if (!scene) {
  26030. return null;
  26031. }
  26032. var engine = scene.getEngine();
  26033. if (this._texture.isCube) {
  26034. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26035. }
  26036. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26037. };
  26038. BaseTexture.prototype.releaseInternalTexture = function () {
  26039. if (this._texture) {
  26040. this._texture.dispose();
  26041. this._texture = null;
  26042. }
  26043. };
  26044. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26045. get: function () {
  26046. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26047. return null;
  26048. }
  26049. if (!this._texture._sphericalPolynomial) {
  26050. this._texture._sphericalPolynomial =
  26051. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26052. }
  26053. return this._texture._sphericalPolynomial;
  26054. },
  26055. set: function (value) {
  26056. if (this._texture) {
  26057. this._texture._sphericalPolynomial = value;
  26058. }
  26059. },
  26060. enumerable: true,
  26061. configurable: true
  26062. });
  26063. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26064. get: function () {
  26065. if (this._texture) {
  26066. return this._texture._lodTextureHigh;
  26067. }
  26068. return null;
  26069. },
  26070. enumerable: true,
  26071. configurable: true
  26072. });
  26073. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26074. get: function () {
  26075. if (this._texture) {
  26076. return this._texture._lodTextureMid;
  26077. }
  26078. return null;
  26079. },
  26080. enumerable: true,
  26081. configurable: true
  26082. });
  26083. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26084. get: function () {
  26085. if (this._texture) {
  26086. return this._texture._lodTextureLow;
  26087. }
  26088. return null;
  26089. },
  26090. enumerable: true,
  26091. configurable: true
  26092. });
  26093. BaseTexture.prototype.dispose = function () {
  26094. if (!this._scene) {
  26095. return;
  26096. }
  26097. // Animations
  26098. this._scene.stopAnimation(this);
  26099. // Remove from scene
  26100. this._scene._removePendingData(this);
  26101. var index = this._scene.textures.indexOf(this);
  26102. if (index >= 0) {
  26103. this._scene.textures.splice(index, 1);
  26104. }
  26105. if (this._texture === undefined) {
  26106. return;
  26107. }
  26108. // Release
  26109. this.releaseInternalTexture();
  26110. // Callback
  26111. this.onDisposeObservable.notifyObservers(this);
  26112. this.onDisposeObservable.clear();
  26113. };
  26114. BaseTexture.prototype.serialize = function () {
  26115. if (!this.name) {
  26116. return null;
  26117. }
  26118. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26119. // Animations
  26120. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26121. return serializationObject;
  26122. };
  26123. BaseTexture.WhenAllReady = function (textures, callback) {
  26124. var numRemaining = textures.length;
  26125. if (numRemaining === 0) {
  26126. callback();
  26127. return;
  26128. }
  26129. var _loop_1 = function () {
  26130. texture = textures[i];
  26131. if (texture.isReady()) {
  26132. if (--numRemaining === 0) {
  26133. callback();
  26134. }
  26135. }
  26136. else {
  26137. onLoadObservable = texture.onLoadObservable;
  26138. var onLoadCallback_1 = function () {
  26139. onLoadObservable.removeCallback(onLoadCallback_1);
  26140. if (--numRemaining === 0) {
  26141. callback();
  26142. }
  26143. };
  26144. onLoadObservable.add(onLoadCallback_1);
  26145. }
  26146. };
  26147. var texture, onLoadObservable;
  26148. for (var i = 0; i < textures.length; i++) {
  26149. _loop_1();
  26150. }
  26151. };
  26152. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26153. __decorate([
  26154. BABYLON.serialize()
  26155. ], BaseTexture.prototype, "name", void 0);
  26156. __decorate([
  26157. BABYLON.serialize("hasAlpha")
  26158. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26159. __decorate([
  26160. BABYLON.serialize()
  26161. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26162. __decorate([
  26163. BABYLON.serialize()
  26164. ], BaseTexture.prototype, "level", void 0);
  26165. __decorate([
  26166. BABYLON.serialize()
  26167. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26168. __decorate([
  26169. BABYLON.serialize("coordinatesMode")
  26170. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26171. __decorate([
  26172. BABYLON.serialize()
  26173. ], BaseTexture.prototype, "wrapU", void 0);
  26174. __decorate([
  26175. BABYLON.serialize()
  26176. ], BaseTexture.prototype, "wrapV", void 0);
  26177. __decorate([
  26178. BABYLON.serialize()
  26179. ], BaseTexture.prototype, "wrapR", void 0);
  26180. __decorate([
  26181. BABYLON.serialize()
  26182. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26183. __decorate([
  26184. BABYLON.serialize()
  26185. ], BaseTexture.prototype, "isCube", void 0);
  26186. __decorate([
  26187. BABYLON.serialize()
  26188. ], BaseTexture.prototype, "is3D", void 0);
  26189. __decorate([
  26190. BABYLON.serialize()
  26191. ], BaseTexture.prototype, "gammaSpace", void 0);
  26192. __decorate([
  26193. BABYLON.serialize()
  26194. ], BaseTexture.prototype, "invertZ", void 0);
  26195. __decorate([
  26196. BABYLON.serialize()
  26197. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26198. __decorate([
  26199. BABYLON.serialize()
  26200. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26201. __decorate([
  26202. BABYLON.serialize()
  26203. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26204. __decorate([
  26205. BABYLON.serialize()
  26206. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26207. return BaseTexture;
  26208. }());
  26209. BABYLON.BaseTexture = BaseTexture;
  26210. })(BABYLON || (BABYLON = {}));
  26211. //# sourceMappingURL=babylon.baseTexture.js.map
  26212. var BABYLON;
  26213. (function (BABYLON) {
  26214. var Texture = /** @class */ (function (_super) {
  26215. __extends(Texture, _super);
  26216. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26217. if (noMipmap === void 0) { noMipmap = false; }
  26218. if (invertY === void 0) { invertY = true; }
  26219. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26220. if (onLoad === void 0) { onLoad = null; }
  26221. if (onError === void 0) { onError = null; }
  26222. if (buffer === void 0) { buffer = null; }
  26223. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26224. var _this = _super.call(this, scene) || this;
  26225. _this.uOffset = 0;
  26226. _this.vOffset = 0;
  26227. _this.uScale = 1.0;
  26228. _this.vScale = 1.0;
  26229. _this.uAng = 0;
  26230. _this.vAng = 0;
  26231. _this.wAng = 0;
  26232. _this._isBlocking = true;
  26233. _this.name = url || "";
  26234. _this.url = url;
  26235. _this._noMipmap = noMipmap;
  26236. _this._invertY = invertY;
  26237. _this._samplingMode = samplingMode;
  26238. _this._buffer = buffer;
  26239. _this._deleteBuffer = deleteBuffer;
  26240. if (format) {
  26241. _this._format = format;
  26242. }
  26243. scene = _this.getScene();
  26244. if (!scene) {
  26245. return _this;
  26246. }
  26247. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26248. var load = function () {
  26249. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26250. _this.onLoadObservable.notifyObservers(_this);
  26251. }
  26252. if (onLoad) {
  26253. onLoad();
  26254. }
  26255. if (!_this.isBlocking && scene) {
  26256. scene.resetCachedMaterial();
  26257. }
  26258. };
  26259. if (!_this.url) {
  26260. _this._delayedOnLoad = load;
  26261. _this._delayedOnError = onError;
  26262. return _this;
  26263. }
  26264. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26265. if (!_this._texture) {
  26266. if (!scene.useDelayedTextureLoading) {
  26267. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26268. if (deleteBuffer) {
  26269. delete _this._buffer;
  26270. }
  26271. }
  26272. else {
  26273. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26274. _this._delayedOnLoad = load;
  26275. _this._delayedOnError = onError;
  26276. }
  26277. }
  26278. else {
  26279. if (_this._texture.isReady) {
  26280. BABYLON.Tools.SetImmediate(function () { return load(); });
  26281. }
  26282. else {
  26283. _this._texture.onLoadedObservable.add(load);
  26284. }
  26285. }
  26286. return _this;
  26287. }
  26288. Object.defineProperty(Texture.prototype, "noMipmap", {
  26289. get: function () {
  26290. return this._noMipmap;
  26291. },
  26292. enumerable: true,
  26293. configurable: true
  26294. });
  26295. Object.defineProperty(Texture.prototype, "isBlocking", {
  26296. get: function () {
  26297. return this._isBlocking;
  26298. },
  26299. set: function (value) {
  26300. this._isBlocking = value;
  26301. },
  26302. enumerable: true,
  26303. configurable: true
  26304. });
  26305. Object.defineProperty(Texture.prototype, "samplingMode", {
  26306. get: function () {
  26307. return this._samplingMode;
  26308. },
  26309. enumerable: true,
  26310. configurable: true
  26311. });
  26312. Texture.prototype.updateURL = function (url) {
  26313. this.url = url;
  26314. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26315. this.delayLoad();
  26316. };
  26317. Texture.prototype.delayLoad = function () {
  26318. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26319. return;
  26320. }
  26321. var scene = this.getScene();
  26322. if (!scene) {
  26323. return;
  26324. }
  26325. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26326. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26327. if (!this._texture) {
  26328. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26329. if (this._deleteBuffer) {
  26330. delete this._buffer;
  26331. }
  26332. }
  26333. else {
  26334. if (this._delayedOnLoad) {
  26335. if (this._texture.isReady) {
  26336. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26337. }
  26338. else {
  26339. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26340. }
  26341. }
  26342. }
  26343. this._delayedOnLoad = null;
  26344. this._delayedOnError = null;
  26345. };
  26346. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26347. if (!this._texture) {
  26348. return;
  26349. }
  26350. var scene = this.getScene();
  26351. if (!scene) {
  26352. return;
  26353. }
  26354. this._samplingMode = samplingMode;
  26355. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26356. };
  26357. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26358. x *= this.uScale;
  26359. y *= this.vScale;
  26360. x -= 0.5 * this.uScale;
  26361. y -= 0.5 * this.vScale;
  26362. z -= 0.5;
  26363. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26364. t.x += 0.5 * this.uScale + this.uOffset;
  26365. t.y += 0.5 * this.vScale + this.vOffset;
  26366. t.z += 0.5;
  26367. };
  26368. Texture.prototype.getTextureMatrix = function () {
  26369. var _this = this;
  26370. if (this.uOffset === this._cachedUOffset &&
  26371. this.vOffset === this._cachedVOffset &&
  26372. this.uScale === this._cachedUScale &&
  26373. this.vScale === this._cachedVScale &&
  26374. this.uAng === this._cachedUAng &&
  26375. this.vAng === this._cachedVAng &&
  26376. this.wAng === this._cachedWAng) {
  26377. return this._cachedTextureMatrix;
  26378. }
  26379. this._cachedUOffset = this.uOffset;
  26380. this._cachedVOffset = this.vOffset;
  26381. this._cachedUScale = this.uScale;
  26382. this._cachedVScale = this.vScale;
  26383. this._cachedUAng = this.uAng;
  26384. this._cachedVAng = this.vAng;
  26385. this._cachedWAng = this.wAng;
  26386. if (!this._cachedTextureMatrix) {
  26387. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26388. this._rowGenerationMatrix = new BABYLON.Matrix();
  26389. this._t0 = BABYLON.Vector3.Zero();
  26390. this._t1 = BABYLON.Vector3.Zero();
  26391. this._t2 = BABYLON.Vector3.Zero();
  26392. }
  26393. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26394. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26395. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26396. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26397. this._t1.subtractInPlace(this._t0);
  26398. this._t2.subtractInPlace(this._t0);
  26399. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26400. this._cachedTextureMatrix.m[0] = this._t1.x;
  26401. this._cachedTextureMatrix.m[1] = this._t1.y;
  26402. this._cachedTextureMatrix.m[2] = this._t1.z;
  26403. this._cachedTextureMatrix.m[4] = this._t2.x;
  26404. this._cachedTextureMatrix.m[5] = this._t2.y;
  26405. this._cachedTextureMatrix.m[6] = this._t2.z;
  26406. this._cachedTextureMatrix.m[8] = this._t0.x;
  26407. this._cachedTextureMatrix.m[9] = this._t0.y;
  26408. this._cachedTextureMatrix.m[10] = this._t0.z;
  26409. var scene = this.getScene();
  26410. if (!scene) {
  26411. return this._cachedTextureMatrix;
  26412. }
  26413. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26414. return mat.hasTexture(_this);
  26415. });
  26416. return this._cachedTextureMatrix;
  26417. };
  26418. Texture.prototype.getReflectionTextureMatrix = function () {
  26419. var _this = this;
  26420. var scene = this.getScene();
  26421. if (!scene) {
  26422. return this._cachedTextureMatrix;
  26423. }
  26424. if (this.uOffset === this._cachedUOffset &&
  26425. this.vOffset === this._cachedVOffset &&
  26426. this.uScale === this._cachedUScale &&
  26427. this.vScale === this._cachedVScale &&
  26428. this.coordinatesMode === this._cachedCoordinatesMode) {
  26429. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26430. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26431. return this._cachedTextureMatrix;
  26432. }
  26433. }
  26434. else {
  26435. return this._cachedTextureMatrix;
  26436. }
  26437. }
  26438. if (!this._cachedTextureMatrix) {
  26439. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26440. }
  26441. if (!this._projectionModeMatrix) {
  26442. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26443. }
  26444. this._cachedUOffset = this.uOffset;
  26445. this._cachedVOffset = this.vOffset;
  26446. this._cachedUScale = this.uScale;
  26447. this._cachedVScale = this.vScale;
  26448. this._cachedCoordinatesMode = this.coordinatesMode;
  26449. switch (this.coordinatesMode) {
  26450. case Texture.PLANAR_MODE:
  26451. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26452. this._cachedTextureMatrix[0] = this.uScale;
  26453. this._cachedTextureMatrix[5] = this.vScale;
  26454. this._cachedTextureMatrix[12] = this.uOffset;
  26455. this._cachedTextureMatrix[13] = this.vOffset;
  26456. break;
  26457. case Texture.PROJECTION_MODE:
  26458. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26459. this._projectionModeMatrix.m[0] = 0.5;
  26460. this._projectionModeMatrix.m[5] = -0.5;
  26461. this._projectionModeMatrix.m[10] = 0.0;
  26462. this._projectionModeMatrix.m[12] = 0.5;
  26463. this._projectionModeMatrix.m[13] = 0.5;
  26464. this._projectionModeMatrix.m[14] = 1.0;
  26465. this._projectionModeMatrix.m[15] = 1.0;
  26466. var projectionMatrix = scene.getProjectionMatrix();
  26467. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26468. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26469. break;
  26470. default:
  26471. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26472. break;
  26473. }
  26474. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26475. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26476. });
  26477. return this._cachedTextureMatrix;
  26478. };
  26479. Texture.prototype.clone = function () {
  26480. var _this = this;
  26481. return BABYLON.SerializationHelper.Clone(function () {
  26482. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26483. }, this);
  26484. };
  26485. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26486. get: function () {
  26487. if (!this._onLoadObservable) {
  26488. this._onLoadObservable = new BABYLON.Observable();
  26489. }
  26490. return this._onLoadObservable;
  26491. },
  26492. enumerable: true,
  26493. configurable: true
  26494. });
  26495. Texture.prototype.serialize = function () {
  26496. var serializationObject = _super.prototype.serialize.call(this);
  26497. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26498. serializationObject.base64String = this._buffer;
  26499. serializationObject.name = serializationObject.name.replace("data:", "");
  26500. }
  26501. return serializationObject;
  26502. };
  26503. Texture.prototype.getClassName = function () {
  26504. return "Texture";
  26505. };
  26506. Texture.prototype.dispose = function () {
  26507. _super.prototype.dispose.call(this);
  26508. if (this.onLoadObservable) {
  26509. this.onLoadObservable.clear();
  26510. this._onLoadObservable = null;
  26511. }
  26512. this._delayedOnLoad = null;
  26513. this._delayedOnError = null;
  26514. };
  26515. // Statics
  26516. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26517. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26518. if (onLoad === void 0) { onLoad = null; }
  26519. if (onError === void 0) { onError = null; }
  26520. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26521. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26522. };
  26523. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26524. if (parsedTexture.customType) {
  26525. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26526. // Update Sampling Mode
  26527. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26528. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26529. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  26530. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  26531. }
  26532. }
  26533. return parsedCustomTexture;
  26534. }
  26535. if (parsedTexture.isCube) {
  26536. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26537. }
  26538. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26539. return null;
  26540. }
  26541. var texture = BABYLON.SerializationHelper.Parse(function () {
  26542. var generateMipMaps = true;
  26543. if (parsedTexture.noMipmap) {
  26544. generateMipMaps = false;
  26545. }
  26546. if (parsedTexture.mirrorPlane) {
  26547. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26548. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26549. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26550. return mirrorTexture;
  26551. }
  26552. else if (parsedTexture.isRenderTarget) {
  26553. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26554. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26555. return renderTargetTexture;
  26556. }
  26557. else {
  26558. var texture;
  26559. if (parsedTexture.base64String) {
  26560. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  26561. }
  26562. else {
  26563. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  26564. }
  26565. return texture;
  26566. }
  26567. }, parsedTexture, scene);
  26568. // Update Sampling Mode
  26569. if (parsedTexture.samplingMode) {
  26570. var sampling = parsedTexture.samplingMode;
  26571. if (texture._samplingMode !== sampling) {
  26572. texture.updateSamplingMode(sampling);
  26573. }
  26574. }
  26575. // Animations
  26576. if (parsedTexture.animations) {
  26577. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26578. var parsedAnimation = parsedTexture.animations[animationIndex];
  26579. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26580. }
  26581. }
  26582. return texture;
  26583. };
  26584. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26585. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26586. if (noMipmap === void 0) { noMipmap = false; }
  26587. if (invertY === void 0) { invertY = true; }
  26588. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26589. if (onLoad === void 0) { onLoad = null; }
  26590. if (onError === void 0) { onError = null; }
  26591. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26592. if (name.substr(0, 5) !== "data:") {
  26593. name = "data:" + name;
  26594. }
  26595. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26596. };
  26597. // Constants
  26598. Texture.NEAREST_SAMPLINGMODE = 1;
  26599. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  26600. Texture.BILINEAR_SAMPLINGMODE = 2;
  26601. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  26602. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26603. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  26604. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  26605. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  26606. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  26607. Texture.NEAREST_LINEAR = 7;
  26608. Texture.NEAREST_NEAREST = 8;
  26609. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  26610. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  26611. Texture.LINEAR_LINEAR = 11;
  26612. Texture.LINEAR_NEAREST = 12;
  26613. Texture.EXPLICIT_MODE = 0;
  26614. Texture.SPHERICAL_MODE = 1;
  26615. Texture.PLANAR_MODE = 2;
  26616. Texture.CUBIC_MODE = 3;
  26617. Texture.PROJECTION_MODE = 4;
  26618. Texture.SKYBOX_MODE = 5;
  26619. Texture.INVCUBIC_MODE = 6;
  26620. Texture.EQUIRECTANGULAR_MODE = 7;
  26621. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26622. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  26623. Texture.CLAMP_ADDRESSMODE = 0;
  26624. Texture.WRAP_ADDRESSMODE = 1;
  26625. Texture.MIRROR_ADDRESSMODE = 2;
  26626. __decorate([
  26627. BABYLON.serialize()
  26628. ], Texture.prototype, "url", void 0);
  26629. __decorate([
  26630. BABYLON.serialize()
  26631. ], Texture.prototype, "uOffset", void 0);
  26632. __decorate([
  26633. BABYLON.serialize()
  26634. ], Texture.prototype, "vOffset", void 0);
  26635. __decorate([
  26636. BABYLON.serialize()
  26637. ], Texture.prototype, "uScale", void 0);
  26638. __decorate([
  26639. BABYLON.serialize()
  26640. ], Texture.prototype, "vScale", void 0);
  26641. __decorate([
  26642. BABYLON.serialize()
  26643. ], Texture.prototype, "uAng", void 0);
  26644. __decorate([
  26645. BABYLON.serialize()
  26646. ], Texture.prototype, "vAng", void 0);
  26647. __decorate([
  26648. BABYLON.serialize()
  26649. ], Texture.prototype, "wAng", void 0);
  26650. __decorate([
  26651. BABYLON.serialize()
  26652. ], Texture.prototype, "isBlocking", null);
  26653. return Texture;
  26654. }(BABYLON.BaseTexture));
  26655. BABYLON.Texture = Texture;
  26656. })(BABYLON || (BABYLON = {}));
  26657. //# sourceMappingURL=babylon.texture.js.map
  26658. var BABYLON;
  26659. (function (BABYLON) {
  26660. var _InstancesBatch = /** @class */ (function () {
  26661. function _InstancesBatch() {
  26662. this.mustReturn = false;
  26663. this.visibleInstances = new Array();
  26664. this.renderSelf = new Array();
  26665. }
  26666. return _InstancesBatch;
  26667. }());
  26668. BABYLON._InstancesBatch = _InstancesBatch;
  26669. var Mesh = /** @class */ (function (_super) {
  26670. __extends(Mesh, _super);
  26671. /**
  26672. * @constructor
  26673. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  26674. * @param {Scene} scene The scene to add this mesh to.
  26675. * @param {Node} parent The parent of this mesh, if it has one
  26676. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  26677. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  26678. * When false, achieved by calling a clone(), also passing False.
  26679. * This will make creation of children, recursive.
  26680. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  26681. */
  26682. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  26683. if (scene === void 0) { scene = null; }
  26684. if (parent === void 0) { parent = null; }
  26685. if (source === void 0) { source = null; }
  26686. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26687. var _this = _super.call(this, name, scene) || this;
  26688. // Events
  26689. /**
  26690. * An event triggered before rendering the mesh
  26691. * @type {BABYLON.Observable}
  26692. */
  26693. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26694. /**
  26695. * An event triggered after rendering the mesh
  26696. * @type {BABYLON.Observable}
  26697. */
  26698. _this.onAfterRenderObservable = new BABYLON.Observable();
  26699. /**
  26700. * An event triggered before drawing the mesh
  26701. * @type {BABYLON.Observable}
  26702. */
  26703. _this.onBeforeDrawObservable = new BABYLON.Observable();
  26704. // Members
  26705. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26706. _this.instances = new Array();
  26707. _this._LODLevels = new Array();
  26708. _this._visibleInstances = {};
  26709. _this._renderIdForInstances = new Array();
  26710. _this._batchCache = new _InstancesBatch();
  26711. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26712. // Use by builder only to know what orientation were the mesh build in.
  26713. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  26714. _this.overrideMaterialSideOrientation = null;
  26715. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  26716. // Will be used to save a source mesh reference, If any
  26717. _this._source = null;
  26718. scene = _this.getScene();
  26719. if (source) {
  26720. // Source mesh
  26721. _this._source = source;
  26722. // Geometry
  26723. if (source._geometry) {
  26724. source._geometry.applyToMesh(_this);
  26725. }
  26726. // Deep copy
  26727. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  26728. // Metadata
  26729. if (source.metadata && source.metadata.clone) {
  26730. _this.metadata = source.metadata.clone();
  26731. }
  26732. else {
  26733. _this.metadata = source.metadata;
  26734. }
  26735. // Tags
  26736. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  26737. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  26738. }
  26739. // Parent
  26740. _this.parent = source.parent;
  26741. // Pivot
  26742. _this.setPivotMatrix(source.getPivotMatrix());
  26743. _this.id = name + "." + source.id;
  26744. // Material
  26745. _this.material = source.material;
  26746. var index;
  26747. if (!doNotCloneChildren) {
  26748. // Children
  26749. var directDescendants = source.getDescendants(true);
  26750. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  26751. var child = directDescendants[index_1];
  26752. if (child.clone) {
  26753. child.clone(name + "." + child.name, _this);
  26754. }
  26755. }
  26756. }
  26757. // Physics clone
  26758. var physicsEngine = _this.getScene().getPhysicsEngine();
  26759. if (clonePhysicsImpostor && physicsEngine) {
  26760. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  26761. if (impostor) {
  26762. _this.physicsImpostor = impostor.clone(_this);
  26763. }
  26764. }
  26765. // Particles
  26766. for (index = 0; index < scene.particleSystems.length; index++) {
  26767. var system = scene.particleSystems[index];
  26768. if (system.emitter === source) {
  26769. system.clone(system.name, _this);
  26770. }
  26771. }
  26772. _this.computeWorldMatrix(true);
  26773. }
  26774. // Parent
  26775. if (parent !== null) {
  26776. _this.parent = parent;
  26777. }
  26778. return _this;
  26779. }
  26780. Object.defineProperty(Mesh, "FRONTSIDE", {
  26781. /**
  26782. * Mesh side orientation : usually the external or front surface
  26783. */
  26784. get: function () {
  26785. return Mesh._FRONTSIDE;
  26786. },
  26787. enumerable: true,
  26788. configurable: true
  26789. });
  26790. Object.defineProperty(Mesh, "BACKSIDE", {
  26791. /**
  26792. * Mesh side orientation : usually the internal or back surface
  26793. */
  26794. get: function () {
  26795. return Mesh._BACKSIDE;
  26796. },
  26797. enumerable: true,
  26798. configurable: true
  26799. });
  26800. Object.defineProperty(Mesh, "DOUBLESIDE", {
  26801. /**
  26802. * Mesh side orientation : both internal and external or front and back surfaces
  26803. */
  26804. get: function () {
  26805. return Mesh._DOUBLESIDE;
  26806. },
  26807. enumerable: true,
  26808. configurable: true
  26809. });
  26810. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  26811. /**
  26812. * Mesh side orientation : by default, `FRONTSIDE`
  26813. */
  26814. get: function () {
  26815. return Mesh._DEFAULTSIDE;
  26816. },
  26817. enumerable: true,
  26818. configurable: true
  26819. });
  26820. Object.defineProperty(Mesh, "NO_CAP", {
  26821. /**
  26822. * Mesh cap setting : no cap
  26823. */
  26824. get: function () {
  26825. return Mesh._NO_CAP;
  26826. },
  26827. enumerable: true,
  26828. configurable: true
  26829. });
  26830. Object.defineProperty(Mesh, "CAP_START", {
  26831. /**
  26832. * Mesh cap setting : one cap at the beginning of the mesh
  26833. */
  26834. get: function () {
  26835. return Mesh._CAP_START;
  26836. },
  26837. enumerable: true,
  26838. configurable: true
  26839. });
  26840. Object.defineProperty(Mesh, "CAP_END", {
  26841. /**
  26842. * Mesh cap setting : one cap at the end of the mesh
  26843. */
  26844. get: function () {
  26845. return Mesh._CAP_END;
  26846. },
  26847. enumerable: true,
  26848. configurable: true
  26849. });
  26850. Object.defineProperty(Mesh, "CAP_ALL", {
  26851. /**
  26852. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  26853. */
  26854. get: function () {
  26855. return Mesh._CAP_ALL;
  26856. },
  26857. enumerable: true,
  26858. configurable: true
  26859. });
  26860. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  26861. set: function (callback) {
  26862. if (this._onBeforeDrawObserver) {
  26863. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  26864. }
  26865. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  26866. },
  26867. enumerable: true,
  26868. configurable: true
  26869. });
  26870. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  26871. get: function () {
  26872. return this._morphTargetManager;
  26873. },
  26874. set: function (value) {
  26875. if (this._morphTargetManager === value) {
  26876. return;
  26877. }
  26878. this._morphTargetManager = value;
  26879. this._syncGeometryWithMorphTargetManager();
  26880. },
  26881. enumerable: true,
  26882. configurable: true
  26883. });
  26884. Object.defineProperty(Mesh.prototype, "source", {
  26885. get: function () {
  26886. return this._source;
  26887. },
  26888. enumerable: true,
  26889. configurable: true
  26890. });
  26891. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  26892. get: function () {
  26893. return this._unIndexed;
  26894. },
  26895. set: function (value) {
  26896. if (this._unIndexed !== value) {
  26897. this._unIndexed = value;
  26898. this._markSubMeshesAsAttributesDirty();
  26899. }
  26900. },
  26901. enumerable: true,
  26902. configurable: true
  26903. });
  26904. // Methods
  26905. /**
  26906. * Returns the string "Mesh".
  26907. */
  26908. Mesh.prototype.getClassName = function () {
  26909. return "Mesh";
  26910. };
  26911. /**
  26912. * Returns a string.
  26913. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26914. */
  26915. Mesh.prototype.toString = function (fullDetails) {
  26916. var ret = _super.prototype.toString.call(this, fullDetails);
  26917. ret += ", n vertices: " + this.getTotalVertices();
  26918. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  26919. if (this.animations) {
  26920. for (var i = 0; i < this.animations.length; i++) {
  26921. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  26922. }
  26923. }
  26924. if (fullDetails) {
  26925. if (this._geometry) {
  26926. var ib = this.getIndices();
  26927. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26928. if (vb && ib) {
  26929. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  26930. }
  26931. }
  26932. else {
  26933. ret += ", flat shading: UNKNOWN";
  26934. }
  26935. }
  26936. return ret;
  26937. };
  26938. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  26939. /**
  26940. * True if the mesh has some Levels Of Details (LOD).
  26941. * Returns a boolean.
  26942. */
  26943. get: function () {
  26944. return this._LODLevels.length > 0;
  26945. },
  26946. enumerable: true,
  26947. configurable: true
  26948. });
  26949. /**
  26950. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  26951. * @returns an array of {BABYLON.MeshLODLevel}
  26952. */
  26953. Mesh.prototype.getLODLevels = function () {
  26954. return this._LODLevels;
  26955. };
  26956. Mesh.prototype._sortLODLevels = function () {
  26957. this._LODLevels.sort(function (a, b) {
  26958. if (a.distance < b.distance) {
  26959. return 1;
  26960. }
  26961. if (a.distance > b.distance) {
  26962. return -1;
  26963. }
  26964. return 0;
  26965. });
  26966. };
  26967. /**
  26968. * Add a mesh as LOD level triggered at the given distance.
  26969. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26970. * @param {number} distance The distance from the center of the object to show this level
  26971. * @param {Mesh} mesh The mesh to be added as LOD level
  26972. * @return {Mesh} This mesh (for chaining)
  26973. */
  26974. Mesh.prototype.addLODLevel = function (distance, mesh) {
  26975. if (mesh && mesh._masterMesh) {
  26976. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  26977. return this;
  26978. }
  26979. var level = new BABYLON.MeshLODLevel(distance, mesh);
  26980. this._LODLevels.push(level);
  26981. if (mesh) {
  26982. mesh._masterMesh = this;
  26983. }
  26984. this._sortLODLevels();
  26985. return this;
  26986. };
  26987. /**
  26988. * Returns the LOD level mesh at the passed distance or null if not found.
  26989. * It is related to the method `addLODLevel(distance, mesh)`.
  26990. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26991. * Returns an object Mesh or `null`.
  26992. */
  26993. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  26994. for (var index = 0; index < this._LODLevels.length; index++) {
  26995. var level = this._LODLevels[index];
  26996. if (level.distance === distance) {
  26997. return level.mesh;
  26998. }
  26999. }
  27000. return null;
  27001. };
  27002. /**
  27003. * Remove a mesh from the LOD array
  27004. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27005. * @param {Mesh} mesh The mesh to be removed.
  27006. * @return {Mesh} This mesh (for chaining)
  27007. */
  27008. Mesh.prototype.removeLODLevel = function (mesh) {
  27009. for (var index = 0; index < this._LODLevels.length; index++) {
  27010. if (this._LODLevels[index].mesh === mesh) {
  27011. this._LODLevels.splice(index, 1);
  27012. if (mesh) {
  27013. mesh._masterMesh = null;
  27014. }
  27015. }
  27016. }
  27017. this._sortLODLevels();
  27018. return this;
  27019. };
  27020. /**
  27021. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27022. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27023. */
  27024. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27025. if (!this._LODLevels || this._LODLevels.length === 0) {
  27026. return this;
  27027. }
  27028. var bSphere;
  27029. if (boundingSphere) {
  27030. bSphere = boundingSphere;
  27031. }
  27032. else {
  27033. var boundingInfo = this.getBoundingInfo();
  27034. bSphere = boundingInfo.boundingSphere;
  27035. }
  27036. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27037. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27038. if (this.onLODLevelSelection) {
  27039. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27040. }
  27041. return this;
  27042. }
  27043. for (var index = 0; index < this._LODLevels.length; index++) {
  27044. var level = this._LODLevels[index];
  27045. if (level.distance < distanceToCamera) {
  27046. if (level.mesh) {
  27047. level.mesh._preActivate();
  27048. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27049. }
  27050. if (this.onLODLevelSelection) {
  27051. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27052. }
  27053. return level.mesh;
  27054. }
  27055. }
  27056. if (this.onLODLevelSelection) {
  27057. this.onLODLevelSelection(distanceToCamera, this, this);
  27058. }
  27059. return this;
  27060. };
  27061. Object.defineProperty(Mesh.prototype, "geometry", {
  27062. /**
  27063. * Returns the mesh internal Geometry object.
  27064. */
  27065. get: function () {
  27066. return this._geometry;
  27067. },
  27068. enumerable: true,
  27069. configurable: true
  27070. });
  27071. /**
  27072. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27073. */
  27074. Mesh.prototype.getTotalVertices = function () {
  27075. if (this._geometry === null || this._geometry === undefined) {
  27076. return 0;
  27077. }
  27078. return this._geometry.getTotalVertices();
  27079. };
  27080. /**
  27081. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27082. * 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.
  27083. * You can force the copy with forceCopy === true
  27084. * Returns null if the mesh has no geometry or no vertex buffer.
  27085. * Possible `kind` values :
  27086. * - BABYLON.VertexBuffer.PositionKind
  27087. * - BABYLON.VertexBuffer.UVKind
  27088. * - BABYLON.VertexBuffer.UV2Kind
  27089. * - BABYLON.VertexBuffer.UV3Kind
  27090. * - BABYLON.VertexBuffer.UV4Kind
  27091. * - BABYLON.VertexBuffer.UV5Kind
  27092. * - BABYLON.VertexBuffer.UV6Kind
  27093. * - BABYLON.VertexBuffer.ColorKind
  27094. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27095. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27096. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27097. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27098. */
  27099. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27100. if (!this._geometry) {
  27101. return null;
  27102. }
  27103. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27104. };
  27105. /**
  27106. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27107. * Returns `null` if the mesh has no geometry.
  27108. * Possible `kind` values :
  27109. * - BABYLON.VertexBuffer.PositionKind
  27110. * - BABYLON.VertexBuffer.UVKind
  27111. * - BABYLON.VertexBuffer.UV2Kind
  27112. * - BABYLON.VertexBuffer.UV3Kind
  27113. * - BABYLON.VertexBuffer.UV4Kind
  27114. * - BABYLON.VertexBuffer.UV5Kind
  27115. * - BABYLON.VertexBuffer.UV6Kind
  27116. * - BABYLON.VertexBuffer.ColorKind
  27117. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27118. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27119. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27120. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27121. */
  27122. Mesh.prototype.getVertexBuffer = function (kind) {
  27123. if (!this._geometry) {
  27124. return null;
  27125. }
  27126. return this._geometry.getVertexBuffer(kind);
  27127. };
  27128. /**
  27129. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27130. * Possible `kind` values :
  27131. * - BABYLON.VertexBuffer.PositionKind
  27132. * - BABYLON.VertexBuffer.UVKind
  27133. * - BABYLON.VertexBuffer.UV2Kind
  27134. * - BABYLON.VertexBuffer.UV3Kind
  27135. * - BABYLON.VertexBuffer.UV4Kind
  27136. * - BABYLON.VertexBuffer.UV5Kind
  27137. * - BABYLON.VertexBuffer.UV6Kind
  27138. * - BABYLON.VertexBuffer.ColorKind
  27139. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27140. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27141. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27142. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27143. */
  27144. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27145. if (!this._geometry) {
  27146. if (this._delayInfo) {
  27147. return this._delayInfo.indexOf(kind) !== -1;
  27148. }
  27149. return false;
  27150. }
  27151. return this._geometry.isVerticesDataPresent(kind);
  27152. };
  27153. /**
  27154. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27155. * Possible `kind` values :
  27156. * - BABYLON.VertexBuffer.PositionKind
  27157. * - BABYLON.VertexBuffer.UVKind
  27158. * - BABYLON.VertexBuffer.UV2Kind
  27159. * - BABYLON.VertexBuffer.UV3Kind
  27160. * - BABYLON.VertexBuffer.UV4Kind
  27161. * - BABYLON.VertexBuffer.UV5Kind
  27162. * - BABYLON.VertexBuffer.UV6Kind
  27163. * - BABYLON.VertexBuffer.ColorKind
  27164. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27165. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27166. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27167. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27168. */
  27169. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27170. if (!this._geometry) {
  27171. if (this._delayInfo) {
  27172. return this._delayInfo.indexOf(kind) !== -1;
  27173. }
  27174. return false;
  27175. }
  27176. return this._geometry.isVertexBufferUpdatable(kind);
  27177. };
  27178. /**
  27179. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27180. * Possible `kind` values :
  27181. * - BABYLON.VertexBuffer.PositionKind
  27182. * - BABYLON.VertexBuffer.UVKind
  27183. * - BABYLON.VertexBuffer.UV2Kind
  27184. * - BABYLON.VertexBuffer.UV3Kind
  27185. * - BABYLON.VertexBuffer.UV4Kind
  27186. * - BABYLON.VertexBuffer.UV5Kind
  27187. * - BABYLON.VertexBuffer.UV6Kind
  27188. * - BABYLON.VertexBuffer.ColorKind
  27189. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27190. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27191. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27192. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27193. */
  27194. Mesh.prototype.getVerticesDataKinds = function () {
  27195. if (!this._geometry) {
  27196. var result = new Array();
  27197. if (this._delayInfo) {
  27198. this._delayInfo.forEach(function (kind, index, array) {
  27199. result.push(kind);
  27200. });
  27201. }
  27202. return result;
  27203. }
  27204. return this._geometry.getVerticesDataKinds();
  27205. };
  27206. /**
  27207. * Returns a positive integer : the total number of indices in this mesh geometry.
  27208. * Returns zero if the mesh has no geometry.
  27209. */
  27210. Mesh.prototype.getTotalIndices = function () {
  27211. if (!this._geometry) {
  27212. return 0;
  27213. }
  27214. return this._geometry.getTotalIndices();
  27215. };
  27216. /**
  27217. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27218. * 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.
  27219. * Returns an empty array if the mesh has no geometry.
  27220. */
  27221. Mesh.prototype.getIndices = function (copyWhenShared) {
  27222. if (!this._geometry) {
  27223. return [];
  27224. }
  27225. return this._geometry.getIndices(copyWhenShared);
  27226. };
  27227. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27228. get: function () {
  27229. return this._masterMesh !== null && this._masterMesh !== undefined;
  27230. },
  27231. enumerable: true,
  27232. configurable: true
  27233. });
  27234. /**
  27235. * Determine if the current mesh is ready to be rendered
  27236. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27237. * @returns true if all associated assets are ready (material, textures, shaders)
  27238. */
  27239. Mesh.prototype.isReady = function (forceInstanceSupport) {
  27240. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27241. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27242. return false;
  27243. }
  27244. if (!_super.prototype.isReady.call(this)) {
  27245. return false;
  27246. }
  27247. if (!this.subMeshes || this.subMeshes.length === 0) {
  27248. return true;
  27249. }
  27250. var engine = this.getEngine();
  27251. var scene = this.getScene();
  27252. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27253. this.computeWorldMatrix();
  27254. var mat = this.material || scene.defaultMaterial;
  27255. if (mat) {
  27256. if (mat.storeEffectOnSubMeshes) {
  27257. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27258. var subMesh = _a[_i];
  27259. var effectiveMaterial = subMesh.getMaterial();
  27260. if (effectiveMaterial) {
  27261. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27262. return false;
  27263. }
  27264. }
  27265. }
  27266. }
  27267. else {
  27268. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27269. return false;
  27270. }
  27271. }
  27272. }
  27273. // Shadows
  27274. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27275. var light = _c[_b];
  27276. var generator = light.getShadowGenerator();
  27277. if (generator) {
  27278. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27279. var subMesh = _e[_d];
  27280. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27281. return false;
  27282. }
  27283. }
  27284. }
  27285. }
  27286. // LOD
  27287. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27288. var lod = _g[_f];
  27289. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27290. return false;
  27291. }
  27292. }
  27293. return true;
  27294. };
  27295. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27296. /**
  27297. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27298. * This property is pertinent only for updatable parametric shapes.
  27299. */
  27300. get: function () {
  27301. return this._areNormalsFrozen;
  27302. },
  27303. enumerable: true,
  27304. configurable: true
  27305. });
  27306. /**
  27307. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27308. * It has no effect at all on other shapes.
  27309. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27310. * Returns the Mesh.
  27311. */
  27312. Mesh.prototype.freezeNormals = function () {
  27313. this._areNormalsFrozen = true;
  27314. return this;
  27315. };
  27316. /**
  27317. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27318. * It has no effect at all on other shapes.
  27319. * It reactivates the mesh normals computation if it was previously frozen.
  27320. * Returns the Mesh.
  27321. */
  27322. Mesh.prototype.unfreezeNormals = function () {
  27323. this._areNormalsFrozen = false;
  27324. return this;
  27325. };
  27326. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27327. /**
  27328. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27329. */
  27330. set: function (count) {
  27331. this._overridenInstanceCount = count;
  27332. },
  27333. enumerable: true,
  27334. configurable: true
  27335. });
  27336. // Methods
  27337. Mesh.prototype._preActivate = function () {
  27338. var sceneRenderId = this.getScene().getRenderId();
  27339. if (this._preActivateId === sceneRenderId) {
  27340. return this;
  27341. }
  27342. this._preActivateId = sceneRenderId;
  27343. this._visibleInstances = null;
  27344. return this;
  27345. };
  27346. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27347. if (this._visibleInstances) {
  27348. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27349. }
  27350. return this;
  27351. };
  27352. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27353. if (!this._visibleInstances) {
  27354. this._visibleInstances = {};
  27355. this._visibleInstances.defaultRenderId = renderId;
  27356. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27357. }
  27358. if (!this._visibleInstances[renderId]) {
  27359. this._visibleInstances[renderId] = new Array();
  27360. }
  27361. this._visibleInstances[renderId].push(instance);
  27362. return this;
  27363. };
  27364. /**
  27365. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27366. * This means the mesh underlying bounding box and sphere are recomputed.
  27367. * Returns the Mesh.
  27368. */
  27369. Mesh.prototype.refreshBoundingInfo = function () {
  27370. return this._refreshBoundingInfo(false);
  27371. };
  27372. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27373. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27374. return this;
  27375. }
  27376. var data = this._getPositionData(applySkeleton);
  27377. if (data) {
  27378. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27379. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27380. }
  27381. if (this.subMeshes) {
  27382. for (var index = 0; index < this.subMeshes.length; index++) {
  27383. this.subMeshes[index].refreshBoundingInfo();
  27384. }
  27385. }
  27386. this._updateBoundingInfo();
  27387. return this;
  27388. };
  27389. Mesh.prototype._getPositionData = function (applySkeleton) {
  27390. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27391. if (data && applySkeleton && this.skeleton) {
  27392. data = BABYLON.Tools.Slice(data);
  27393. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27394. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27395. if (matricesWeightsData && matricesIndicesData) {
  27396. var needExtras = this.numBoneInfluencers > 4;
  27397. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27398. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27399. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27400. var tempVector = BABYLON.Tmp.Vector3[0];
  27401. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27402. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27403. var matWeightIdx = 0;
  27404. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27405. finalMatrix.reset();
  27406. var inf;
  27407. var weight;
  27408. for (inf = 0; inf < 4; inf++) {
  27409. weight = matricesWeightsData[matWeightIdx + inf];
  27410. if (weight <= 0)
  27411. break;
  27412. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27413. finalMatrix.addToSelf(tempMatrix);
  27414. }
  27415. if (needExtras) {
  27416. for (inf = 0; inf < 4; inf++) {
  27417. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27418. if (weight <= 0)
  27419. break;
  27420. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27421. finalMatrix.addToSelf(tempMatrix);
  27422. }
  27423. }
  27424. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27425. tempVector.toArray(data, index);
  27426. }
  27427. }
  27428. }
  27429. return data;
  27430. };
  27431. Mesh.prototype._createGlobalSubMesh = function (force) {
  27432. var totalVertices = this.getTotalVertices();
  27433. if (!totalVertices || !this.getIndices()) {
  27434. return null;
  27435. }
  27436. // Check if we need to recreate the submeshes
  27437. if (this.subMeshes && this.subMeshes.length > 0) {
  27438. var ib = this.getIndices();
  27439. if (!ib) {
  27440. return null;
  27441. }
  27442. var totalIndices = ib.length;
  27443. var needToRecreate = false;
  27444. if (force) {
  27445. needToRecreate = true;
  27446. }
  27447. else {
  27448. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27449. var submesh = _a[_i];
  27450. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27451. needToRecreate = true;
  27452. break;
  27453. }
  27454. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27455. needToRecreate = true;
  27456. break;
  27457. }
  27458. }
  27459. }
  27460. if (!needToRecreate) {
  27461. return this.subMeshes[0];
  27462. }
  27463. }
  27464. this.releaseSubMeshes();
  27465. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27466. };
  27467. Mesh.prototype.subdivide = function (count) {
  27468. if (count < 1) {
  27469. return;
  27470. }
  27471. var totalIndices = this.getTotalIndices();
  27472. var subdivisionSize = (totalIndices / count) | 0;
  27473. var offset = 0;
  27474. // Ensure that subdivisionSize is a multiple of 3
  27475. while (subdivisionSize % 3 !== 0) {
  27476. subdivisionSize++;
  27477. }
  27478. this.releaseSubMeshes();
  27479. for (var index = 0; index < count; index++) {
  27480. if (offset >= totalIndices) {
  27481. break;
  27482. }
  27483. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27484. offset += subdivisionSize;
  27485. }
  27486. this.synchronizeInstances();
  27487. };
  27488. /**
  27489. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27490. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27491. * The `data` are either a numeric array either a Float32Array.
  27492. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27493. * 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).
  27494. * Note that a new underlying VertexBuffer object is created each call.
  27495. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27496. *
  27497. * Possible `kind` values :
  27498. * - BABYLON.VertexBuffer.PositionKind
  27499. * - BABYLON.VertexBuffer.UVKind
  27500. * - BABYLON.VertexBuffer.UV2Kind
  27501. * - BABYLON.VertexBuffer.UV3Kind
  27502. * - BABYLON.VertexBuffer.UV4Kind
  27503. * - BABYLON.VertexBuffer.UV5Kind
  27504. * - BABYLON.VertexBuffer.UV6Kind
  27505. * - BABYLON.VertexBuffer.ColorKind
  27506. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27507. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27508. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27509. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27510. *
  27511. * Returns the Mesh.
  27512. */
  27513. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27514. if (updatable === void 0) { updatable = false; }
  27515. if (!this._geometry) {
  27516. var vertexData = new BABYLON.VertexData();
  27517. vertexData.set(data, kind);
  27518. var scene = this.getScene();
  27519. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27520. }
  27521. else {
  27522. this._geometry.setVerticesData(kind, data, updatable, stride);
  27523. }
  27524. return this;
  27525. };
  27526. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  27527. if (updatable === void 0) { updatable = true; }
  27528. var vb = this.getVertexBuffer(kind);
  27529. if (!vb || vb.isUpdatable() === updatable) {
  27530. return;
  27531. }
  27532. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  27533. };
  27534. /**
  27535. * Sets the mesh VertexBuffer.
  27536. * Returns the Mesh.
  27537. */
  27538. Mesh.prototype.setVerticesBuffer = function (buffer) {
  27539. if (!this._geometry) {
  27540. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  27541. }
  27542. this._geometry.setVerticesBuffer(buffer);
  27543. return this;
  27544. };
  27545. /**
  27546. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  27547. * If the mesh has no geometry, it is simply returned as it is.
  27548. * The `data` are either a numeric array either a Float32Array.
  27549. * No new underlying VertexBuffer object is created.
  27550. * 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.
  27551. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  27552. *
  27553. * Possible `kind` values :
  27554. * - BABYLON.VertexBuffer.PositionKind
  27555. * - BABYLON.VertexBuffer.UVKind
  27556. * - BABYLON.VertexBuffer.UV2Kind
  27557. * - BABYLON.VertexBuffer.UV3Kind
  27558. * - BABYLON.VertexBuffer.UV4Kind
  27559. * - BABYLON.VertexBuffer.UV5Kind
  27560. * - BABYLON.VertexBuffer.UV6Kind
  27561. * - BABYLON.VertexBuffer.ColorKind
  27562. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27563. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27564. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27565. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27566. *
  27567. * Returns the Mesh.
  27568. */
  27569. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  27570. if (!this._geometry) {
  27571. return this;
  27572. }
  27573. if (!makeItUnique) {
  27574. this._geometry.updateVerticesData(kind, data, updateExtends);
  27575. }
  27576. else {
  27577. this.makeGeometryUnique();
  27578. this.updateVerticesData(kind, data, updateExtends, false);
  27579. }
  27580. return this;
  27581. };
  27582. /**
  27583. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  27584. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  27585. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  27586. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  27587. * Returns the Mesh.
  27588. */
  27589. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  27590. if (computeNormals === void 0) { computeNormals = true; }
  27591. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27592. if (!positions) {
  27593. return this;
  27594. }
  27595. positionFunction(positions);
  27596. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  27597. if (computeNormals) {
  27598. var indices = this.getIndices();
  27599. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27600. if (!normals) {
  27601. return this;
  27602. }
  27603. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  27604. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  27605. }
  27606. return this;
  27607. };
  27608. /**
  27609. * Creates a un-shared specific occurence of the geometry for the mesh.
  27610. * Returns the Mesh.
  27611. */
  27612. Mesh.prototype.makeGeometryUnique = function () {
  27613. if (!this._geometry) {
  27614. return this;
  27615. }
  27616. var oldGeometry = this._geometry;
  27617. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  27618. oldGeometry.releaseForMesh(this, true);
  27619. geometry.applyToMesh(this);
  27620. return this;
  27621. };
  27622. /**
  27623. * Sets the mesh indices.
  27624. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  27625. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  27626. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  27627. * This method creates a new index buffer each call.
  27628. * Returns the Mesh.
  27629. */
  27630. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  27631. if (totalVertices === void 0) { totalVertices = null; }
  27632. if (updatable === void 0) { updatable = false; }
  27633. if (!this._geometry) {
  27634. var vertexData = new BABYLON.VertexData();
  27635. vertexData.indices = indices;
  27636. var scene = this.getScene();
  27637. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27638. }
  27639. else {
  27640. this._geometry.setIndices(indices, totalVertices, updatable);
  27641. }
  27642. return this;
  27643. };
  27644. /**
  27645. * Update the current index buffer
  27646. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  27647. * Returns the Mesh.
  27648. */
  27649. Mesh.prototype.updateIndices = function (indices, offset) {
  27650. if (!this._geometry) {
  27651. return this;
  27652. }
  27653. this._geometry.updateIndices(indices, offset);
  27654. return this;
  27655. };
  27656. /**
  27657. * Invert the geometry to move from a right handed system to a left handed one.
  27658. * Returns the Mesh.
  27659. */
  27660. Mesh.prototype.toLeftHanded = function () {
  27661. if (!this._geometry) {
  27662. return this;
  27663. }
  27664. this._geometry.toLeftHanded();
  27665. return this;
  27666. };
  27667. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  27668. if (!this._geometry) {
  27669. return this;
  27670. }
  27671. var engine = this.getScene().getEngine();
  27672. // Wireframe
  27673. var indexToBind;
  27674. if (this._unIndexed) {
  27675. indexToBind = null;
  27676. }
  27677. else {
  27678. switch (fillMode) {
  27679. case BABYLON.Material.PointFillMode:
  27680. indexToBind = null;
  27681. break;
  27682. case BABYLON.Material.WireFrameFillMode:
  27683. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  27684. break;
  27685. default:
  27686. case BABYLON.Material.TriangleFillMode:
  27687. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  27688. break;
  27689. }
  27690. }
  27691. // VBOs
  27692. this._geometry._bind(effect, indexToBind);
  27693. return this;
  27694. };
  27695. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  27696. if (alternate === void 0) { alternate = false; }
  27697. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27698. return this;
  27699. }
  27700. this.onBeforeDrawObservable.notifyObservers(this);
  27701. var scene = this.getScene();
  27702. var engine = scene.getEngine();
  27703. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  27704. // or triangles as points
  27705. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  27706. }
  27707. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  27708. // Triangles as wireframe
  27709. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  27710. }
  27711. else {
  27712. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  27713. }
  27714. if (scene._isAlternateRenderingEnabled && !alternate) {
  27715. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  27716. if (!effect || !scene.activeCamera) {
  27717. return this;
  27718. }
  27719. scene._switchToAlternateCameraConfiguration(true);
  27720. this._effectiveMaterial.bindView(effect);
  27721. this._effectiveMaterial.bindViewProjection(effect);
  27722. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  27723. this._draw(subMesh, fillMode, instancesCount, true);
  27724. engine.setViewport(scene.activeCamera.viewport);
  27725. scene._switchToAlternateCameraConfiguration(false);
  27726. this._effectiveMaterial.bindView(effect);
  27727. this._effectiveMaterial.bindViewProjection(effect);
  27728. }
  27729. return this;
  27730. };
  27731. /**
  27732. * Registers for this mesh a javascript function called just before the rendering process.
  27733. * This function is passed the current mesh.
  27734. * Return the Mesh.
  27735. */
  27736. Mesh.prototype.registerBeforeRender = function (func) {
  27737. this.onBeforeRenderObservable.add(func);
  27738. return this;
  27739. };
  27740. /**
  27741. * Disposes a previously registered javascript function called before the rendering.
  27742. * This function is passed the current mesh.
  27743. * Returns the Mesh.
  27744. */
  27745. Mesh.prototype.unregisterBeforeRender = function (func) {
  27746. this.onBeforeRenderObservable.removeCallback(func);
  27747. return this;
  27748. };
  27749. /**
  27750. * Registers for this mesh a javascript function called just after the rendering is complete.
  27751. * This function is passed the current mesh.
  27752. * Returns the Mesh.
  27753. */
  27754. Mesh.prototype.registerAfterRender = function (func) {
  27755. this.onAfterRenderObservable.add(func);
  27756. return this;
  27757. };
  27758. /**
  27759. * Disposes a previously registered javascript function called after the rendering.
  27760. * This function is passed the current mesh.
  27761. * Return the Mesh.
  27762. */
  27763. Mesh.prototype.unregisterAfterRender = function (func) {
  27764. this.onAfterRenderObservable.removeCallback(func);
  27765. return this;
  27766. };
  27767. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  27768. var scene = this.getScene();
  27769. this._batchCache.mustReturn = false;
  27770. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  27771. this._batchCache.visibleInstances[subMeshId] = null;
  27772. if (this._visibleInstances) {
  27773. var currentRenderId = scene.getRenderId();
  27774. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  27775. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  27776. var selfRenderId = this._renderId;
  27777. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  27778. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  27779. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  27780. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  27781. }
  27782. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  27783. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  27784. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  27785. this._batchCache.mustReturn = true;
  27786. return this._batchCache;
  27787. }
  27788. if (currentRenderId !== selfRenderId) {
  27789. this._batchCache.renderSelf[subMeshId] = false;
  27790. }
  27791. }
  27792. this._renderIdForInstances[subMeshId] = currentRenderId;
  27793. }
  27794. return this._batchCache;
  27795. };
  27796. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  27797. var visibleInstances = batch.visibleInstances[subMesh._id];
  27798. if (!visibleInstances) {
  27799. return this;
  27800. }
  27801. var matricesCount = visibleInstances.length + 1;
  27802. var bufferSize = matricesCount * 16 * 4;
  27803. var currentInstancesBufferSize = this._instancesBufferSize;
  27804. var instancesBuffer = this._instancesBuffer;
  27805. while (this._instancesBufferSize < bufferSize) {
  27806. this._instancesBufferSize *= 2;
  27807. }
  27808. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  27809. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  27810. }
  27811. var offset = 0;
  27812. var instancesCount = 0;
  27813. var world = this.getWorldMatrix();
  27814. if (batch.renderSelf[subMesh._id]) {
  27815. world.copyToArray(this._instancesData, offset);
  27816. offset += 16;
  27817. instancesCount++;
  27818. }
  27819. if (visibleInstances) {
  27820. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  27821. var instance = visibleInstances[instanceIndex];
  27822. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  27823. offset += 16;
  27824. instancesCount++;
  27825. }
  27826. }
  27827. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  27828. if (instancesBuffer) {
  27829. instancesBuffer.dispose();
  27830. }
  27831. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  27832. this._instancesBuffer = instancesBuffer;
  27833. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  27834. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  27835. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  27836. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  27837. }
  27838. else {
  27839. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  27840. }
  27841. this._bind(subMesh, effect, fillMode);
  27842. this._draw(subMesh, fillMode, instancesCount);
  27843. engine.unbindInstanceAttributes();
  27844. return this;
  27845. };
  27846. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  27847. var scene = this.getScene();
  27848. var engine = scene.getEngine();
  27849. if (hardwareInstancedRendering) {
  27850. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  27851. }
  27852. else {
  27853. if (batch.renderSelf[subMesh._id]) {
  27854. // Draw
  27855. if (onBeforeDraw) {
  27856. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  27857. }
  27858. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  27859. }
  27860. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  27861. if (visibleInstancesForSubMesh) {
  27862. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  27863. var instance = visibleInstancesForSubMesh[instanceIndex];
  27864. // World
  27865. var world = instance.getWorldMatrix();
  27866. if (onBeforeDraw) {
  27867. onBeforeDraw(true, world, effectiveMaterial);
  27868. }
  27869. // Draw
  27870. this._draw(subMesh, fillMode);
  27871. }
  27872. }
  27873. }
  27874. return this;
  27875. };
  27876. /**
  27877. * Triggers the draw call for the mesh.
  27878. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  27879. * Returns the Mesh.
  27880. */
  27881. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  27882. this.checkOcclusionQuery();
  27883. if (this._isOccluded) {
  27884. return this;
  27885. }
  27886. var scene = this.getScene();
  27887. // Managing instances
  27888. var batch = this._getInstancesRenderList(subMesh._id);
  27889. if (batch.mustReturn) {
  27890. return this;
  27891. }
  27892. // Checking geometry state
  27893. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27894. return this;
  27895. }
  27896. this.onBeforeRenderObservable.notifyObservers(this);
  27897. var engine = scene.getEngine();
  27898. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27899. // Material
  27900. var material = subMesh.getMaterial();
  27901. if (!material) {
  27902. return this;
  27903. }
  27904. this._effectiveMaterial = material;
  27905. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27906. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27907. return this;
  27908. }
  27909. }
  27910. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  27911. return this;
  27912. }
  27913. // Alpha mode
  27914. if (enableAlphaMode) {
  27915. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  27916. }
  27917. // Outline - step 1
  27918. var savedDepthWrite = engine.getDepthWrite();
  27919. if (this.renderOutline) {
  27920. engine.setDepthWrite(false);
  27921. scene.getOutlineRenderer().render(subMesh, batch);
  27922. engine.setDepthWrite(savedDepthWrite);
  27923. }
  27924. var effect;
  27925. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27926. effect = subMesh.effect;
  27927. }
  27928. else {
  27929. effect = this._effectiveMaterial.getEffect();
  27930. }
  27931. if (!effect) {
  27932. return this;
  27933. }
  27934. var sideOrientation = this.overrideMaterialSideOrientation;
  27935. if (sideOrientation == null) {
  27936. sideOrientation = this._effectiveMaterial.sideOrientation;
  27937. if (this._getWorldMatrixDeterminant() < 0) {
  27938. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  27939. }
  27940. }
  27941. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  27942. if (this._effectiveMaterial.forceDepthWrite) {
  27943. engine.setDepthWrite(true);
  27944. }
  27945. // Bind
  27946. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  27947. if (!hardwareInstancedRendering) {
  27948. this._bind(subMesh, effect, fillMode);
  27949. }
  27950. var world = this.getWorldMatrix();
  27951. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27952. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  27953. }
  27954. else {
  27955. this._effectiveMaterial.bind(world, this);
  27956. }
  27957. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  27958. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  27959. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27960. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  27961. }
  27962. // Draw
  27963. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27964. // Unbind
  27965. this._effectiveMaterial.unbind();
  27966. // Outline - step 2
  27967. if (this.renderOutline && savedDepthWrite) {
  27968. engine.setDepthWrite(true);
  27969. engine.setColorWrite(false);
  27970. scene.getOutlineRenderer().render(subMesh, batch);
  27971. engine.setColorWrite(true);
  27972. }
  27973. // Overlay
  27974. if (this.renderOverlay) {
  27975. var currentMode = engine.getAlphaMode();
  27976. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27977. scene.getOutlineRenderer().render(subMesh, batch, true);
  27978. engine.setAlphaMode(currentMode);
  27979. }
  27980. this.onAfterRenderObservable.notifyObservers(this);
  27981. return this;
  27982. };
  27983. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  27984. if (isInstance && effectiveMaterial) {
  27985. effectiveMaterial.bindOnlyWorldMatrix(world);
  27986. }
  27987. };
  27988. /**
  27989. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  27990. */
  27991. Mesh.prototype.getEmittedParticleSystems = function () {
  27992. var results = new Array();
  27993. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27994. var particleSystem = this.getScene().particleSystems[index];
  27995. if (particleSystem.emitter === this) {
  27996. results.push(particleSystem);
  27997. }
  27998. }
  27999. return results;
  28000. };
  28001. /**
  28002. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28003. */
  28004. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28005. var results = new Array();
  28006. var descendants = this.getDescendants();
  28007. descendants.push(this);
  28008. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28009. var particleSystem = this.getScene().particleSystems[index];
  28010. var emitter = particleSystem.emitter;
  28011. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28012. results.push(particleSystem);
  28013. }
  28014. }
  28015. return results;
  28016. };
  28017. Mesh.prototype._checkDelayState = function () {
  28018. var scene = this.getScene();
  28019. if (this._geometry) {
  28020. this._geometry.load(scene);
  28021. }
  28022. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28023. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28024. this._queueLoad(scene);
  28025. }
  28026. return this;
  28027. };
  28028. Mesh.prototype._queueLoad = function (scene) {
  28029. var _this = this;
  28030. scene._addPendingData(this);
  28031. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28032. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28033. if (data instanceof ArrayBuffer) {
  28034. _this._delayLoadingFunction(data, _this);
  28035. }
  28036. else {
  28037. _this._delayLoadingFunction(JSON.parse(data), _this);
  28038. }
  28039. _this.instances.forEach(function (instance) {
  28040. instance._syncSubMeshes();
  28041. });
  28042. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28043. scene._removePendingData(_this);
  28044. }, function () { }, scene.database, getBinaryData);
  28045. return this;
  28046. };
  28047. /**
  28048. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28049. */
  28050. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28051. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28052. return false;
  28053. }
  28054. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28055. return false;
  28056. }
  28057. this._checkDelayState();
  28058. return true;
  28059. };
  28060. /**
  28061. * Sets the mesh material by the material or multiMaterial `id` property.
  28062. * The material `id` is a string identifying the material or the multiMaterial.
  28063. * This method returns the Mesh.
  28064. */
  28065. Mesh.prototype.setMaterialByID = function (id) {
  28066. var materials = this.getScene().materials;
  28067. var index;
  28068. for (index = materials.length - 1; index > -1; index--) {
  28069. if (materials[index].id === id) {
  28070. this.material = materials[index];
  28071. return this;
  28072. }
  28073. }
  28074. // Multi
  28075. var multiMaterials = this.getScene().multiMaterials;
  28076. for (index = multiMaterials.length - 1; index > -1; index--) {
  28077. if (multiMaterials[index].id === id) {
  28078. this.material = multiMaterials[index];
  28079. return this;
  28080. }
  28081. }
  28082. return this;
  28083. };
  28084. /**
  28085. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28086. */
  28087. Mesh.prototype.getAnimatables = function () {
  28088. var results = new Array();
  28089. if (this.material) {
  28090. results.push(this.material);
  28091. }
  28092. if (this.skeleton) {
  28093. results.push(this.skeleton);
  28094. }
  28095. return results;
  28096. };
  28097. /**
  28098. * Modifies the mesh geometry according to the passed transformation matrix.
  28099. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28100. * The mesh normals are modified accordingly the same transformation.
  28101. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28102. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28103. * Returns the Mesh.
  28104. */
  28105. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28106. // Position
  28107. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28108. return this;
  28109. }
  28110. var submeshes = this.subMeshes.splice(0);
  28111. this._resetPointsArrayCache();
  28112. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28113. var temp = new Array();
  28114. var index;
  28115. for (index = 0; index < data.length; index += 3) {
  28116. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28117. }
  28118. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28119. // Normals
  28120. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28121. return this;
  28122. }
  28123. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28124. temp = [];
  28125. for (index = 0; index < data.length; index += 3) {
  28126. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28127. }
  28128. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28129. // flip faces?
  28130. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28131. this.flipFaces();
  28132. }
  28133. // Restore submeshes
  28134. this.releaseSubMeshes();
  28135. this.subMeshes = submeshes;
  28136. return this;
  28137. };
  28138. /**
  28139. * Modifies the mesh geometry according to its own current World Matrix.
  28140. * The mesh World Matrix is then reset.
  28141. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28142. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28143. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28144. * Returns the Mesh.
  28145. */
  28146. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28147. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28148. this.scaling.copyFromFloats(1, 1, 1);
  28149. this.position.copyFromFloats(0, 0, 0);
  28150. this.rotation.copyFromFloats(0, 0, 0);
  28151. //only if quaternion is already set
  28152. if (this.rotationQuaternion) {
  28153. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28154. }
  28155. this._worldMatrix = BABYLON.Matrix.Identity();
  28156. return this;
  28157. };
  28158. Object.defineProperty(Mesh.prototype, "_positions", {
  28159. // Cache
  28160. get: function () {
  28161. if (this._geometry) {
  28162. return this._geometry._positions;
  28163. }
  28164. return null;
  28165. },
  28166. enumerable: true,
  28167. configurable: true
  28168. });
  28169. Mesh.prototype._resetPointsArrayCache = function () {
  28170. if (this._geometry) {
  28171. this._geometry._resetPointsArrayCache();
  28172. }
  28173. return this;
  28174. };
  28175. Mesh.prototype._generatePointsArray = function () {
  28176. if (this._geometry) {
  28177. return this._geometry._generatePointsArray();
  28178. }
  28179. return false;
  28180. };
  28181. /**
  28182. * Returns a new Mesh object generated from the current mesh properties.
  28183. * This method must not get confused with createInstance().
  28184. * The parameter `name` is a string, the name given to the new mesh.
  28185. * The optional parameter `newParent` can be any Node object (default `null`).
  28186. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28187. * 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.
  28188. */
  28189. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28190. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28191. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28192. };
  28193. /**
  28194. * Disposes the Mesh.
  28195. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28196. * Returns nothing.
  28197. */
  28198. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28199. var _this = this;
  28200. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28201. this.morphTargetManager = null;
  28202. if (this._geometry) {
  28203. this._geometry.releaseForMesh(this, true);
  28204. }
  28205. // Sources
  28206. var meshes = this.getScene().meshes;
  28207. meshes.forEach(function (abstractMesh) {
  28208. var mesh = abstractMesh;
  28209. if (mesh._source && mesh._source === _this) {
  28210. mesh._source = null;
  28211. }
  28212. });
  28213. this._source = null;
  28214. // Instances
  28215. if (this._instancesBuffer) {
  28216. this._instancesBuffer.dispose();
  28217. this._instancesBuffer = null;
  28218. }
  28219. while (this.instances.length) {
  28220. this.instances[0].dispose();
  28221. }
  28222. // Effect layers.
  28223. var effectLayers = this.getScene().effectLayers;
  28224. for (var i = 0; i < effectLayers.length; i++) {
  28225. var effectLayer = effectLayers[i];
  28226. if (effectLayer) {
  28227. effectLayer._disposeMesh(this);
  28228. }
  28229. }
  28230. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28231. };
  28232. /**
  28233. * Modifies the mesh geometry according to a displacement map.
  28234. * 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.
  28235. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28236. * This method returns nothing.
  28237. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28238. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28239. * 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.
  28240. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28241. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28242. *
  28243. * Returns the Mesh.
  28244. */
  28245. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28246. var _this = this;
  28247. var scene = this.getScene();
  28248. var onload = function (img) {
  28249. // Getting height map data
  28250. var canvas = document.createElement("canvas");
  28251. var context = canvas.getContext("2d");
  28252. var heightMapWidth = img.width;
  28253. var heightMapHeight = img.height;
  28254. canvas.width = heightMapWidth;
  28255. canvas.height = heightMapHeight;
  28256. context.drawImage(img, 0, 0);
  28257. // Create VertexData from map data
  28258. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28259. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28260. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28261. //execute success callback, if set
  28262. if (onSuccess) {
  28263. onSuccess(_this);
  28264. }
  28265. };
  28266. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28267. return this;
  28268. };
  28269. /**
  28270. * Modifies the mesh geometry according to a displacementMap buffer.
  28271. * 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.
  28272. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28273. * This method returns nothing.
  28274. * 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.
  28275. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28276. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28277. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28278. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28279. *
  28280. * Returns the Mesh.
  28281. */
  28282. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28283. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28284. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28285. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28286. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28287. return this;
  28288. }
  28289. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28290. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28291. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28292. var position = BABYLON.Vector3.Zero();
  28293. var normal = BABYLON.Vector3.Zero();
  28294. var uv = BABYLON.Vector2.Zero();
  28295. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28296. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28297. for (var index = 0; index < positions.length; index += 3) {
  28298. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28299. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28300. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28301. // Compute height
  28302. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28303. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28304. var pos = (u + v * heightMapWidth) * 4;
  28305. var r = buffer[pos] / 255.0;
  28306. var g = buffer[pos + 1] / 255.0;
  28307. var b = buffer[pos + 2] / 255.0;
  28308. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28309. normal.normalize();
  28310. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28311. position = position.add(normal);
  28312. position.toArray(positions, index);
  28313. }
  28314. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28315. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28316. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28317. return this;
  28318. };
  28319. /**
  28320. * Modify the mesh to get a flat shading rendering.
  28321. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28322. * This method returns the Mesh.
  28323. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28324. */
  28325. Mesh.prototype.convertToFlatShadedMesh = function () {
  28326. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28327. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28328. var kinds = this.getVerticesDataKinds();
  28329. var vbs = {};
  28330. var data = {};
  28331. var newdata = {};
  28332. var updatableNormals = false;
  28333. var kindIndex;
  28334. var kind;
  28335. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28336. kind = kinds[kindIndex];
  28337. var vertexBuffer = this.getVertexBuffer(kind);
  28338. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28339. updatableNormals = vertexBuffer.isUpdatable();
  28340. kinds.splice(kindIndex, 1);
  28341. kindIndex--;
  28342. continue;
  28343. }
  28344. vbs[kind] = vertexBuffer;
  28345. data[kind] = vbs[kind].getData();
  28346. newdata[kind] = [];
  28347. }
  28348. // Save previous submeshes
  28349. var previousSubmeshes = this.subMeshes.slice(0);
  28350. var indices = this.getIndices();
  28351. var totalIndices = this.getTotalIndices();
  28352. // Generating unique vertices per face
  28353. var index;
  28354. for (index = 0; index < totalIndices; index++) {
  28355. var vertexIndex = indices[index];
  28356. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28357. kind = kinds[kindIndex];
  28358. var stride = vbs[kind].getStrideSize();
  28359. for (var offset = 0; offset < stride; offset++) {
  28360. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28361. }
  28362. }
  28363. }
  28364. // Updating faces & normal
  28365. var normals = [];
  28366. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28367. for (index = 0; index < totalIndices; index += 3) {
  28368. indices[index] = index;
  28369. indices[index + 1] = index + 1;
  28370. indices[index + 2] = index + 2;
  28371. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28372. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28373. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28374. var p1p2 = p1.subtract(p2);
  28375. var p3p2 = p3.subtract(p2);
  28376. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28377. // Store same normals for every vertex
  28378. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28379. normals.push(normal.x);
  28380. normals.push(normal.y);
  28381. normals.push(normal.z);
  28382. }
  28383. }
  28384. this.setIndices(indices);
  28385. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28386. // Updating vertex buffers
  28387. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28388. kind = kinds[kindIndex];
  28389. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28390. }
  28391. // Updating submeshes
  28392. this.releaseSubMeshes();
  28393. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28394. var previousOne = previousSubmeshes[submeshIndex];
  28395. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28396. }
  28397. this.synchronizeInstances();
  28398. return this;
  28399. };
  28400. /**
  28401. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28402. * In other words, more vertices, no more indices and a single bigger VBO.
  28403. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28404. * Returns the Mesh.
  28405. */
  28406. Mesh.prototype.convertToUnIndexedMesh = function () {
  28407. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28408. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28409. var kinds = this.getVerticesDataKinds();
  28410. var vbs = {};
  28411. var data = {};
  28412. var newdata = {};
  28413. var kindIndex;
  28414. var kind;
  28415. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28416. kind = kinds[kindIndex];
  28417. var vertexBuffer = this.getVertexBuffer(kind);
  28418. vbs[kind] = vertexBuffer;
  28419. data[kind] = vbs[kind].getData();
  28420. newdata[kind] = [];
  28421. }
  28422. // Save previous submeshes
  28423. var previousSubmeshes = this.subMeshes.slice(0);
  28424. var indices = this.getIndices();
  28425. var totalIndices = this.getTotalIndices();
  28426. // Generating unique vertices per face
  28427. var index;
  28428. for (index = 0; index < totalIndices; index++) {
  28429. var vertexIndex = indices[index];
  28430. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28431. kind = kinds[kindIndex];
  28432. var stride = vbs[kind].getStrideSize();
  28433. for (var offset = 0; offset < stride; offset++) {
  28434. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28435. }
  28436. }
  28437. }
  28438. // Updating indices
  28439. for (index = 0; index < totalIndices; index += 3) {
  28440. indices[index] = index;
  28441. indices[index + 1] = index + 1;
  28442. indices[index + 2] = index + 2;
  28443. }
  28444. this.setIndices(indices);
  28445. // Updating vertex buffers
  28446. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28447. kind = kinds[kindIndex];
  28448. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28449. }
  28450. // Updating submeshes
  28451. this.releaseSubMeshes();
  28452. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28453. var previousOne = previousSubmeshes[submeshIndex];
  28454. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28455. }
  28456. this._unIndexed = true;
  28457. this.synchronizeInstances();
  28458. return this;
  28459. };
  28460. /**
  28461. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28462. * This method returns the Mesh.
  28463. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28464. */
  28465. Mesh.prototype.flipFaces = function (flipNormals) {
  28466. if (flipNormals === void 0) { flipNormals = false; }
  28467. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28468. var i;
  28469. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28470. for (i = 0; i < vertex_data.normals.length; i++) {
  28471. vertex_data.normals[i] *= -1;
  28472. }
  28473. }
  28474. if (vertex_data.indices) {
  28475. var temp;
  28476. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28477. // reassign indices
  28478. temp = vertex_data.indices[i + 1];
  28479. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28480. vertex_data.indices[i + 2] = temp;
  28481. }
  28482. }
  28483. vertex_data.applyToMesh(this);
  28484. return this;
  28485. };
  28486. // Instances
  28487. /**
  28488. * Creates a new InstancedMesh object from the mesh model.
  28489. * An instance shares the same properties and the same material than its model.
  28490. * Only these properties of each instance can then be set individually :
  28491. * - position
  28492. * - rotation
  28493. * - rotationQuaternion
  28494. * - setPivotMatrix
  28495. * - scaling
  28496. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28497. * Warning : this method is not supported for Line mesh and LineSystem
  28498. */
  28499. Mesh.prototype.createInstance = function (name) {
  28500. return new BABYLON.InstancedMesh(name, this);
  28501. };
  28502. /**
  28503. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28504. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28505. * This method returns the Mesh.
  28506. */
  28507. Mesh.prototype.synchronizeInstances = function () {
  28508. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28509. var instance = this.instances[instanceIndex];
  28510. instance._syncSubMeshes();
  28511. }
  28512. return this;
  28513. };
  28514. /**
  28515. * Simplify the mesh according to the given array of settings.
  28516. * Function will return immediately and will simplify async. It returns the Mesh.
  28517. * @param settings a collection of simplification settings.
  28518. * @param parallelProcessing should all levels calculate parallel or one after the other.
  28519. * @param type the type of simplification to run.
  28520. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  28521. */
  28522. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  28523. if (parallelProcessing === void 0) { parallelProcessing = true; }
  28524. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  28525. this.getScene().simplificationQueue.addTask({
  28526. settings: settings,
  28527. parallelProcessing: parallelProcessing,
  28528. mesh: this,
  28529. simplificationType: simplificationType,
  28530. successCallback: successCallback
  28531. });
  28532. return this;
  28533. };
  28534. /**
  28535. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  28536. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  28537. * This should be used together with the simplification to avoid disappearing triangles.
  28538. * Returns the Mesh.
  28539. * @param successCallback an optional success callback to be called after the optimization finished.
  28540. */
  28541. Mesh.prototype.optimizeIndices = function (successCallback) {
  28542. var _this = this;
  28543. var indices = this.getIndices();
  28544. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28545. if (!positions || !indices) {
  28546. return this;
  28547. }
  28548. var vectorPositions = new Array();
  28549. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  28550. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  28551. }
  28552. var dupes = new Array();
  28553. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  28554. var realPos = vectorPositions.length - 1 - iteration;
  28555. var testedPosition = vectorPositions[realPos];
  28556. for (var j = 0; j < realPos; ++j) {
  28557. var againstPosition = vectorPositions[j];
  28558. if (testedPosition.equals(againstPosition)) {
  28559. dupes[realPos] = j;
  28560. break;
  28561. }
  28562. }
  28563. }, function () {
  28564. for (var i = 0; i < indices.length; ++i) {
  28565. indices[i] = dupes[indices[i]] || indices[i];
  28566. }
  28567. //indices are now reordered
  28568. var originalSubMeshes = _this.subMeshes.slice(0);
  28569. _this.setIndices(indices);
  28570. _this.subMeshes = originalSubMeshes;
  28571. if (successCallback) {
  28572. successCallback(_this);
  28573. }
  28574. });
  28575. return this;
  28576. };
  28577. Mesh.prototype.serialize = function (serializationObject) {
  28578. serializationObject.name = this.name;
  28579. serializationObject.id = this.id;
  28580. serializationObject.type = this.getClassName();
  28581. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28582. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28583. }
  28584. serializationObject.position = this.position.asArray();
  28585. if (this.rotationQuaternion) {
  28586. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  28587. }
  28588. else if (this.rotation) {
  28589. serializationObject.rotation = this.rotation.asArray();
  28590. }
  28591. serializationObject.scaling = this.scaling.asArray();
  28592. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  28593. serializationObject.isEnabled = this.isEnabled(false);
  28594. serializationObject.isVisible = this.isVisible;
  28595. serializationObject.infiniteDistance = this.infiniteDistance;
  28596. serializationObject.pickable = this.isPickable;
  28597. serializationObject.receiveShadows = this.receiveShadows;
  28598. serializationObject.billboardMode = this.billboardMode;
  28599. serializationObject.visibility = this.visibility;
  28600. serializationObject.checkCollisions = this.checkCollisions;
  28601. serializationObject.isBlocker = this.isBlocker;
  28602. // Parent
  28603. if (this.parent) {
  28604. serializationObject.parentId = this.parent.id;
  28605. }
  28606. // Geometry
  28607. serializationObject.isUnIndexed = this.isUnIndexed;
  28608. var geometry = this._geometry;
  28609. if (geometry) {
  28610. var geometryId = geometry.id;
  28611. serializationObject.geometryId = geometryId;
  28612. // SubMeshes
  28613. serializationObject.subMeshes = [];
  28614. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  28615. var subMesh = this.subMeshes[subIndex];
  28616. serializationObject.subMeshes.push({
  28617. materialIndex: subMesh.materialIndex,
  28618. verticesStart: subMesh.verticesStart,
  28619. verticesCount: subMesh.verticesCount,
  28620. indexStart: subMesh.indexStart,
  28621. indexCount: subMesh.indexCount
  28622. });
  28623. }
  28624. }
  28625. // Material
  28626. if (this.material) {
  28627. serializationObject.materialId = this.material.id;
  28628. }
  28629. else {
  28630. this.material = null;
  28631. }
  28632. // Morph targets
  28633. if (this.morphTargetManager) {
  28634. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  28635. }
  28636. // Skeleton
  28637. if (this.skeleton) {
  28638. serializationObject.skeletonId = this.skeleton.id;
  28639. }
  28640. // Physics
  28641. //TODO implement correct serialization for physics impostors.
  28642. var impostor = this.getPhysicsImpostor();
  28643. if (impostor) {
  28644. serializationObject.physicsMass = impostor.getParam("mass");
  28645. serializationObject.physicsFriction = impostor.getParam("friction");
  28646. serializationObject.physicsRestitution = impostor.getParam("mass");
  28647. serializationObject.physicsImpostor = impostor.type;
  28648. }
  28649. // Metadata
  28650. if (this.metadata) {
  28651. serializationObject.metadata = this.metadata;
  28652. }
  28653. // Instances
  28654. serializationObject.instances = [];
  28655. for (var index = 0; index < this.instances.length; index++) {
  28656. var instance = this.instances[index];
  28657. var serializationInstance = {
  28658. name: instance.name,
  28659. id: instance.id,
  28660. position: instance.position.asArray(),
  28661. scaling: instance.scaling.asArray()
  28662. };
  28663. if (instance.rotationQuaternion) {
  28664. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  28665. }
  28666. else if (instance.rotation) {
  28667. serializationInstance.rotation = instance.rotation.asArray();
  28668. }
  28669. serializationObject.instances.push(serializationInstance);
  28670. // Animations
  28671. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  28672. serializationInstance.ranges = instance.serializeAnimationRanges();
  28673. }
  28674. //
  28675. // Animations
  28676. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28677. serializationObject.ranges = this.serializeAnimationRanges();
  28678. // Layer mask
  28679. serializationObject.layerMask = this.layerMask;
  28680. // Alpha
  28681. serializationObject.alphaIndex = this.alphaIndex;
  28682. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  28683. // Overlay
  28684. serializationObject.overlayAlpha = this.overlayAlpha;
  28685. serializationObject.overlayColor = this.overlayColor.asArray();
  28686. serializationObject.renderOverlay = this.renderOverlay;
  28687. // Fog
  28688. serializationObject.applyFog = this.applyFog;
  28689. // Action Manager
  28690. if (this.actionManager) {
  28691. serializationObject.actions = this.actionManager.serialize(this.name);
  28692. }
  28693. };
  28694. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  28695. if (!this.geometry) {
  28696. return;
  28697. }
  28698. this._markSubMeshesAsAttributesDirty();
  28699. var morphTargetManager = this._morphTargetManager;
  28700. if (morphTargetManager && morphTargetManager.vertexCount) {
  28701. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  28702. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  28703. this.morphTargetManager = null;
  28704. return;
  28705. }
  28706. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  28707. var morphTarget = morphTargetManager.getActiveTarget(index);
  28708. var positions = morphTarget.getPositions();
  28709. if (!positions) {
  28710. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  28711. return;
  28712. }
  28713. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  28714. var normals = morphTarget.getNormals();
  28715. if (normals) {
  28716. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  28717. }
  28718. var tangents = morphTarget.getTangents();
  28719. if (tangents) {
  28720. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  28721. }
  28722. }
  28723. }
  28724. else {
  28725. var index = 0;
  28726. // Positions
  28727. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  28728. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  28729. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  28730. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  28731. }
  28732. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  28733. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  28734. }
  28735. index++;
  28736. }
  28737. }
  28738. };
  28739. // Statics
  28740. /**
  28741. * Returns a new Mesh object parsed from the source provided.
  28742. * The parameter `parsedMesh` is the source.
  28743. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  28744. */
  28745. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  28746. var mesh;
  28747. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  28748. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  28749. }
  28750. else {
  28751. mesh = new Mesh(parsedMesh.name, scene);
  28752. }
  28753. mesh.id = parsedMesh.id;
  28754. if (BABYLON.Tags) {
  28755. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  28756. }
  28757. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  28758. if (parsedMesh.metadata !== undefined) {
  28759. mesh.metadata = parsedMesh.metadata;
  28760. }
  28761. if (parsedMesh.rotationQuaternion) {
  28762. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  28763. }
  28764. else if (parsedMesh.rotation) {
  28765. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  28766. }
  28767. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  28768. if (parsedMesh.localMatrix) {
  28769. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  28770. }
  28771. else if (parsedMesh.pivotMatrix) {
  28772. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  28773. }
  28774. mesh.setEnabled(parsedMesh.isEnabled);
  28775. mesh.isVisible = parsedMesh.isVisible;
  28776. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  28777. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  28778. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  28779. if (parsedMesh.applyFog !== undefined) {
  28780. mesh.applyFog = parsedMesh.applyFog;
  28781. }
  28782. if (parsedMesh.pickable !== undefined) {
  28783. mesh.isPickable = parsedMesh.pickable;
  28784. }
  28785. if (parsedMesh.alphaIndex !== undefined) {
  28786. mesh.alphaIndex = parsedMesh.alphaIndex;
  28787. }
  28788. mesh.receiveShadows = parsedMesh.receiveShadows;
  28789. mesh.billboardMode = parsedMesh.billboardMode;
  28790. if (parsedMesh.visibility !== undefined) {
  28791. mesh.visibility = parsedMesh.visibility;
  28792. }
  28793. mesh.checkCollisions = parsedMesh.checkCollisions;
  28794. if (parsedMesh.isBlocker !== undefined) {
  28795. mesh.isBlocker = parsedMesh.isBlocker;
  28796. }
  28797. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  28798. // freezeWorldMatrix
  28799. if (parsedMesh.freezeWorldMatrix) {
  28800. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  28801. }
  28802. // Parent
  28803. if (parsedMesh.parentId) {
  28804. mesh._waitingParentId = parsedMesh.parentId;
  28805. }
  28806. // Actions
  28807. if (parsedMesh.actions !== undefined) {
  28808. mesh._waitingActions = parsedMesh.actions;
  28809. }
  28810. // Overlay
  28811. if (parsedMesh.overlayAlpha !== undefined) {
  28812. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  28813. }
  28814. if (parsedMesh.overlayColor !== undefined) {
  28815. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  28816. }
  28817. if (parsedMesh.renderOverlay !== undefined) {
  28818. mesh.renderOverlay = parsedMesh.renderOverlay;
  28819. }
  28820. // Geometry
  28821. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  28822. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  28823. if (parsedMesh.delayLoadingFile) {
  28824. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28825. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  28826. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  28827. if (parsedMesh._binaryInfo) {
  28828. mesh._binaryInfo = parsedMesh._binaryInfo;
  28829. }
  28830. mesh._delayInfo = [];
  28831. if (parsedMesh.hasUVs) {
  28832. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28833. }
  28834. if (parsedMesh.hasUVs2) {
  28835. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28836. }
  28837. if (parsedMesh.hasUVs3) {
  28838. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28839. }
  28840. if (parsedMesh.hasUVs4) {
  28841. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28842. }
  28843. if (parsedMesh.hasUVs5) {
  28844. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28845. }
  28846. if (parsedMesh.hasUVs6) {
  28847. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28848. }
  28849. if (parsedMesh.hasColors) {
  28850. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28851. }
  28852. if (parsedMesh.hasMatricesIndices) {
  28853. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28854. }
  28855. if (parsedMesh.hasMatricesWeights) {
  28856. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28857. }
  28858. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  28859. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  28860. mesh._checkDelayState();
  28861. }
  28862. }
  28863. else {
  28864. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  28865. }
  28866. // Material
  28867. if (parsedMesh.materialId) {
  28868. mesh.setMaterialByID(parsedMesh.materialId);
  28869. }
  28870. else {
  28871. mesh.material = null;
  28872. }
  28873. // Morph targets
  28874. if (parsedMesh.morphTargetManagerId > -1) {
  28875. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  28876. }
  28877. // Skeleton
  28878. if (parsedMesh.skeletonId > -1) {
  28879. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  28880. if (parsedMesh.numBoneInfluencers) {
  28881. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  28882. }
  28883. }
  28884. // Animations
  28885. if (parsedMesh.animations) {
  28886. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28887. var parsedAnimation = parsedMesh.animations[animationIndex];
  28888. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28889. }
  28890. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  28891. }
  28892. if (parsedMesh.autoAnimate) {
  28893. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  28894. }
  28895. // Layer Mask
  28896. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  28897. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  28898. }
  28899. else {
  28900. mesh.layerMask = 0x0FFFFFFF;
  28901. }
  28902. // Physics
  28903. if (parsedMesh.physicsImpostor) {
  28904. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  28905. mass: parsedMesh.physicsMass,
  28906. friction: parsedMesh.physicsFriction,
  28907. restitution: parsedMesh.physicsRestitution
  28908. }, scene);
  28909. }
  28910. // Instances
  28911. if (parsedMesh.instances) {
  28912. for (var index = 0; index < parsedMesh.instances.length; index++) {
  28913. var parsedInstance = parsedMesh.instances[index];
  28914. var instance = mesh.createInstance(parsedInstance.name);
  28915. if (parsedInstance.id) {
  28916. instance.id = parsedInstance.id;
  28917. }
  28918. if (BABYLON.Tags) {
  28919. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  28920. }
  28921. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  28922. if (parsedInstance.parentId) {
  28923. instance._waitingParentId = parsedInstance.parentId;
  28924. }
  28925. if (parsedInstance.rotationQuaternion) {
  28926. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  28927. }
  28928. else if (parsedInstance.rotation) {
  28929. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  28930. }
  28931. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  28932. instance.checkCollisions = mesh.checkCollisions;
  28933. if (parsedMesh.animations) {
  28934. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28935. parsedAnimation = parsedMesh.animations[animationIndex];
  28936. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28937. }
  28938. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  28939. }
  28940. }
  28941. }
  28942. return mesh;
  28943. };
  28944. /**
  28945. * Creates a ribbon mesh.
  28946. * Please consider using the same method from the MeshBuilder class instead.
  28947. * 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.
  28948. *
  28949. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28950. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28951. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28952. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28953. * 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.
  28954. * 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.
  28955. * 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
  28956. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28957. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28958. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28959. */
  28960. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  28961. if (closeArray === void 0) { closeArray = false; }
  28962. if (updatable === void 0) { updatable = false; }
  28963. return BABYLON.MeshBuilder.CreateRibbon(name, {
  28964. pathArray: pathArray,
  28965. closeArray: closeArray,
  28966. closePath: closePath,
  28967. offset: offset,
  28968. updatable: updatable,
  28969. sideOrientation: sideOrientation,
  28970. instance: instance
  28971. }, scene);
  28972. };
  28973. /**
  28974. * Creates a plane polygonal mesh. By default, this is a disc.
  28975. * Please consider using the same method from the MeshBuilder class instead.
  28976. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28977. * 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.
  28978. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28979. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28980. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28981. */
  28982. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  28983. if (scene === void 0) { scene = null; }
  28984. var options = {
  28985. radius: radius,
  28986. tessellation: tessellation,
  28987. sideOrientation: sideOrientation,
  28988. updatable: updatable
  28989. };
  28990. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  28991. };
  28992. /**
  28993. * Creates a box mesh.
  28994. * Please consider using the same method from the MeshBuilder class instead.
  28995. * The parameter `size` sets the size (float) of each box side (default 1).
  28996. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28997. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28998. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28999. */
  29000. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29001. if (scene === void 0) { scene = null; }
  29002. var options = {
  29003. size: size,
  29004. sideOrientation: sideOrientation,
  29005. updatable: updatable
  29006. };
  29007. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29008. };
  29009. /**
  29010. * Creates a sphere mesh.
  29011. * Please consider using the same method from the MeshBuilder class instead.
  29012. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29013. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29014. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29015. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29016. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29017. */
  29018. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29019. var options = {
  29020. segments: segments,
  29021. diameterX: diameter,
  29022. diameterY: diameter,
  29023. diameterZ: diameter,
  29024. sideOrientation: sideOrientation,
  29025. updatable: updatable
  29026. };
  29027. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29028. };
  29029. /**
  29030. * Creates a cylinder or a cone mesh.
  29031. * Please consider using the same method from the MeshBuilder class instead.
  29032. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29033. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29034. * 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.
  29035. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29036. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29037. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29038. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29039. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29040. */
  29041. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29042. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29043. if (scene !== undefined) {
  29044. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29045. updatable = scene;
  29046. }
  29047. scene = subdivisions;
  29048. subdivisions = 1;
  29049. }
  29050. var options = {
  29051. height: height,
  29052. diameterTop: diameterTop,
  29053. diameterBottom: diameterBottom,
  29054. tessellation: tessellation,
  29055. subdivisions: subdivisions,
  29056. sideOrientation: sideOrientation,
  29057. updatable: updatable
  29058. };
  29059. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29060. };
  29061. // Torus (Code from SharpDX.org)
  29062. /**
  29063. * Creates a torus mesh.
  29064. * Please consider using the same method from the MeshBuilder class instead.
  29065. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29066. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29067. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29068. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29069. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29070. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29071. */
  29072. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29073. var options = {
  29074. diameter: diameter,
  29075. thickness: thickness,
  29076. tessellation: tessellation,
  29077. sideOrientation: sideOrientation,
  29078. updatable: updatable
  29079. };
  29080. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29081. };
  29082. /**
  29083. * Creates a torus knot mesh.
  29084. * Please consider using the same method from the MeshBuilder class instead.
  29085. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29086. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29087. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29088. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29089. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29090. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29091. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29092. */
  29093. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29094. var options = {
  29095. radius: radius,
  29096. tube: tube,
  29097. radialSegments: radialSegments,
  29098. tubularSegments: tubularSegments,
  29099. p: p,
  29100. q: q,
  29101. sideOrientation: sideOrientation,
  29102. updatable: updatable
  29103. };
  29104. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29105. };
  29106. /**
  29107. * Creates a line mesh.
  29108. * Please consider using the same method from the MeshBuilder class instead.
  29109. * 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.
  29110. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29111. * The parameter `points` is an array successive Vector3.
  29112. * 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
  29113. * When updating an instance, remember that only point positions can change, not the number of points.
  29114. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29115. */
  29116. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29117. if (scene === void 0) { scene = null; }
  29118. if (updatable === void 0) { updatable = false; }
  29119. if (instance === void 0) { instance = null; }
  29120. var options = {
  29121. points: points,
  29122. updatable: updatable,
  29123. instance: instance
  29124. };
  29125. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29126. };
  29127. /**
  29128. * Creates a dashed line mesh.
  29129. * Please consider using the same method from the MeshBuilder class instead.
  29130. * 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.
  29131. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29132. * The parameter `points` is an array successive Vector3.
  29133. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29134. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29135. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29136. * 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
  29137. * When updating an instance, remember that only point positions can change, not the number of points.
  29138. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29139. */
  29140. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29141. if (scene === void 0) { scene = null; }
  29142. var options = {
  29143. points: points,
  29144. dashSize: dashSize,
  29145. gapSize: gapSize,
  29146. dashNb: dashNb,
  29147. updatable: updatable,
  29148. instance: instance
  29149. };
  29150. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29151. };
  29152. /**
  29153. * Creates a polygon mesh.
  29154. * Please consider using the same method from the MeshBuilder class instead.
  29155. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29156. * 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.
  29157. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29158. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29159. * Remember you can only change the shape positions, not their number when updating a polygon.
  29160. */
  29161. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29162. var options = {
  29163. shape: shape,
  29164. holes: holes,
  29165. updatable: updatable,
  29166. sideOrientation: sideOrientation
  29167. };
  29168. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29169. };
  29170. /**
  29171. * Creates an extruded polygon mesh, with depth in the Y direction.
  29172. * Please consider using the same method from the MeshBuilder class instead.
  29173. */
  29174. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29175. var options = {
  29176. shape: shape,
  29177. holes: holes,
  29178. depth: depth,
  29179. updatable: updatable,
  29180. sideOrientation: sideOrientation
  29181. };
  29182. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29183. };
  29184. /**
  29185. * Creates an extruded shape mesh.
  29186. * 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.
  29187. * Please consider using the same method from the MeshBuilder class instead.
  29188. *
  29189. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29190. * 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
  29191. * extruded along the Z axis.
  29192. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29193. * 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.
  29194. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29195. * 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
  29196. * 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
  29197. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29198. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29199. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29200. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29201. */
  29202. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29203. if (scene === void 0) { scene = null; }
  29204. var options = {
  29205. shape: shape,
  29206. path: path,
  29207. scale: scale,
  29208. rotation: rotation,
  29209. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29210. sideOrientation: sideOrientation,
  29211. instance: instance,
  29212. updatable: updatable
  29213. };
  29214. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29215. };
  29216. /**
  29217. * Creates an custom extruded shape mesh.
  29218. * 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.
  29219. * Please consider using the same method from the MeshBuilder class instead.
  29220. *
  29221. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29222. * 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
  29223. * extruded along the Z axis.
  29224. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29225. * 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
  29226. * and the distance of this point from the begining of the path :
  29227. * ```javascript
  29228. * var rotationFunction = function(i, distance) {
  29229. * // do things
  29230. * return rotationValue; }
  29231. * ```
  29232. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29233. * 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
  29234. * and the distance of this point from the begining of the path :
  29235. * ```javascript
  29236. * var scaleFunction = function(i, distance) {
  29237. * // do things
  29238. * return scaleValue;}
  29239. * ```
  29240. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29241. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29242. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29243. * 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
  29244. * 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
  29245. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29246. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29247. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29248. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29249. */
  29250. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29251. var options = {
  29252. shape: shape,
  29253. path: path,
  29254. scaleFunction: scaleFunction,
  29255. rotationFunction: rotationFunction,
  29256. ribbonCloseArray: ribbonCloseArray,
  29257. ribbonClosePath: ribbonClosePath,
  29258. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29259. sideOrientation: sideOrientation,
  29260. instance: instance,
  29261. updatable: updatable
  29262. };
  29263. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29264. };
  29265. /**
  29266. * Creates lathe mesh.
  29267. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29268. * Please consider using the same method from the MeshBuilder class instead.
  29269. * 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
  29270. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29271. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29272. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29273. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29274. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29275. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29276. */
  29277. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29278. var options = {
  29279. shape: shape,
  29280. radius: radius,
  29281. tessellation: tessellation,
  29282. sideOrientation: sideOrientation,
  29283. updatable: updatable
  29284. };
  29285. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29286. };
  29287. /**
  29288. * Creates a plane mesh.
  29289. * Please consider using the same method from the MeshBuilder class instead.
  29290. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29291. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29292. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29293. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29294. */
  29295. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29296. var options = {
  29297. size: size,
  29298. width: size,
  29299. height: size,
  29300. sideOrientation: sideOrientation,
  29301. updatable: updatable
  29302. };
  29303. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29304. };
  29305. /**
  29306. * Creates a ground mesh.
  29307. * Please consider using the same method from the MeshBuilder class instead.
  29308. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29309. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29310. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29311. */
  29312. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29313. var options = {
  29314. width: width,
  29315. height: height,
  29316. subdivisions: subdivisions,
  29317. updatable: updatable
  29318. };
  29319. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29320. };
  29321. /**
  29322. * Creates a tiled ground mesh.
  29323. * Please consider using the same method from the MeshBuilder class instead.
  29324. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29325. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29326. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29327. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29328. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29329. * numbers of subdivisions on the ground width and height of each tile.
  29330. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29331. */
  29332. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29333. var options = {
  29334. xmin: xmin,
  29335. zmin: zmin,
  29336. xmax: xmax,
  29337. zmax: zmax,
  29338. subdivisions: subdivisions,
  29339. precision: precision,
  29340. updatable: updatable
  29341. };
  29342. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29343. };
  29344. /**
  29345. * Creates a ground mesh from a height map.
  29346. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29347. * Please consider using the same method from the MeshBuilder class instead.
  29348. * The parameter `url` sets the URL of the height map image resource.
  29349. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29350. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29351. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29352. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29353. * 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).
  29354. * This function is passed the newly built mesh :
  29355. * ```javascript
  29356. * function(mesh) { // do things
  29357. * return; }
  29358. * ```
  29359. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29360. */
  29361. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29362. var options = {
  29363. width: width,
  29364. height: height,
  29365. subdivisions: subdivisions,
  29366. minHeight: minHeight,
  29367. maxHeight: maxHeight,
  29368. updatable: updatable,
  29369. onReady: onReady
  29370. };
  29371. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29372. };
  29373. /**
  29374. * Creates a tube mesh.
  29375. * 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.
  29376. * Please consider using the same method from the MeshBuilder class instead.
  29377. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29378. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29379. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29380. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29381. * 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.
  29382. * It must return a radius value (positive float) :
  29383. * ```javascript
  29384. * var radiusFunction = function(i, distance) {
  29385. * // do things
  29386. * return radius; }
  29387. * ```
  29388. * 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
  29389. * 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
  29390. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29391. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29392. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29393. */
  29394. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29395. var options = {
  29396. path: path,
  29397. radius: radius,
  29398. tessellation: tessellation,
  29399. radiusFunction: radiusFunction,
  29400. arc: 1,
  29401. cap: cap,
  29402. updatable: updatable,
  29403. sideOrientation: sideOrientation,
  29404. instance: instance
  29405. };
  29406. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29407. };
  29408. /**
  29409. * Creates a polyhedron mesh.
  29410. * Please consider using the same method from the MeshBuilder class instead.
  29411. * 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
  29412. * to choose the wanted type.
  29413. * The parameter `size` (positive float, default 1) sets the polygon size.
  29414. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29415. * 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`.
  29416. * 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
  29417. * 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)`).
  29418. * 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
  29419. * 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.
  29420. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29421. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29422. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29423. */
  29424. Mesh.CreatePolyhedron = function (name, options, scene) {
  29425. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29426. };
  29427. /**
  29428. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29429. * Please consider using the same method from the MeshBuilder class instead.
  29430. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29431. * 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`).
  29432. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29433. * 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.
  29434. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29435. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29436. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29437. */
  29438. Mesh.CreateIcoSphere = function (name, options, scene) {
  29439. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29440. };
  29441. /**
  29442. * Creates a decal mesh.
  29443. * Please consider using the same method from the MeshBuilder class instead.
  29444. * 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.
  29445. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29446. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29447. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29448. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29449. */
  29450. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29451. var options = {
  29452. position: position,
  29453. normal: normal,
  29454. size: size,
  29455. angle: angle
  29456. };
  29457. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29458. };
  29459. // Skeletons
  29460. /**
  29461. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29462. */
  29463. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29464. if (!this._sourcePositions) {
  29465. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29466. if (!source) {
  29467. return this._sourcePositions;
  29468. }
  29469. this._sourcePositions = new Float32Array(source);
  29470. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29471. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29472. }
  29473. }
  29474. return this._sourcePositions;
  29475. };
  29476. /**
  29477. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29478. */
  29479. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29480. if (!this._sourceNormals) {
  29481. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29482. if (!source) {
  29483. return this._sourceNormals;
  29484. }
  29485. this._sourceNormals = new Float32Array(source);
  29486. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29487. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29488. }
  29489. }
  29490. return this._sourceNormals;
  29491. };
  29492. /**
  29493. * Updates the vertex buffer by applying transformation from the bones.
  29494. * Returns the Mesh.
  29495. *
  29496. * @param {skeleton} skeleton to apply
  29497. */
  29498. Mesh.prototype.applySkeleton = function (skeleton) {
  29499. if (!this.geometry) {
  29500. return this;
  29501. }
  29502. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29503. return this;
  29504. }
  29505. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29506. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29507. return this;
  29508. }
  29509. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29510. return this;
  29511. }
  29512. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29513. return this;
  29514. }
  29515. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29516. return this;
  29517. }
  29518. if (!this._sourcePositions) {
  29519. var submeshes = this.subMeshes.slice();
  29520. this.setPositionsForCPUSkinning();
  29521. this.subMeshes = submeshes;
  29522. }
  29523. if (!this._sourceNormals) {
  29524. this.setNormalsForCPUSkinning();
  29525. }
  29526. // positionsData checks for not being Float32Array will only pass at most once
  29527. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29528. if (!positionsData) {
  29529. return this;
  29530. }
  29531. if (!(positionsData instanceof Float32Array)) {
  29532. positionsData = new Float32Array(positionsData);
  29533. }
  29534. // normalsData checks for not being Float32Array will only pass at most once
  29535. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29536. if (!normalsData) {
  29537. return this;
  29538. }
  29539. if (!(normalsData instanceof Float32Array)) {
  29540. normalsData = new Float32Array(normalsData);
  29541. }
  29542. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29543. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29544. if (!matricesWeightsData || !matricesIndicesData) {
  29545. return this;
  29546. }
  29547. var needExtras = this.numBoneInfluencers > 4;
  29548. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29549. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29550. var skeletonMatrices = skeleton.getTransformMatrices(this);
  29551. var tempVector3 = BABYLON.Vector3.Zero();
  29552. var finalMatrix = new BABYLON.Matrix();
  29553. var tempMatrix = new BABYLON.Matrix();
  29554. var matWeightIdx = 0;
  29555. var inf;
  29556. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  29557. var weight;
  29558. for (inf = 0; inf < 4; inf++) {
  29559. weight = matricesWeightsData[matWeightIdx + inf];
  29560. if (weight > 0) {
  29561. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29562. finalMatrix.addToSelf(tempMatrix);
  29563. }
  29564. else
  29565. break;
  29566. }
  29567. if (needExtras) {
  29568. for (inf = 0; inf < 4; inf++) {
  29569. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29570. if (weight > 0) {
  29571. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29572. finalMatrix.addToSelf(tempMatrix);
  29573. }
  29574. else
  29575. break;
  29576. }
  29577. }
  29578. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  29579. tempVector3.toArray(positionsData, index);
  29580. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  29581. tempVector3.toArray(normalsData, index);
  29582. finalMatrix.reset();
  29583. }
  29584. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  29585. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  29586. return this;
  29587. };
  29588. // Tools
  29589. /**
  29590. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  29591. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  29592. */
  29593. Mesh.MinMax = function (meshes) {
  29594. var minVector = null;
  29595. var maxVector = null;
  29596. meshes.forEach(function (mesh, index, array) {
  29597. var boundingInfo = mesh.getBoundingInfo();
  29598. var boundingBox = boundingInfo.boundingBox;
  29599. if (!minVector || !maxVector) {
  29600. minVector = boundingBox.minimumWorld;
  29601. maxVector = boundingBox.maximumWorld;
  29602. }
  29603. else {
  29604. minVector.minimizeInPlace(boundingBox.minimumWorld);
  29605. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  29606. }
  29607. });
  29608. if (!minVector || !maxVector) {
  29609. return {
  29610. min: BABYLON.Vector3.Zero(),
  29611. max: BABYLON.Vector3.Zero()
  29612. };
  29613. }
  29614. return {
  29615. min: minVector,
  29616. max: maxVector
  29617. };
  29618. };
  29619. /**
  29620. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  29621. */
  29622. Mesh.Center = function (meshesOrMinMaxVector) {
  29623. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  29624. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  29625. };
  29626. /**
  29627. * Merge the array of meshes into a single mesh for performance reasons.
  29628. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  29629. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  29630. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  29631. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  29632. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  29633. */
  29634. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  29635. if (disposeSource === void 0) { disposeSource = true; }
  29636. var index;
  29637. if (!allow32BitsIndices) {
  29638. var totalVertices = 0;
  29639. // Counting vertices
  29640. for (index = 0; index < meshes.length; index++) {
  29641. if (meshes[index]) {
  29642. totalVertices += meshes[index].getTotalVertices();
  29643. if (totalVertices > 65536) {
  29644. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  29645. return null;
  29646. }
  29647. }
  29648. }
  29649. }
  29650. // Merge
  29651. var vertexData = null;
  29652. var otherVertexData;
  29653. var indiceArray = new Array();
  29654. var source = null;
  29655. for (index = 0; index < meshes.length; index++) {
  29656. if (meshes[index]) {
  29657. meshes[index].computeWorldMatrix(true);
  29658. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  29659. otherVertexData.transform(meshes[index].getWorldMatrix());
  29660. if (vertexData) {
  29661. vertexData.merge(otherVertexData);
  29662. }
  29663. else {
  29664. vertexData = otherVertexData;
  29665. source = meshes[index];
  29666. }
  29667. if (subdivideWithSubMeshes) {
  29668. indiceArray.push(meshes[index].getTotalIndices());
  29669. }
  29670. }
  29671. }
  29672. source = source;
  29673. if (!meshSubclass) {
  29674. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  29675. }
  29676. vertexData.applyToMesh(meshSubclass);
  29677. // Setting properties
  29678. meshSubclass.material = source.material;
  29679. meshSubclass.checkCollisions = source.checkCollisions;
  29680. // Cleaning
  29681. if (disposeSource) {
  29682. for (index = 0; index < meshes.length; index++) {
  29683. if (meshes[index]) {
  29684. meshes[index].dispose();
  29685. }
  29686. }
  29687. }
  29688. // Subdivide
  29689. if (subdivideWithSubMeshes) {
  29690. //-- Suppresions du submesh global
  29691. meshSubclass.releaseSubMeshes();
  29692. index = 0;
  29693. var offset = 0;
  29694. //-- aplique la subdivision en fonction du tableau d'indices
  29695. while (index < indiceArray.length) {
  29696. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  29697. offset += indiceArray[index];
  29698. index++;
  29699. }
  29700. }
  29701. return meshSubclass;
  29702. };
  29703. // Consts
  29704. Mesh._FRONTSIDE = 0;
  29705. Mesh._BACKSIDE = 1;
  29706. Mesh._DOUBLESIDE = 2;
  29707. Mesh._DEFAULTSIDE = 0;
  29708. Mesh._NO_CAP = 0;
  29709. Mesh._CAP_START = 1;
  29710. Mesh._CAP_END = 2;
  29711. Mesh._CAP_ALL = 3;
  29712. return Mesh;
  29713. }(BABYLON.AbstractMesh));
  29714. BABYLON.Mesh = Mesh;
  29715. })(BABYLON || (BABYLON = {}));
  29716. //# sourceMappingURL=babylon.mesh.js.map
  29717. var BABYLON;
  29718. (function (BABYLON) {
  29719. var BaseSubMesh = /** @class */ (function () {
  29720. function BaseSubMesh() {
  29721. }
  29722. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  29723. get: function () {
  29724. return this._materialEffect;
  29725. },
  29726. enumerable: true,
  29727. configurable: true
  29728. });
  29729. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  29730. if (defines === void 0) { defines = null; }
  29731. if (this._materialEffect === effect) {
  29732. if (!effect) {
  29733. this._materialDefines = null;
  29734. }
  29735. return;
  29736. }
  29737. this._materialDefines = defines;
  29738. this._materialEffect = effect;
  29739. };
  29740. return BaseSubMesh;
  29741. }());
  29742. BABYLON.BaseSubMesh = BaseSubMesh;
  29743. var SubMesh = /** @class */ (function (_super) {
  29744. __extends(SubMesh, _super);
  29745. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29746. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29747. var _this = _super.call(this) || this;
  29748. _this.materialIndex = materialIndex;
  29749. _this.verticesStart = verticesStart;
  29750. _this.verticesCount = verticesCount;
  29751. _this.indexStart = indexStart;
  29752. _this.indexCount = indexCount;
  29753. _this._renderId = 0;
  29754. _this._mesh = mesh;
  29755. _this._renderingMesh = renderingMesh || mesh;
  29756. mesh.subMeshes.push(_this);
  29757. _this._trianglePlanes = [];
  29758. _this._id = mesh.subMeshes.length - 1;
  29759. if (createBoundingBox) {
  29760. _this.refreshBoundingInfo();
  29761. mesh.computeWorldMatrix(true);
  29762. }
  29763. return _this;
  29764. }
  29765. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29766. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29767. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  29768. };
  29769. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  29770. get: function () {
  29771. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  29772. },
  29773. enumerable: true,
  29774. configurable: true
  29775. });
  29776. /**
  29777. * Returns the submesh BoudingInfo object.
  29778. */
  29779. SubMesh.prototype.getBoundingInfo = function () {
  29780. if (this.IsGlobal) {
  29781. return this._mesh.getBoundingInfo();
  29782. }
  29783. return this._boundingInfo;
  29784. };
  29785. /**
  29786. * Sets the submesh BoundingInfo.
  29787. * Return the SubMesh.
  29788. */
  29789. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  29790. this._boundingInfo = boundingInfo;
  29791. return this;
  29792. };
  29793. /**
  29794. * Returns the mesh of the current submesh.
  29795. */
  29796. SubMesh.prototype.getMesh = function () {
  29797. return this._mesh;
  29798. };
  29799. /**
  29800. * Returns the rendering mesh of the submesh.
  29801. */
  29802. SubMesh.prototype.getRenderingMesh = function () {
  29803. return this._renderingMesh;
  29804. };
  29805. /**
  29806. * Returns the submesh material.
  29807. */
  29808. SubMesh.prototype.getMaterial = function () {
  29809. var rootMaterial = this._renderingMesh.material;
  29810. if (rootMaterial === null || rootMaterial === undefined) {
  29811. return this._mesh.getScene().defaultMaterial;
  29812. }
  29813. else if (rootMaterial.getSubMaterial) {
  29814. var multiMaterial = rootMaterial;
  29815. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  29816. if (this._currentMaterial !== effectiveMaterial) {
  29817. this._currentMaterial = effectiveMaterial;
  29818. this._materialDefines = null;
  29819. }
  29820. return effectiveMaterial;
  29821. }
  29822. return rootMaterial;
  29823. };
  29824. // Methods
  29825. /**
  29826. * Sets a new updated BoundingInfo object to the submesh.
  29827. * Returns the SubMesh.
  29828. */
  29829. SubMesh.prototype.refreshBoundingInfo = function () {
  29830. this._lastColliderWorldVertices = null;
  29831. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  29832. return this;
  29833. }
  29834. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29835. if (!data) {
  29836. this._boundingInfo = this._mesh.getBoundingInfo();
  29837. return this;
  29838. }
  29839. var indices = this._renderingMesh.getIndices();
  29840. var extend;
  29841. //is this the only submesh?
  29842. if (this.indexStart === 0 && this.indexCount === indices.length) {
  29843. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29844. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  29845. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  29846. }
  29847. else {
  29848. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  29849. }
  29850. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29851. return this;
  29852. };
  29853. SubMesh.prototype._checkCollision = function (collider) {
  29854. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29855. return boundingInfo._checkCollision(collider);
  29856. };
  29857. /**
  29858. * Updates the submesh BoundingInfo.
  29859. * Returns the Submesh.
  29860. */
  29861. SubMesh.prototype.updateBoundingInfo = function (world) {
  29862. var boundingInfo = this.getBoundingInfo();
  29863. if (!boundingInfo) {
  29864. this.refreshBoundingInfo();
  29865. boundingInfo = this.getBoundingInfo();
  29866. }
  29867. boundingInfo.update(world);
  29868. return this;
  29869. };
  29870. /**
  29871. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  29872. * Boolean returned.
  29873. */
  29874. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  29875. var boundingInfo = this.getBoundingInfo();
  29876. if (!boundingInfo) {
  29877. return false;
  29878. }
  29879. return boundingInfo.isInFrustum(frustumPlanes);
  29880. };
  29881. /**
  29882. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  29883. * Boolean returned.
  29884. */
  29885. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  29886. var boundingInfo = this.getBoundingInfo();
  29887. if (!boundingInfo) {
  29888. return false;
  29889. }
  29890. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  29891. };
  29892. /**
  29893. * Renders the submesh.
  29894. * Returns it.
  29895. */
  29896. SubMesh.prototype.render = function (enableAlphaMode) {
  29897. this._renderingMesh.render(this, enableAlphaMode);
  29898. return this;
  29899. };
  29900. /**
  29901. * Returns a new Index Buffer.
  29902. * Type returned : WebGLBuffer.
  29903. */
  29904. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  29905. if (!this._linesIndexBuffer) {
  29906. var linesIndices = [];
  29907. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29908. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  29909. }
  29910. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  29911. this.linesIndexCount = linesIndices.length;
  29912. }
  29913. return this._linesIndexBuffer;
  29914. };
  29915. /**
  29916. * True is the passed Ray intersects the submesh bounding box.
  29917. * Boolean returned.
  29918. */
  29919. SubMesh.prototype.canIntersects = function (ray) {
  29920. var boundingInfo = this.getBoundingInfo();
  29921. if (!boundingInfo) {
  29922. return false;
  29923. }
  29924. return ray.intersectsBox(boundingInfo.boundingBox);
  29925. };
  29926. /**
  29927. * Returns an object IntersectionInfo.
  29928. */
  29929. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  29930. var intersectInfo = null;
  29931. // LineMesh first as it's also a Mesh...
  29932. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  29933. var lineMesh = this._mesh;
  29934. // Line test
  29935. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  29936. var p0 = positions[indices[index]];
  29937. var p1 = positions[indices[index + 1]];
  29938. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  29939. if (length < 0) {
  29940. continue;
  29941. }
  29942. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  29943. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  29944. if (fastCheck) {
  29945. break;
  29946. }
  29947. }
  29948. }
  29949. }
  29950. else {
  29951. // Triangles test
  29952. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29953. var p0 = positions[indices[index]];
  29954. var p1 = positions[indices[index + 1]];
  29955. var p2 = positions[indices[index + 2]];
  29956. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  29957. if (currentIntersectInfo) {
  29958. if (currentIntersectInfo.distance < 0) {
  29959. continue;
  29960. }
  29961. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  29962. intersectInfo = currentIntersectInfo;
  29963. intersectInfo.faceId = index / 3;
  29964. if (fastCheck) {
  29965. break;
  29966. }
  29967. }
  29968. }
  29969. }
  29970. }
  29971. return intersectInfo;
  29972. };
  29973. SubMesh.prototype._rebuild = function () {
  29974. if (this._linesIndexBuffer) {
  29975. this._linesIndexBuffer = null;
  29976. }
  29977. };
  29978. // Clone
  29979. /**
  29980. * Creates a new Submesh from the passed Mesh.
  29981. */
  29982. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  29983. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  29984. if (!this.IsGlobal) {
  29985. var boundingInfo = this.getBoundingInfo();
  29986. if (!boundingInfo) {
  29987. return result;
  29988. }
  29989. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  29990. }
  29991. return result;
  29992. };
  29993. // Dispose
  29994. /**
  29995. * Disposes the Submesh.
  29996. * Returns nothing.
  29997. */
  29998. SubMesh.prototype.dispose = function () {
  29999. if (this._linesIndexBuffer) {
  30000. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30001. this._linesIndexBuffer = null;
  30002. }
  30003. // Remove from mesh
  30004. var index = this._mesh.subMeshes.indexOf(this);
  30005. this._mesh.subMeshes.splice(index, 1);
  30006. };
  30007. // Statics
  30008. /**
  30009. * Creates a new Submesh from the passed parameters :
  30010. * - materialIndex (integer) : the index of the main mesh material.
  30011. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30012. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30013. * - mesh (Mesh) : the main mesh to create the submesh from.
  30014. * - renderingMesh (optional Mesh) : rendering mesh.
  30015. */
  30016. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30017. var minVertexIndex = Number.MAX_VALUE;
  30018. var maxVertexIndex = -Number.MAX_VALUE;
  30019. renderingMesh = (renderingMesh || mesh);
  30020. var indices = renderingMesh.getIndices();
  30021. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30022. var vertexIndex = indices[index];
  30023. if (vertexIndex < minVertexIndex)
  30024. minVertexIndex = vertexIndex;
  30025. if (vertexIndex > maxVertexIndex)
  30026. maxVertexIndex = vertexIndex;
  30027. }
  30028. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30029. };
  30030. return SubMesh;
  30031. }(BaseSubMesh));
  30032. BABYLON.SubMesh = SubMesh;
  30033. })(BABYLON || (BABYLON = {}));
  30034. //# sourceMappingURL=babylon.subMesh.js.map
  30035. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30036. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30037. s = arguments[i];
  30038. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30039. t[p] = s[p];
  30040. }
  30041. return t;
  30042. };
  30043. var BABYLON;
  30044. (function (BABYLON) {
  30045. /**
  30046. * Manages the defines for the Material.
  30047. */
  30048. var MaterialDefines = /** @class */ (function () {
  30049. function MaterialDefines() {
  30050. this._isDirty = true;
  30051. this._areLightsDirty = true;
  30052. this._areAttributesDirty = true;
  30053. this._areTexturesDirty = true;
  30054. this._areFresnelDirty = true;
  30055. this._areMiscDirty = true;
  30056. this._areImageProcessingDirty = true;
  30057. this._normals = false;
  30058. this._uvs = false;
  30059. this._needNormals = false;
  30060. this._needUVs = false;
  30061. }
  30062. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30063. /**
  30064. * Specifies if the material needs to be re-calculated.
  30065. */
  30066. get: function () {
  30067. return this._isDirty;
  30068. },
  30069. enumerable: true,
  30070. configurable: true
  30071. });
  30072. /**
  30073. * Marks the material to indicate that it has been re-calculated.
  30074. */
  30075. MaterialDefines.prototype.markAsProcessed = function () {
  30076. this._isDirty = false;
  30077. this._areAttributesDirty = false;
  30078. this._areTexturesDirty = false;
  30079. this._areFresnelDirty = false;
  30080. this._areLightsDirty = false;
  30081. this._areMiscDirty = false;
  30082. this._areImageProcessingDirty = false;
  30083. };
  30084. /**
  30085. * Marks the material to indicate that it needs to be re-calculated.
  30086. */
  30087. MaterialDefines.prototype.markAsUnprocessed = function () {
  30088. this._isDirty = true;
  30089. };
  30090. /**
  30091. * Marks the material to indicate all of its defines need to be re-calculated.
  30092. */
  30093. MaterialDefines.prototype.markAllAsDirty = function () {
  30094. this._areTexturesDirty = true;
  30095. this._areAttributesDirty = true;
  30096. this._areLightsDirty = true;
  30097. this._areFresnelDirty = true;
  30098. this._areMiscDirty = true;
  30099. this._areImageProcessingDirty = true;
  30100. this._isDirty = true;
  30101. };
  30102. /**
  30103. * Marks the material to indicate that image processing needs to be re-calculated.
  30104. */
  30105. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30106. this._areImageProcessingDirty = true;
  30107. this._isDirty = true;
  30108. };
  30109. /**
  30110. * Marks the material to indicate the lights need to be re-calculated.
  30111. */
  30112. MaterialDefines.prototype.markAsLightDirty = function () {
  30113. this._areLightsDirty = true;
  30114. this._isDirty = true;
  30115. };
  30116. /**
  30117. * Marks the attribute state as changed.
  30118. */
  30119. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30120. this._areAttributesDirty = true;
  30121. this._isDirty = true;
  30122. };
  30123. /**
  30124. * Marks the texture state as changed.
  30125. */
  30126. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30127. this._areTexturesDirty = true;
  30128. this._isDirty = true;
  30129. };
  30130. /**
  30131. * Marks the fresnel state as changed.
  30132. */
  30133. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30134. this._areFresnelDirty = true;
  30135. this._isDirty = true;
  30136. };
  30137. /**
  30138. * Marks the misc state as changed.
  30139. */
  30140. MaterialDefines.prototype.markAsMiscDirty = function () {
  30141. this._areMiscDirty = true;
  30142. this._isDirty = true;
  30143. };
  30144. /**
  30145. * Rebuilds the material defines.
  30146. */
  30147. MaterialDefines.prototype.rebuild = function () {
  30148. if (this._keys) {
  30149. delete this._keys;
  30150. }
  30151. this._keys = [];
  30152. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30153. var key = _a[_i];
  30154. if (key[0] === "_") {
  30155. continue;
  30156. }
  30157. this._keys.push(key);
  30158. }
  30159. };
  30160. /**
  30161. * Specifies if two material defines are equal.
  30162. * @param other - A material define instance to compare to.
  30163. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30164. */
  30165. MaterialDefines.prototype.isEqual = function (other) {
  30166. if (this._keys.length !== other._keys.length) {
  30167. return false;
  30168. }
  30169. for (var index = 0; index < this._keys.length; index++) {
  30170. var prop = this._keys[index];
  30171. if (this[prop] !== other[prop]) {
  30172. return false;
  30173. }
  30174. }
  30175. return true;
  30176. };
  30177. /**
  30178. * Clones this instance's defines to another instance.
  30179. * @param other - material defines to clone values to.
  30180. */
  30181. MaterialDefines.prototype.cloneTo = function (other) {
  30182. if (this._keys.length !== other._keys.length) {
  30183. other._keys = this._keys.slice(0);
  30184. }
  30185. for (var index = 0; index < this._keys.length; index++) {
  30186. var prop = this._keys[index];
  30187. other[prop] = this[prop];
  30188. }
  30189. };
  30190. /**
  30191. * Resets the material define values.
  30192. */
  30193. MaterialDefines.prototype.reset = function () {
  30194. for (var index = 0; index < this._keys.length; index++) {
  30195. var prop = this._keys[index];
  30196. if (typeof (this[prop]) === "number") {
  30197. this[prop] = 0;
  30198. }
  30199. else {
  30200. this[prop] = false;
  30201. }
  30202. }
  30203. };
  30204. /**
  30205. * Converts the material define values to a string.
  30206. * @returns - String of material define information.
  30207. */
  30208. MaterialDefines.prototype.toString = function () {
  30209. var result = "";
  30210. for (var index = 0; index < this._keys.length; index++) {
  30211. var prop = this._keys[index];
  30212. var value = this[prop];
  30213. if (typeof (value) === "number") {
  30214. result += "#define " + prop + " " + this[prop] + "\n";
  30215. }
  30216. else if (value) {
  30217. result += "#define " + prop + "\n";
  30218. }
  30219. }
  30220. return result;
  30221. };
  30222. return MaterialDefines;
  30223. }());
  30224. BABYLON.MaterialDefines = MaterialDefines;
  30225. /**
  30226. * This offers the main features of a material in BJS.
  30227. */
  30228. var Material = /** @class */ (function () {
  30229. /**
  30230. * Creates a material instance.
  30231. * @param name - The name of the material.
  30232. * @param scene - The BJS scene to reference.
  30233. * @param doNotAdd - Specifies if the material should be added to the scene.
  30234. */
  30235. function Material(name, scene, doNotAdd) {
  30236. /**
  30237. * Specifies if the ready state should be checked on each call.
  30238. */
  30239. this.checkReadyOnEveryCall = false;
  30240. /**
  30241. * Specifies if the ready state should be checked once.
  30242. */
  30243. this.checkReadyOnlyOnce = false;
  30244. /**
  30245. * The state of the material.
  30246. */
  30247. this.state = "";
  30248. /**
  30249. * The alpha value of the material.
  30250. */
  30251. this._alpha = 1.0;
  30252. /**
  30253. * Specifies if back face culling is enabled.
  30254. */
  30255. this._backFaceCulling = true;
  30256. /**
  30257. * Specifies if the material should be serialized.
  30258. */
  30259. this.doNotSerialize = false;
  30260. /**
  30261. * Specifies if the effect should be stored on sub meshes.
  30262. */
  30263. this.storeEffectOnSubMeshes = false;
  30264. /**
  30265. * An event triggered when the material is disposed.
  30266. * @type {BABYLON.Observable}
  30267. */
  30268. this.onDisposeObservable = new BABYLON.Observable();
  30269. /**
  30270. * An event triggered when the material is bound.
  30271. * @type {BABYLON.Observable}
  30272. */
  30273. this.onBindObservable = new BABYLON.Observable();
  30274. /**
  30275. * An event triggered when the material is unbound.
  30276. * @type {BABYLON.Observable}
  30277. */
  30278. this.onUnBindObservable = new BABYLON.Observable();
  30279. /**
  30280. * Stores the value of the alpha mode.
  30281. */
  30282. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30283. /**
  30284. * Stores the state of the need depth pre-pass value.
  30285. */
  30286. this._needDepthPrePass = false;
  30287. /**
  30288. * Specifies if depth writing should be disabled.
  30289. */
  30290. this.disableDepthWrite = false;
  30291. /**
  30292. * Specifies if depth writing should be forced.
  30293. */
  30294. this.forceDepthWrite = false;
  30295. /**
  30296. * Specifies if there should be a separate pass for culling.
  30297. */
  30298. this.separateCullingPass = false;
  30299. /**
  30300. * Stores the state specifing if fog should be enabled.
  30301. */
  30302. this._fogEnabled = true;
  30303. /**
  30304. * Stores the size of points.
  30305. */
  30306. this.pointSize = 1.0;
  30307. /**
  30308. * Stores the z offset value.
  30309. */
  30310. this.zOffset = 0;
  30311. /**
  30312. * Specifies if the material was previously ready.
  30313. */
  30314. this._wasPreviouslyReady = false;
  30315. /**
  30316. * Stores the fill mode state.
  30317. */
  30318. this._fillMode = Material.TriangleFillMode;
  30319. this.name = name;
  30320. this.id = name || BABYLON.Tools.RandomId();
  30321. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30322. if (this._scene.useRightHandedSystem) {
  30323. this.sideOrientation = Material.ClockWiseSideOrientation;
  30324. }
  30325. else {
  30326. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30327. }
  30328. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30329. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30330. if (!doNotAdd) {
  30331. this._scene.materials.push(this);
  30332. }
  30333. }
  30334. Object.defineProperty(Material, "TriangleFillMode", {
  30335. /**
  30336. * Returns the triangle fill mode.
  30337. */
  30338. get: function () {
  30339. return Material._TriangleFillMode;
  30340. },
  30341. enumerable: true,
  30342. configurable: true
  30343. });
  30344. Object.defineProperty(Material, "WireFrameFillMode", {
  30345. /**
  30346. * Returns the wireframe mode.
  30347. */
  30348. get: function () {
  30349. return Material._WireFrameFillMode;
  30350. },
  30351. enumerable: true,
  30352. configurable: true
  30353. });
  30354. Object.defineProperty(Material, "PointFillMode", {
  30355. /**
  30356. * Returns the point fill mode.
  30357. */
  30358. get: function () {
  30359. return Material._PointFillMode;
  30360. },
  30361. enumerable: true,
  30362. configurable: true
  30363. });
  30364. Object.defineProperty(Material, "PointListDrawMode", {
  30365. /**
  30366. * Returns the point list draw mode.
  30367. */
  30368. get: function () {
  30369. return Material._PointListDrawMode;
  30370. },
  30371. enumerable: true,
  30372. configurable: true
  30373. });
  30374. Object.defineProperty(Material, "LineListDrawMode", {
  30375. /**
  30376. * Returns the line list draw mode.
  30377. */
  30378. get: function () {
  30379. return Material._LineListDrawMode;
  30380. },
  30381. enumerable: true,
  30382. configurable: true
  30383. });
  30384. Object.defineProperty(Material, "LineLoopDrawMode", {
  30385. /**
  30386. * Returns the line loop draw mode.
  30387. */
  30388. get: function () {
  30389. return Material._LineLoopDrawMode;
  30390. },
  30391. enumerable: true,
  30392. configurable: true
  30393. });
  30394. Object.defineProperty(Material, "LineStripDrawMode", {
  30395. /**
  30396. * Returns the line strip draw mode.
  30397. */
  30398. get: function () {
  30399. return Material._LineStripDrawMode;
  30400. },
  30401. enumerable: true,
  30402. configurable: true
  30403. });
  30404. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30405. /**
  30406. * Returns the triangle strip draw mode.
  30407. */
  30408. get: function () {
  30409. return Material._TriangleStripDrawMode;
  30410. },
  30411. enumerable: true,
  30412. configurable: true
  30413. });
  30414. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30415. /**
  30416. * Returns the triangle fan draw mode.
  30417. */
  30418. get: function () {
  30419. return Material._TriangleFanDrawMode;
  30420. },
  30421. enumerable: true,
  30422. configurable: true
  30423. });
  30424. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30425. /**
  30426. * Returns the clock-wise side orientation.
  30427. */
  30428. get: function () {
  30429. return Material._ClockWiseSideOrientation;
  30430. },
  30431. enumerable: true,
  30432. configurable: true
  30433. });
  30434. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30435. /**
  30436. * Returns the counter clock-wise side orientation.
  30437. */
  30438. get: function () {
  30439. return Material._CounterClockWiseSideOrientation;
  30440. },
  30441. enumerable: true,
  30442. configurable: true
  30443. });
  30444. Object.defineProperty(Material, "TextureDirtyFlag", {
  30445. /**
  30446. * Returns the dirty texture flag value.
  30447. */
  30448. get: function () {
  30449. return Material._TextureDirtyFlag;
  30450. },
  30451. enumerable: true,
  30452. configurable: true
  30453. });
  30454. Object.defineProperty(Material, "LightDirtyFlag", {
  30455. /**
  30456. * Returns the dirty light flag value.
  30457. */
  30458. get: function () {
  30459. return Material._LightDirtyFlag;
  30460. },
  30461. enumerable: true,
  30462. configurable: true
  30463. });
  30464. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30465. /**
  30466. * Returns the dirty fresnel flag value.
  30467. */
  30468. get: function () {
  30469. return Material._FresnelDirtyFlag;
  30470. },
  30471. enumerable: true,
  30472. configurable: true
  30473. });
  30474. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30475. /**
  30476. * Returns the dirty attributes flag value.
  30477. */
  30478. get: function () {
  30479. return Material._AttributesDirtyFlag;
  30480. },
  30481. enumerable: true,
  30482. configurable: true
  30483. });
  30484. Object.defineProperty(Material, "MiscDirtyFlag", {
  30485. /**
  30486. * Returns the dirty misc flag value.
  30487. */
  30488. get: function () {
  30489. return Material._MiscDirtyFlag;
  30490. },
  30491. enumerable: true,
  30492. configurable: true
  30493. });
  30494. Object.defineProperty(Material.prototype, "alpha", {
  30495. /**
  30496. * Gets the alpha value of the material.
  30497. */
  30498. get: function () {
  30499. return this._alpha;
  30500. },
  30501. /**
  30502. * Sets the alpha value of the material.
  30503. */
  30504. set: function (value) {
  30505. if (this._alpha === value) {
  30506. return;
  30507. }
  30508. this._alpha = value;
  30509. this.markAsDirty(Material.MiscDirtyFlag);
  30510. },
  30511. enumerable: true,
  30512. configurable: true
  30513. });
  30514. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30515. /**
  30516. * Gets the back-face culling state.
  30517. */
  30518. get: function () {
  30519. return this._backFaceCulling;
  30520. },
  30521. /**
  30522. * Sets the back-face culling state.
  30523. */
  30524. set: function (value) {
  30525. if (this._backFaceCulling === value) {
  30526. return;
  30527. }
  30528. this._backFaceCulling = value;
  30529. this.markAsDirty(Material.TextureDirtyFlag);
  30530. },
  30531. enumerable: true,
  30532. configurable: true
  30533. });
  30534. Object.defineProperty(Material.prototype, "onDispose", {
  30535. /**
  30536. * Called during a dispose event.
  30537. */
  30538. set: function (callback) {
  30539. if (this._onDisposeObserver) {
  30540. this.onDisposeObservable.remove(this._onDisposeObserver);
  30541. }
  30542. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30543. },
  30544. enumerable: true,
  30545. configurable: true
  30546. });
  30547. Object.defineProperty(Material.prototype, "onBind", {
  30548. /**
  30549. * Called during a bind event.
  30550. */
  30551. set: function (callback) {
  30552. if (this._onBindObserver) {
  30553. this.onBindObservable.remove(this._onBindObserver);
  30554. }
  30555. this._onBindObserver = this.onBindObservable.add(callback);
  30556. },
  30557. enumerable: true,
  30558. configurable: true
  30559. });
  30560. Object.defineProperty(Material.prototype, "alphaMode", {
  30561. /**
  30562. * Gets the value of the alpha mode.
  30563. */
  30564. get: function () {
  30565. return this._alphaMode;
  30566. },
  30567. /**
  30568. * Sets the value of the alpha mode.
  30569. */
  30570. set: function (value) {
  30571. if (this._alphaMode === value) {
  30572. return;
  30573. }
  30574. this._alphaMode = value;
  30575. this.markAsDirty(Material.TextureDirtyFlag);
  30576. },
  30577. enumerable: true,
  30578. configurable: true
  30579. });
  30580. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  30581. /**
  30582. * Gets the depth pre-pass value.
  30583. */
  30584. get: function () {
  30585. return this._needDepthPrePass;
  30586. },
  30587. /**
  30588. * Sets the need depth pre-pass value.
  30589. */
  30590. set: function (value) {
  30591. if (this._needDepthPrePass === value) {
  30592. return;
  30593. }
  30594. this._needDepthPrePass = value;
  30595. if (this._needDepthPrePass) {
  30596. this.checkReadyOnEveryCall = true;
  30597. }
  30598. },
  30599. enumerable: true,
  30600. configurable: true
  30601. });
  30602. Object.defineProperty(Material.prototype, "fogEnabled", {
  30603. /**
  30604. * Gets the value of the fog enabled state.
  30605. */
  30606. get: function () {
  30607. return this._fogEnabled;
  30608. },
  30609. /**
  30610. * Sets the state for enabling fog.
  30611. */
  30612. set: function (value) {
  30613. if (this._fogEnabled === value) {
  30614. return;
  30615. }
  30616. this._fogEnabled = value;
  30617. this.markAsDirty(Material.MiscDirtyFlag);
  30618. },
  30619. enumerable: true,
  30620. configurable: true
  30621. });
  30622. Object.defineProperty(Material.prototype, "wireframe", {
  30623. /**
  30624. * Gets a value specifying if wireframe mode is enabled.
  30625. */
  30626. get: function () {
  30627. return this._fillMode === Material.WireFrameFillMode;
  30628. },
  30629. /**
  30630. * Sets the state of wireframe mode.
  30631. */
  30632. set: function (value) {
  30633. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30634. },
  30635. enumerable: true,
  30636. configurable: true
  30637. });
  30638. Object.defineProperty(Material.prototype, "pointsCloud", {
  30639. /**
  30640. * Gets the value specifying if point clouds are enabled.
  30641. */
  30642. get: function () {
  30643. return this._fillMode === Material.PointFillMode;
  30644. },
  30645. /**
  30646. * Sets the state of point cloud mode.
  30647. */
  30648. set: function (value) {
  30649. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30650. },
  30651. enumerable: true,
  30652. configurable: true
  30653. });
  30654. Object.defineProperty(Material.prototype, "fillMode", {
  30655. /**
  30656. * Gets the material fill mode.
  30657. */
  30658. get: function () {
  30659. return this._fillMode;
  30660. },
  30661. /**
  30662. * Sets the material fill mode.
  30663. */
  30664. set: function (value) {
  30665. if (this._fillMode === value) {
  30666. return;
  30667. }
  30668. this._fillMode = value;
  30669. this.markAsDirty(Material.MiscDirtyFlag);
  30670. },
  30671. enumerable: true,
  30672. configurable: true
  30673. });
  30674. /**
  30675. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30676. * subclasses should override adding information pertainent to themselves.
  30677. * @returns - String with material information.
  30678. */
  30679. Material.prototype.toString = function (fullDetails) {
  30680. var ret = "Name: " + this.name;
  30681. if (fullDetails) {
  30682. }
  30683. return ret;
  30684. };
  30685. /**
  30686. * Gets the class name of the material.
  30687. * @returns - String with the class name of the material.
  30688. */
  30689. Material.prototype.getClassName = function () {
  30690. return "Material";
  30691. };
  30692. Object.defineProperty(Material.prototype, "isFrozen", {
  30693. /**
  30694. * Specifies if updates for the material been locked.
  30695. */
  30696. get: function () {
  30697. return this.checkReadyOnlyOnce;
  30698. },
  30699. enumerable: true,
  30700. configurable: true
  30701. });
  30702. /**
  30703. * Locks updates for the material.
  30704. */
  30705. Material.prototype.freeze = function () {
  30706. this.checkReadyOnlyOnce = true;
  30707. };
  30708. /**
  30709. * Unlocks updates for the material.
  30710. */
  30711. Material.prototype.unfreeze = function () {
  30712. this.checkReadyOnlyOnce = false;
  30713. };
  30714. /**
  30715. * Specifies if the material is ready to be used.
  30716. * @param mesh - BJS mesh.
  30717. * @param useInstances - Specifies if instances should be used.
  30718. * @returns - Boolean indicating if the material is ready to be used.
  30719. */
  30720. Material.prototype.isReady = function (mesh, useInstances) {
  30721. return true;
  30722. };
  30723. /**
  30724. * Specifies that the submesh is ready to be used.
  30725. * @param mesh - BJS mesh.
  30726. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  30727. * @param useInstances - Specifies that instances should be used.
  30728. * @returns - boolean indicating that the submesh is ready or not.
  30729. */
  30730. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30731. return false;
  30732. };
  30733. /**
  30734. * Returns the material effect.
  30735. * @returns - Nullable material effect.
  30736. */
  30737. Material.prototype.getEffect = function () {
  30738. return this._effect;
  30739. };
  30740. /**
  30741. * Returns the BJS scene.
  30742. * @returns - BJS Scene.
  30743. */
  30744. Material.prototype.getScene = function () {
  30745. return this._scene;
  30746. };
  30747. /**
  30748. * Specifies if the material will require alpha blending
  30749. * @returns - Boolean specifying if alpha blending is needed.
  30750. */
  30751. Material.prototype.needAlphaBlending = function () {
  30752. return (this.alpha < 1.0);
  30753. };
  30754. /**
  30755. * Specifies if the mesh will require alpha blending.
  30756. * @param mesh - BJS mesh.
  30757. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  30758. */
  30759. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  30760. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  30761. };
  30762. /**
  30763. * Specifies if this material should be rendered in alpha test mode.
  30764. * @returns - Boolean specifying if an alpha test is needed.
  30765. */
  30766. Material.prototype.needAlphaTesting = function () {
  30767. return false;
  30768. };
  30769. /**
  30770. * Gets the texture used for the alpha test.
  30771. * @returns - Nullable alpha test texture.
  30772. */
  30773. Material.prototype.getAlphaTestTexture = function () {
  30774. return null;
  30775. };
  30776. /**
  30777. * Marks the material to indicate that it needs to be re-calculated.
  30778. */
  30779. Material.prototype.markDirty = function () {
  30780. this._wasPreviouslyReady = false;
  30781. };
  30782. Material.prototype._preBind = function (effect, overrideOrientation) {
  30783. if (overrideOrientation === void 0) { overrideOrientation = null; }
  30784. var engine = this._scene.getEngine();
  30785. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  30786. var reverse = orientation === Material.ClockWiseSideOrientation;
  30787. engine.enableEffect(effect ? effect : this._effect);
  30788. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  30789. return reverse;
  30790. };
  30791. /**
  30792. * Binds the material to the mesh.
  30793. * @param world - World transformation matrix.
  30794. * @param mesh - Mesh to bind the material to.
  30795. */
  30796. Material.prototype.bind = function (world, mesh) {
  30797. };
  30798. /**
  30799. * Binds the submesh to the material.
  30800. * @param world - World transformation matrix.
  30801. * @param mesh - Mesh containing the submesh.
  30802. * @param subMesh - Submesh to bind the material to.
  30803. */
  30804. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30805. };
  30806. /**
  30807. * Binds the world matrix to the material.
  30808. * @param world - World transformation matrix.
  30809. */
  30810. Material.prototype.bindOnlyWorldMatrix = function (world) {
  30811. };
  30812. /**
  30813. * Binds the scene's uniform buffer to the effect.
  30814. * @param effect - Effect to bind to the scene uniform buffer.
  30815. * @param sceneUbo - Scene uniform buffer.
  30816. */
  30817. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  30818. sceneUbo.bindToEffect(effect, "Scene");
  30819. };
  30820. /**
  30821. * Binds the view matrix to the effect.
  30822. * @param effect - Effect to bind the view matrix to.
  30823. */
  30824. Material.prototype.bindView = function (effect) {
  30825. if (!this._useUBO) {
  30826. effect.setMatrix("view", this.getScene().getViewMatrix());
  30827. }
  30828. else {
  30829. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30830. }
  30831. };
  30832. /**
  30833. * Binds the view projection matrix to the effect.
  30834. * @param effect - Effect to bind the view projection matrix to.
  30835. */
  30836. Material.prototype.bindViewProjection = function (effect) {
  30837. if (!this._useUBO) {
  30838. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30839. }
  30840. else {
  30841. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30842. }
  30843. };
  30844. /**
  30845. * Specifies if material alpha testing should be turned on for the mesh.
  30846. * @param mesh - BJS mesh.
  30847. */
  30848. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  30849. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  30850. };
  30851. /**
  30852. * Processes to execute after binding the material to a mesh.
  30853. * @param mesh - BJS mesh.
  30854. */
  30855. Material.prototype._afterBind = function (mesh) {
  30856. this._scene._cachedMaterial = this;
  30857. if (mesh) {
  30858. this._scene._cachedVisibility = mesh.visibility;
  30859. }
  30860. else {
  30861. this._scene._cachedVisibility = 1;
  30862. }
  30863. if (mesh) {
  30864. this.onBindObservable.notifyObservers(mesh);
  30865. }
  30866. if (this.disableDepthWrite) {
  30867. var engine = this._scene.getEngine();
  30868. this._cachedDepthWriteState = engine.getDepthWrite();
  30869. engine.setDepthWrite(false);
  30870. }
  30871. };
  30872. /**
  30873. * Unbinds the material from the mesh.
  30874. */
  30875. Material.prototype.unbind = function () {
  30876. this.onUnBindObservable.notifyObservers(this);
  30877. if (this.disableDepthWrite) {
  30878. var engine = this._scene.getEngine();
  30879. engine.setDepthWrite(this._cachedDepthWriteState);
  30880. }
  30881. };
  30882. /**
  30883. * Gets the active textures from the material.
  30884. * @returns - Array of textures.
  30885. */
  30886. Material.prototype.getActiveTextures = function () {
  30887. return [];
  30888. };
  30889. /**
  30890. * Specifies if the material uses a texture.
  30891. * @param texture - Texture to check against the material.
  30892. * @returns - Boolean specifying if the material uses the texture.
  30893. */
  30894. Material.prototype.hasTexture = function (texture) {
  30895. return false;
  30896. };
  30897. /**
  30898. * Makes a duplicate of the material, and gives it a new name.
  30899. * @param name - Name to call the duplicated material.
  30900. * @returns - Nullable cloned material
  30901. */
  30902. Material.prototype.clone = function (name) {
  30903. return null;
  30904. };
  30905. /**
  30906. * Gets the meshes bound to the material.
  30907. * @returns - Array of meshes bound to the material.
  30908. */
  30909. Material.prototype.getBindedMeshes = function () {
  30910. var result = new Array();
  30911. for (var index = 0; index < this._scene.meshes.length; index++) {
  30912. var mesh = this._scene.meshes[index];
  30913. if (mesh.material === this) {
  30914. result.push(mesh);
  30915. }
  30916. }
  30917. return result;
  30918. };
  30919. /**
  30920. * Force shader compilation
  30921. * @param mesh - BJS mesh.
  30922. * @param onCompiled - function to execute once the material is compiled.
  30923. * @param options - options to pass to this function.
  30924. */
  30925. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  30926. var _this = this;
  30927. var localOptions = __assign({ clipPlane: false }, options);
  30928. var subMesh = new BABYLON.BaseSubMesh();
  30929. var scene = this.getScene();
  30930. var checkReady = function () {
  30931. if (!_this._scene || !_this._scene.getEngine()) {
  30932. return;
  30933. }
  30934. if (subMesh._materialDefines) {
  30935. subMesh._materialDefines._renderId = -1;
  30936. }
  30937. var clipPlaneState = scene.clipPlane;
  30938. if (localOptions.clipPlane) {
  30939. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  30940. }
  30941. if (_this.storeEffectOnSubMeshes) {
  30942. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  30943. if (onCompiled) {
  30944. onCompiled(_this);
  30945. }
  30946. }
  30947. else {
  30948. setTimeout(checkReady, 16);
  30949. }
  30950. }
  30951. else {
  30952. if (_this.isReady(mesh)) {
  30953. if (onCompiled) {
  30954. onCompiled(_this);
  30955. }
  30956. }
  30957. else {
  30958. setTimeout(checkReady, 16);
  30959. }
  30960. }
  30961. if (localOptions.clipPlane) {
  30962. scene.clipPlane = clipPlaneState;
  30963. }
  30964. };
  30965. checkReady();
  30966. };
  30967. /**
  30968. * Force shader compilation.
  30969. * @param mesh The mesh that will use this material
  30970. * @param options Additional options for compiling the shaders
  30971. * @returns A promise that resolves when the compilation completes
  30972. */
  30973. Material.prototype.forceCompilationAsync = function (mesh, options) {
  30974. var _this = this;
  30975. return new Promise(function (resolve) {
  30976. _this.forceCompilation(mesh, function () {
  30977. resolve();
  30978. }, options);
  30979. });
  30980. };
  30981. /**
  30982. * Marks a define in the material to indicate that it needs to be re-computed.
  30983. * @param flag - Material define flag.
  30984. */
  30985. Material.prototype.markAsDirty = function (flag) {
  30986. if (flag & Material.TextureDirtyFlag) {
  30987. this._markAllSubMeshesAsTexturesDirty();
  30988. }
  30989. if (flag & Material.LightDirtyFlag) {
  30990. this._markAllSubMeshesAsLightsDirty();
  30991. }
  30992. if (flag & Material.FresnelDirtyFlag) {
  30993. this._markAllSubMeshesAsFresnelDirty();
  30994. }
  30995. if (flag & Material.AttributesDirtyFlag) {
  30996. this._markAllSubMeshesAsAttributesDirty();
  30997. }
  30998. if (flag & Material.MiscDirtyFlag) {
  30999. this._markAllSubMeshesAsMiscDirty();
  31000. }
  31001. this.getScene().resetCachedMaterial();
  31002. };
  31003. /**
  31004. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31005. * @param func - function which checks material defines against the submeshes.
  31006. */
  31007. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31008. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31009. var mesh = _a[_i];
  31010. if (!mesh.subMeshes) {
  31011. continue;
  31012. }
  31013. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31014. var subMesh = _c[_b];
  31015. if (subMesh.getMaterial() !== this) {
  31016. continue;
  31017. }
  31018. if (!subMesh._materialDefines) {
  31019. continue;
  31020. }
  31021. func(subMesh._materialDefines);
  31022. }
  31023. }
  31024. };
  31025. /**
  31026. * Indicates that image processing needs to be re-calculated for all submeshes.
  31027. */
  31028. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31029. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31030. };
  31031. /**
  31032. * Indicates that textures need to be re-calculated for all submeshes.
  31033. */
  31034. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31035. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31036. };
  31037. /**
  31038. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31039. */
  31040. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31041. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31042. };
  31043. /**
  31044. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31045. */
  31046. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31047. this._markAllSubMeshesAsDirty(function (defines) {
  31048. defines.markAsFresnelDirty();
  31049. defines.markAsMiscDirty();
  31050. });
  31051. };
  31052. /**
  31053. * Indicates that lights need to be re-calculated for all submeshes.
  31054. */
  31055. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31056. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31057. };
  31058. /**
  31059. * Indicates that attributes need to be re-calculated for all submeshes.
  31060. */
  31061. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31062. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31063. };
  31064. /**
  31065. * Indicates that misc needs to be re-calculated for all submeshes.
  31066. */
  31067. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31068. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31069. };
  31070. /**
  31071. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31072. */
  31073. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31074. this._markAllSubMeshesAsDirty(function (defines) {
  31075. defines.markAsTexturesDirty();
  31076. defines.markAsMiscDirty();
  31077. });
  31078. };
  31079. /**
  31080. * Disposes the material.
  31081. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31082. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31083. */
  31084. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31085. // Animations
  31086. this.getScene().stopAnimation(this);
  31087. // Remove from scene
  31088. var index = this._scene.materials.indexOf(this);
  31089. if (index >= 0) {
  31090. this._scene.materials.splice(index, 1);
  31091. }
  31092. // Remove from meshes
  31093. for (index = 0; index < this._scene.meshes.length; index++) {
  31094. var mesh = this._scene.meshes[index];
  31095. if (mesh.material === this) {
  31096. mesh.material = null;
  31097. if (mesh.geometry) {
  31098. var geometry = (mesh.geometry);
  31099. if (this.storeEffectOnSubMeshes) {
  31100. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31101. var subMesh = _a[_i];
  31102. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31103. if (forceDisposeEffect && subMesh._materialEffect) {
  31104. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31105. }
  31106. }
  31107. }
  31108. else {
  31109. geometry._releaseVertexArrayObject(this._effect);
  31110. }
  31111. }
  31112. }
  31113. }
  31114. this._uniformBuffer.dispose();
  31115. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31116. if (forceDisposeEffect && this._effect) {
  31117. if (!this.storeEffectOnSubMeshes) {
  31118. this._scene.getEngine()._releaseEffect(this._effect);
  31119. }
  31120. this._effect = null;
  31121. }
  31122. // Callback
  31123. this.onDisposeObservable.notifyObservers(this);
  31124. this.onDisposeObservable.clear();
  31125. this.onBindObservable.clear();
  31126. this.onUnBindObservable.clear();
  31127. };
  31128. /**
  31129. * Serializes this material.
  31130. * @returns - serialized material object.
  31131. */
  31132. Material.prototype.serialize = function () {
  31133. return BABYLON.SerializationHelper.Serialize(this);
  31134. };
  31135. /**
  31136. * Creates a MultiMaterial from parse MultiMaterial data.
  31137. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31138. * @param scene - BJS scene.
  31139. * @returns - MultiMaterial.
  31140. */
  31141. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31142. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31143. multiMaterial.id = parsedMultiMaterial.id;
  31144. if (BABYLON.Tags) {
  31145. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31146. }
  31147. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31148. var subMatId = parsedMultiMaterial.materials[matIndex];
  31149. if (subMatId) {
  31150. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31151. }
  31152. else {
  31153. multiMaterial.subMaterials.push(null);
  31154. }
  31155. }
  31156. return multiMaterial;
  31157. };
  31158. /**
  31159. * Creates a material from parsed material data.
  31160. * @param parsedMaterial - Parsed material data.
  31161. * @param scene - BJS scene.
  31162. * @param rootUrl - Root URL containing the material information.
  31163. * @returns - Parsed material.
  31164. */
  31165. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31166. if (!parsedMaterial.customType) {
  31167. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31168. }
  31169. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31170. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31171. if (!BABYLON.LegacyPBRMaterial) {
  31172. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31173. return;
  31174. }
  31175. }
  31176. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31177. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31178. ;
  31179. };
  31180. // Triangle views
  31181. Material._TriangleFillMode = 0;
  31182. Material._WireFrameFillMode = 1;
  31183. Material._PointFillMode = 2;
  31184. // Draw modes
  31185. Material._PointListDrawMode = 3;
  31186. Material._LineListDrawMode = 4;
  31187. Material._LineLoopDrawMode = 5;
  31188. Material._LineStripDrawMode = 6;
  31189. Material._TriangleStripDrawMode = 7;
  31190. Material._TriangleFanDrawMode = 8;
  31191. /**
  31192. * Stores the clock-wise side orientation.
  31193. */
  31194. Material._ClockWiseSideOrientation = 0;
  31195. /**
  31196. * Stores the counter clock-wise side orientation.
  31197. */
  31198. Material._CounterClockWiseSideOrientation = 1;
  31199. /**
  31200. * The dirty texture flag value.
  31201. */
  31202. Material._TextureDirtyFlag = 1;
  31203. /**
  31204. * The dirty light flag value.
  31205. */
  31206. Material._LightDirtyFlag = 2;
  31207. /**
  31208. * The dirty fresnel flag value.
  31209. */
  31210. Material._FresnelDirtyFlag = 4;
  31211. /**
  31212. * The dirty attribute flag value.
  31213. */
  31214. Material._AttributesDirtyFlag = 8;
  31215. /**
  31216. * The dirty misc flag value.
  31217. */
  31218. Material._MiscDirtyFlag = 16;
  31219. __decorate([
  31220. BABYLON.serialize()
  31221. ], Material.prototype, "id", void 0);
  31222. __decorate([
  31223. BABYLON.serialize()
  31224. ], Material.prototype, "name", void 0);
  31225. __decorate([
  31226. BABYLON.serialize()
  31227. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31228. __decorate([
  31229. BABYLON.serialize()
  31230. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31231. __decorate([
  31232. BABYLON.serialize()
  31233. ], Material.prototype, "state", void 0);
  31234. __decorate([
  31235. BABYLON.serialize("alpha")
  31236. ], Material.prototype, "_alpha", void 0);
  31237. __decorate([
  31238. BABYLON.serialize("backFaceCulling")
  31239. ], Material.prototype, "_backFaceCulling", void 0);
  31240. __decorate([
  31241. BABYLON.serialize()
  31242. ], Material.prototype, "sideOrientation", void 0);
  31243. __decorate([
  31244. BABYLON.serialize("alphaMode")
  31245. ], Material.prototype, "_alphaMode", void 0);
  31246. __decorate([
  31247. BABYLON.serialize()
  31248. ], Material.prototype, "_needDepthPrePass", void 0);
  31249. __decorate([
  31250. BABYLON.serialize()
  31251. ], Material.prototype, "disableDepthWrite", void 0);
  31252. __decorate([
  31253. BABYLON.serialize()
  31254. ], Material.prototype, "forceDepthWrite", void 0);
  31255. __decorate([
  31256. BABYLON.serialize()
  31257. ], Material.prototype, "separateCullingPass", void 0);
  31258. __decorate([
  31259. BABYLON.serialize("fogEnabled")
  31260. ], Material.prototype, "_fogEnabled", void 0);
  31261. __decorate([
  31262. BABYLON.serialize()
  31263. ], Material.prototype, "pointSize", void 0);
  31264. __decorate([
  31265. BABYLON.serialize()
  31266. ], Material.prototype, "zOffset", void 0);
  31267. __decorate([
  31268. BABYLON.serialize()
  31269. ], Material.prototype, "wireframe", null);
  31270. __decorate([
  31271. BABYLON.serialize()
  31272. ], Material.prototype, "pointsCloud", null);
  31273. __decorate([
  31274. BABYLON.serialize()
  31275. ], Material.prototype, "fillMode", null);
  31276. return Material;
  31277. }());
  31278. BABYLON.Material = Material;
  31279. })(BABYLON || (BABYLON = {}));
  31280. //# sourceMappingURL=babylon.material.js.map
  31281. var BABYLON;
  31282. (function (BABYLON) {
  31283. var UniformBuffer = /** @class */ (function () {
  31284. /**
  31285. * Uniform buffer objects.
  31286. *
  31287. * Handles blocks of uniform on the GPU.
  31288. *
  31289. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31290. *
  31291. * For more information, please refer to :
  31292. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31293. */
  31294. function UniformBuffer(engine, data, dynamic) {
  31295. this._engine = engine;
  31296. this._noUBO = !engine.supportsUniformBuffers;
  31297. this._dynamic = dynamic;
  31298. this._data = data || [];
  31299. this._uniformLocations = {};
  31300. this._uniformSizes = {};
  31301. this._uniformLocationPointer = 0;
  31302. this._needSync = false;
  31303. if (this._noUBO) {
  31304. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31305. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31306. this.updateFloat = this._updateFloatForEffect;
  31307. this.updateFloat2 = this._updateFloat2ForEffect;
  31308. this.updateFloat3 = this._updateFloat3ForEffect;
  31309. this.updateFloat4 = this._updateFloat4ForEffect;
  31310. this.updateMatrix = this._updateMatrixForEffect;
  31311. this.updateVector3 = this._updateVector3ForEffect;
  31312. this.updateVector4 = this._updateVector4ForEffect;
  31313. this.updateColor3 = this._updateColor3ForEffect;
  31314. this.updateColor4 = this._updateColor4ForEffect;
  31315. }
  31316. else {
  31317. this._engine._uniformBuffers.push(this);
  31318. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31319. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31320. this.updateFloat = this._updateFloatForUniform;
  31321. this.updateFloat2 = this._updateFloat2ForUniform;
  31322. this.updateFloat3 = this._updateFloat3ForUniform;
  31323. this.updateFloat4 = this._updateFloat4ForUniform;
  31324. this.updateMatrix = this._updateMatrixForUniform;
  31325. this.updateVector3 = this._updateVector3ForUniform;
  31326. this.updateVector4 = this._updateVector4ForUniform;
  31327. this.updateColor3 = this._updateColor3ForUniform;
  31328. this.updateColor4 = this._updateColor4ForUniform;
  31329. }
  31330. }
  31331. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31332. // Properties
  31333. /**
  31334. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31335. * or just falling back on setUniformXXX calls.
  31336. */
  31337. get: function () {
  31338. return !this._noUBO;
  31339. },
  31340. enumerable: true,
  31341. configurable: true
  31342. });
  31343. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31344. /**
  31345. * Indicates if the WebGL underlying uniform buffer is in sync
  31346. * with the javascript cache data.
  31347. */
  31348. get: function () {
  31349. return !this._needSync;
  31350. },
  31351. enumerable: true,
  31352. configurable: true
  31353. });
  31354. /**
  31355. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31356. * Also, a dynamic UniformBuffer will disable cache verification and always
  31357. * update the underlying WebGL uniform buffer to the GPU.
  31358. */
  31359. UniformBuffer.prototype.isDynamic = function () {
  31360. return this._dynamic !== undefined;
  31361. };
  31362. /**
  31363. * The data cache on JS side.
  31364. */
  31365. UniformBuffer.prototype.getData = function () {
  31366. return this._bufferData;
  31367. };
  31368. /**
  31369. * The underlying WebGL Uniform buffer.
  31370. */
  31371. UniformBuffer.prototype.getBuffer = function () {
  31372. return this._buffer;
  31373. };
  31374. /**
  31375. * std140 layout specifies how to align data within an UBO structure.
  31376. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31377. * for specs.
  31378. */
  31379. UniformBuffer.prototype._fillAlignment = function (size) {
  31380. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31381. // and 4x4 matrices
  31382. // TODO : change if other types are used
  31383. var alignment;
  31384. if (size <= 2) {
  31385. alignment = size;
  31386. }
  31387. else {
  31388. alignment = 4;
  31389. }
  31390. if ((this._uniformLocationPointer % alignment) !== 0) {
  31391. var oldPointer = this._uniformLocationPointer;
  31392. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31393. var diff = this._uniformLocationPointer - oldPointer;
  31394. for (var i = 0; i < diff; i++) {
  31395. this._data.push(0);
  31396. }
  31397. }
  31398. };
  31399. /**
  31400. * Adds an uniform in the buffer.
  31401. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31402. * for the layout to be correct !
  31403. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31404. * @param {number|number[]} size Data size, or data directly.
  31405. */
  31406. UniformBuffer.prototype.addUniform = function (name, size) {
  31407. if (this._noUBO) {
  31408. return;
  31409. }
  31410. if (this._uniformLocations[name] !== undefined) {
  31411. // Already existing uniform
  31412. return;
  31413. }
  31414. // This function must be called in the order of the shader layout !
  31415. // size can be the size of the uniform, or data directly
  31416. var data;
  31417. if (size instanceof Array) {
  31418. data = size;
  31419. size = data.length;
  31420. }
  31421. else {
  31422. size = size;
  31423. data = [];
  31424. // Fill with zeros
  31425. for (var i = 0; i < size; i++) {
  31426. data.push(0);
  31427. }
  31428. }
  31429. this._fillAlignment(size);
  31430. this._uniformSizes[name] = size;
  31431. this._uniformLocations[name] = this._uniformLocationPointer;
  31432. this._uniformLocationPointer += size;
  31433. for (var i = 0; i < size; i++) {
  31434. this._data.push(data[i]);
  31435. }
  31436. this._needSync = true;
  31437. };
  31438. /**
  31439. * Wrapper for addUniform.
  31440. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31441. * @param {Matrix} mat A 4x4 matrix.
  31442. */
  31443. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31444. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31445. };
  31446. /**
  31447. * Wrapper for addUniform.
  31448. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31449. * @param {number} x
  31450. * @param {number} y
  31451. */
  31452. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31453. var temp = [x, y];
  31454. this.addUniform(name, temp);
  31455. };
  31456. /**
  31457. * Wrapper for addUniform.
  31458. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31459. * @param {number} x
  31460. * @param {number} y
  31461. * @param {number} z
  31462. */
  31463. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31464. var temp = [x, y, z];
  31465. this.addUniform(name, temp);
  31466. };
  31467. /**
  31468. * Wrapper for addUniform.
  31469. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31470. * @param {Color3} color
  31471. */
  31472. UniformBuffer.prototype.addColor3 = function (name, color) {
  31473. var temp = new Array();
  31474. color.toArray(temp);
  31475. this.addUniform(name, temp);
  31476. };
  31477. /**
  31478. * Wrapper for addUniform.
  31479. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31480. * @param {Color3} color
  31481. * @param {number} alpha
  31482. */
  31483. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31484. var temp = new Array();
  31485. color.toArray(temp);
  31486. temp.push(alpha);
  31487. this.addUniform(name, temp);
  31488. };
  31489. /**
  31490. * Wrapper for addUniform.
  31491. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31492. * @param {Vector3} vector
  31493. */
  31494. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31495. var temp = new Array();
  31496. vector.toArray(temp);
  31497. this.addUniform(name, temp);
  31498. };
  31499. /**
  31500. * Wrapper for addUniform.
  31501. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31502. */
  31503. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31504. this.addUniform(name, 12);
  31505. };
  31506. /**
  31507. * Wrapper for addUniform.
  31508. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31509. */
  31510. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31511. this.addUniform(name, 8);
  31512. };
  31513. /**
  31514. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31515. */
  31516. UniformBuffer.prototype.create = function () {
  31517. if (this._noUBO) {
  31518. return;
  31519. }
  31520. if (this._buffer) {
  31521. return; // nothing to do
  31522. }
  31523. // See spec, alignment must be filled as a vec4
  31524. this._fillAlignment(4);
  31525. this._bufferData = new Float32Array(this._data);
  31526. this._rebuild();
  31527. this._needSync = true;
  31528. };
  31529. UniformBuffer.prototype._rebuild = function () {
  31530. if (this._noUBO) {
  31531. return;
  31532. }
  31533. if (this._dynamic) {
  31534. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  31535. }
  31536. else {
  31537. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  31538. }
  31539. };
  31540. /**
  31541. * Updates the WebGL Uniform Buffer on the GPU.
  31542. * If the `dynamic` flag is set to true, no cache comparison is done.
  31543. * Otherwise, the buffer will be updated only if the cache differs.
  31544. */
  31545. UniformBuffer.prototype.update = function () {
  31546. if (!this._buffer) {
  31547. this.create();
  31548. return;
  31549. }
  31550. if (!this._dynamic && !this._needSync) {
  31551. return;
  31552. }
  31553. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  31554. this._needSync = false;
  31555. };
  31556. /**
  31557. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  31558. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31559. * @param {number[]|Float32Array} data Flattened data
  31560. * @param {number} size Size of the data.
  31561. */
  31562. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  31563. var location = this._uniformLocations[uniformName];
  31564. if (location === undefined) {
  31565. if (this._buffer) {
  31566. // Cannot add an uniform if the buffer is already created
  31567. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  31568. return;
  31569. }
  31570. this.addUniform(uniformName, size);
  31571. location = this._uniformLocations[uniformName];
  31572. }
  31573. if (!this._buffer) {
  31574. this.create();
  31575. }
  31576. if (!this._dynamic) {
  31577. // Cache for static uniform buffers
  31578. var changed = false;
  31579. for (var i = 0; i < size; i++) {
  31580. if (this._bufferData[location + i] !== data[i]) {
  31581. changed = true;
  31582. this._bufferData[location + i] = data[i];
  31583. }
  31584. }
  31585. this._needSync = this._needSync || changed;
  31586. }
  31587. else {
  31588. // No cache for dynamic
  31589. for (var i = 0; i < size; i++) {
  31590. this._bufferData[location + i] = data[i];
  31591. }
  31592. }
  31593. };
  31594. // Update methods
  31595. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  31596. // To match std140, matrix must be realigned
  31597. for (var i = 0; i < 3; i++) {
  31598. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  31599. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  31600. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  31601. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31602. }
  31603. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  31604. };
  31605. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  31606. this._currentEffect.setMatrix3x3(name, matrix);
  31607. };
  31608. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  31609. this._currentEffect.setMatrix2x2(name, matrix);
  31610. };
  31611. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  31612. // To match std140, matrix must be realigned
  31613. for (var i = 0; i < 2; i++) {
  31614. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  31615. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  31616. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  31617. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31618. }
  31619. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  31620. };
  31621. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  31622. this._currentEffect.setFloat(name, x);
  31623. };
  31624. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  31625. UniformBuffer._tempBuffer[0] = x;
  31626. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  31627. };
  31628. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  31629. if (suffix === void 0) { suffix = ""; }
  31630. this._currentEffect.setFloat2(name + suffix, x, y);
  31631. };
  31632. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  31633. if (suffix === void 0) { suffix = ""; }
  31634. UniformBuffer._tempBuffer[0] = x;
  31635. UniformBuffer._tempBuffer[1] = y;
  31636. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  31637. };
  31638. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  31639. if (suffix === void 0) { suffix = ""; }
  31640. this._currentEffect.setFloat3(name + suffix, x, y, z);
  31641. };
  31642. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  31643. if (suffix === void 0) { suffix = ""; }
  31644. UniformBuffer._tempBuffer[0] = x;
  31645. UniformBuffer._tempBuffer[1] = y;
  31646. UniformBuffer._tempBuffer[2] = z;
  31647. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31648. };
  31649. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  31650. if (suffix === void 0) { suffix = ""; }
  31651. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  31652. };
  31653. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  31654. if (suffix === void 0) { suffix = ""; }
  31655. UniformBuffer._tempBuffer[0] = x;
  31656. UniformBuffer._tempBuffer[1] = y;
  31657. UniformBuffer._tempBuffer[2] = z;
  31658. UniformBuffer._tempBuffer[3] = w;
  31659. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31660. };
  31661. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  31662. this._currentEffect.setMatrix(name, mat);
  31663. };
  31664. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  31665. this.updateUniform(name, mat.toArray(), 16);
  31666. };
  31667. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  31668. this._currentEffect.setVector3(name, vector);
  31669. };
  31670. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  31671. vector.toArray(UniformBuffer._tempBuffer);
  31672. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31673. };
  31674. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  31675. this._currentEffect.setVector4(name, vector);
  31676. };
  31677. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  31678. vector.toArray(UniformBuffer._tempBuffer);
  31679. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31680. };
  31681. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  31682. if (suffix === void 0) { suffix = ""; }
  31683. this._currentEffect.setColor3(name + suffix, color);
  31684. };
  31685. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  31686. if (suffix === void 0) { suffix = ""; }
  31687. color.toArray(UniformBuffer._tempBuffer);
  31688. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31689. };
  31690. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  31691. if (suffix === void 0) { suffix = ""; }
  31692. this._currentEffect.setColor4(name + suffix, color, alpha);
  31693. };
  31694. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  31695. if (suffix === void 0) { suffix = ""; }
  31696. color.toArray(UniformBuffer._tempBuffer);
  31697. UniformBuffer._tempBuffer[3] = alpha;
  31698. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31699. };
  31700. /**
  31701. * Sets a sampler uniform on the effect.
  31702. * @param {string} name Name of the sampler.
  31703. * @param {Texture} texture
  31704. */
  31705. UniformBuffer.prototype.setTexture = function (name, texture) {
  31706. this._currentEffect.setTexture(name, texture);
  31707. };
  31708. /**
  31709. * Directly updates the value of the uniform in the cache AND on the GPU.
  31710. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31711. * @param {number[]|Float32Array} data Flattened data
  31712. */
  31713. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  31714. this.updateUniform(uniformName, data, data.length);
  31715. this.update();
  31716. };
  31717. /**
  31718. * Binds this uniform buffer to an effect.
  31719. * @param {Effect} effect
  31720. * @param {string} name Name of the uniform block in the shader.
  31721. */
  31722. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  31723. this._currentEffect = effect;
  31724. if (this._noUBO || !this._buffer) {
  31725. return;
  31726. }
  31727. effect.bindUniformBuffer(this._buffer, name);
  31728. };
  31729. /**
  31730. * Disposes the uniform buffer.
  31731. */
  31732. UniformBuffer.prototype.dispose = function () {
  31733. if (this._noUBO) {
  31734. return;
  31735. }
  31736. var index = this._engine._uniformBuffers.indexOf(this);
  31737. if (index !== -1) {
  31738. this._engine._uniformBuffers.splice(index, 1);
  31739. }
  31740. if (!this._buffer) {
  31741. return;
  31742. }
  31743. if (this._engine._releaseBuffer(this._buffer)) {
  31744. this._buffer = null;
  31745. }
  31746. };
  31747. // Pool for avoiding memory leaks
  31748. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  31749. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  31750. return UniformBuffer;
  31751. }());
  31752. BABYLON.UniformBuffer = UniformBuffer;
  31753. })(BABYLON || (BABYLON = {}));
  31754. //# sourceMappingURL=babylon.uniformBuffer.js.map
  31755. var BABYLON;
  31756. (function (BABYLON) {
  31757. var VertexData = /** @class */ (function () {
  31758. function VertexData() {
  31759. }
  31760. VertexData.prototype.set = function (data, kind) {
  31761. switch (kind) {
  31762. case BABYLON.VertexBuffer.PositionKind:
  31763. this.positions = data;
  31764. break;
  31765. case BABYLON.VertexBuffer.NormalKind:
  31766. this.normals = data;
  31767. break;
  31768. case BABYLON.VertexBuffer.TangentKind:
  31769. this.tangents = data;
  31770. break;
  31771. case BABYLON.VertexBuffer.UVKind:
  31772. this.uvs = data;
  31773. break;
  31774. case BABYLON.VertexBuffer.UV2Kind:
  31775. this.uvs2 = data;
  31776. break;
  31777. case BABYLON.VertexBuffer.UV3Kind:
  31778. this.uvs3 = data;
  31779. break;
  31780. case BABYLON.VertexBuffer.UV4Kind:
  31781. this.uvs4 = data;
  31782. break;
  31783. case BABYLON.VertexBuffer.UV5Kind:
  31784. this.uvs5 = data;
  31785. break;
  31786. case BABYLON.VertexBuffer.UV6Kind:
  31787. this.uvs6 = data;
  31788. break;
  31789. case BABYLON.VertexBuffer.ColorKind:
  31790. this.colors = data;
  31791. break;
  31792. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31793. this.matricesIndices = data;
  31794. break;
  31795. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31796. this.matricesWeights = data;
  31797. break;
  31798. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31799. this.matricesIndicesExtra = data;
  31800. break;
  31801. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31802. this.matricesWeightsExtra = data;
  31803. break;
  31804. }
  31805. };
  31806. /**
  31807. * Associates the vertexData to the passed Mesh.
  31808. * Sets it as updatable or not (default `false`).
  31809. * Returns the VertexData.
  31810. */
  31811. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31812. this._applyTo(mesh, updatable);
  31813. return this;
  31814. };
  31815. /**
  31816. * Associates the vertexData to the passed Geometry.
  31817. * Sets it as updatable or not (default `false`).
  31818. * Returns the VertexData.
  31819. */
  31820. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31821. this._applyTo(geometry, updatable);
  31822. return this;
  31823. };
  31824. /**
  31825. * Updates the associated mesh.
  31826. * Returns the VertexData.
  31827. */
  31828. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31829. this._update(mesh);
  31830. return this;
  31831. };
  31832. /**
  31833. * Updates the associated geometry.
  31834. * Returns the VertexData.
  31835. */
  31836. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31837. this._update(geometry);
  31838. return this;
  31839. };
  31840. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31841. if (updatable === void 0) { updatable = false; }
  31842. if (this.positions) {
  31843. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31844. }
  31845. if (this.normals) {
  31846. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  31847. }
  31848. if (this.tangents) {
  31849. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  31850. }
  31851. if (this.uvs) {
  31852. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  31853. }
  31854. if (this.uvs2) {
  31855. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  31856. }
  31857. if (this.uvs3) {
  31858. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  31859. }
  31860. if (this.uvs4) {
  31861. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  31862. }
  31863. if (this.uvs5) {
  31864. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  31865. }
  31866. if (this.uvs6) {
  31867. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  31868. }
  31869. if (this.colors) {
  31870. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  31871. }
  31872. if (this.matricesIndices) {
  31873. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  31874. }
  31875. if (this.matricesWeights) {
  31876. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  31877. }
  31878. if (this.matricesIndicesExtra) {
  31879. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  31880. }
  31881. if (this.matricesWeightsExtra) {
  31882. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  31883. }
  31884. if (this.indices) {
  31885. meshOrGeometry.setIndices(this.indices, null, updatable);
  31886. }
  31887. return this;
  31888. };
  31889. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  31890. if (this.positions) {
  31891. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  31892. }
  31893. if (this.normals) {
  31894. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  31895. }
  31896. if (this.tangents) {
  31897. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  31898. }
  31899. if (this.uvs) {
  31900. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  31901. }
  31902. if (this.uvs2) {
  31903. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  31904. }
  31905. if (this.uvs3) {
  31906. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  31907. }
  31908. if (this.uvs4) {
  31909. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  31910. }
  31911. if (this.uvs5) {
  31912. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  31913. }
  31914. if (this.uvs6) {
  31915. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  31916. }
  31917. if (this.colors) {
  31918. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  31919. }
  31920. if (this.matricesIndices) {
  31921. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  31922. }
  31923. if (this.matricesWeights) {
  31924. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  31925. }
  31926. if (this.matricesIndicesExtra) {
  31927. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  31928. }
  31929. if (this.matricesWeightsExtra) {
  31930. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  31931. }
  31932. if (this.indices) {
  31933. meshOrGeometry.setIndices(this.indices, null);
  31934. }
  31935. return this;
  31936. };
  31937. /**
  31938. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  31939. * Returns the VertexData.
  31940. */
  31941. VertexData.prototype.transform = function (matrix) {
  31942. var transformed = BABYLON.Vector3.Zero();
  31943. var index;
  31944. if (this.positions) {
  31945. var position = BABYLON.Vector3.Zero();
  31946. for (index = 0; index < this.positions.length; index += 3) {
  31947. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  31948. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  31949. this.positions[index] = transformed.x;
  31950. this.positions[index + 1] = transformed.y;
  31951. this.positions[index + 2] = transformed.z;
  31952. }
  31953. }
  31954. if (this.normals) {
  31955. var normal = BABYLON.Vector3.Zero();
  31956. for (index = 0; index < this.normals.length; index += 3) {
  31957. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  31958. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  31959. this.normals[index] = transformed.x;
  31960. this.normals[index + 1] = transformed.y;
  31961. this.normals[index + 2] = transformed.z;
  31962. }
  31963. }
  31964. if (this.tangents) {
  31965. var tangent = BABYLON.Vector4.Zero();
  31966. var tangentTransformed = BABYLON.Vector4.Zero();
  31967. for (index = 0; index < this.tangents.length; index += 4) {
  31968. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  31969. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  31970. this.tangents[index] = tangentTransformed.x;
  31971. this.tangents[index + 1] = tangentTransformed.y;
  31972. this.tangents[index + 2] = tangentTransformed.z;
  31973. this.tangents[index + 3] = tangentTransformed.w;
  31974. }
  31975. }
  31976. return this;
  31977. };
  31978. /**
  31979. * Merges the passed VertexData into the current one.
  31980. * Returns the modified VertexData.
  31981. */
  31982. VertexData.prototype.merge = function (other) {
  31983. this._validate();
  31984. other._validate();
  31985. if (!this.normals !== !other.normals ||
  31986. !this.tangents !== !other.tangents ||
  31987. !this.uvs !== !other.uvs ||
  31988. !this.uvs2 !== !other.uvs2 ||
  31989. !this.uvs3 !== !other.uvs3 ||
  31990. !this.uvs4 !== !other.uvs4 ||
  31991. !this.uvs5 !== !other.uvs5 ||
  31992. !this.uvs6 !== !other.uvs6 ||
  31993. !this.colors !== !other.colors ||
  31994. !this.matricesIndices !== !other.matricesIndices ||
  31995. !this.matricesWeights !== !other.matricesWeights ||
  31996. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  31997. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  31998. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  31999. }
  32000. if (other.indices) {
  32001. if (!this.indices) {
  32002. this.indices = [];
  32003. }
  32004. var offset = this.positions ? this.positions.length / 3 : 0;
  32005. for (var index = 0; index < other.indices.length; index++) {
  32006. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32007. this.indices.push(other.indices[index] + offset);
  32008. }
  32009. }
  32010. this.positions = this._mergeElement(this.positions, other.positions);
  32011. this.normals = this._mergeElement(this.normals, other.normals);
  32012. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32013. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32014. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32015. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32016. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32017. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32018. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32019. this.colors = this._mergeElement(this.colors, other.colors);
  32020. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32021. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32022. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32023. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32024. return this;
  32025. };
  32026. VertexData.prototype._mergeElement = function (source, other) {
  32027. if (!source) {
  32028. return other;
  32029. }
  32030. if (!other) {
  32031. return source;
  32032. }
  32033. var len = other.length + source.length;
  32034. var isSrcTypedArray = source instanceof Float32Array;
  32035. var isOthTypedArray = other instanceof Float32Array;
  32036. // use non-loop method when the source is Float32Array
  32037. if (isSrcTypedArray) {
  32038. var ret32 = new Float32Array(len);
  32039. ret32.set(source);
  32040. ret32.set(other, source.length);
  32041. return ret32;
  32042. // source is number[], when other is also use concat
  32043. }
  32044. else if (!isOthTypedArray) {
  32045. return source.concat(other);
  32046. // source is a number[], but other is a Float32Array, loop required
  32047. }
  32048. else {
  32049. var ret = source.slice(0); // copy source to a separate array
  32050. for (var i = 0, len = other.length; i < len; i++) {
  32051. ret.push(other[i]);
  32052. }
  32053. return ret;
  32054. }
  32055. };
  32056. VertexData.prototype._validate = function () {
  32057. if (!this.positions) {
  32058. throw new Error("Positions are required");
  32059. }
  32060. var getElementCount = function (kind, values) {
  32061. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32062. if ((values.length % stride) !== 0) {
  32063. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32064. }
  32065. return values.length / stride;
  32066. };
  32067. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32068. var validateElementCount = function (kind, values) {
  32069. var elementCount = getElementCount(kind, values);
  32070. if (elementCount !== positionsElementCount) {
  32071. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32072. }
  32073. };
  32074. if (this.normals)
  32075. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32076. if (this.tangents)
  32077. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32078. if (this.uvs)
  32079. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32080. if (this.uvs2)
  32081. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32082. if (this.uvs3)
  32083. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32084. if (this.uvs4)
  32085. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32086. if (this.uvs5)
  32087. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32088. if (this.uvs6)
  32089. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32090. if (this.colors)
  32091. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32092. if (this.matricesIndices)
  32093. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32094. if (this.matricesWeights)
  32095. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32096. if (this.matricesIndicesExtra)
  32097. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32098. if (this.matricesWeightsExtra)
  32099. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32100. };
  32101. /**
  32102. * Serializes the VertexData.
  32103. * Returns a serialized object.
  32104. */
  32105. VertexData.prototype.serialize = function () {
  32106. var serializationObject = this.serialize();
  32107. if (this.positions) {
  32108. serializationObject.positions = this.positions;
  32109. }
  32110. if (this.normals) {
  32111. serializationObject.normals = this.normals;
  32112. }
  32113. if (this.tangents) {
  32114. serializationObject.tangents = this.tangents;
  32115. }
  32116. if (this.uvs) {
  32117. serializationObject.uvs = this.uvs;
  32118. }
  32119. if (this.uvs2) {
  32120. serializationObject.uvs2 = this.uvs2;
  32121. }
  32122. if (this.uvs3) {
  32123. serializationObject.uvs3 = this.uvs3;
  32124. }
  32125. if (this.uvs4) {
  32126. serializationObject.uvs4 = this.uvs4;
  32127. }
  32128. if (this.uvs5) {
  32129. serializationObject.uvs5 = this.uvs5;
  32130. }
  32131. if (this.uvs6) {
  32132. serializationObject.uvs6 = this.uvs6;
  32133. }
  32134. if (this.colors) {
  32135. serializationObject.colors = this.colors;
  32136. }
  32137. if (this.matricesIndices) {
  32138. serializationObject.matricesIndices = this.matricesIndices;
  32139. serializationObject.matricesIndices._isExpanded = true;
  32140. }
  32141. if (this.matricesWeights) {
  32142. serializationObject.matricesWeights = this.matricesWeights;
  32143. }
  32144. if (this.matricesIndicesExtra) {
  32145. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32146. serializationObject.matricesIndicesExtra._isExpanded = true;
  32147. }
  32148. if (this.matricesWeightsExtra) {
  32149. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32150. }
  32151. serializationObject.indices = this.indices;
  32152. return serializationObject;
  32153. };
  32154. // Statics
  32155. /**
  32156. * Returns the object VertexData associated to the passed mesh.
  32157. */
  32158. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32159. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32160. };
  32161. /**
  32162. * Returns the object VertexData associated to the passed geometry.
  32163. */
  32164. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32165. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32166. };
  32167. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32168. var result = new VertexData();
  32169. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32170. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32171. }
  32172. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32173. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32174. }
  32175. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32176. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32177. }
  32178. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32179. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32180. }
  32181. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32182. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32183. }
  32184. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32185. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32186. }
  32187. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32188. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32189. }
  32190. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32191. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32192. }
  32193. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32194. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32195. }
  32196. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32197. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32198. }
  32199. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32200. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32201. }
  32202. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32203. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32204. }
  32205. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32206. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32207. }
  32208. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32209. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32210. }
  32211. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32212. return result;
  32213. };
  32214. /**
  32215. * Creates the vertexData of the Ribbon.
  32216. */
  32217. VertexData.CreateRibbon = function (options) {
  32218. var pathArray = options.pathArray;
  32219. var closeArray = options.closeArray || false;
  32220. var closePath = options.closePath || false;
  32221. var invertUV = options.invertUV || false;
  32222. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32223. var offset = options.offset || defaultOffset;
  32224. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32225. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32226. var customUV = options.uvs;
  32227. var customColors = options.colors;
  32228. var positions = [];
  32229. var indices = [];
  32230. var normals = [];
  32231. var uvs = [];
  32232. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32233. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32234. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32235. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32236. var minlg; // minimal length among all paths from pathArray
  32237. var lg = []; // array of path lengths : nb of vertex per path
  32238. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32239. var p; // path iterator
  32240. var i; // point iterator
  32241. var j; // point iterator
  32242. // if single path in pathArray
  32243. if (pathArray.length < 2) {
  32244. var ar1 = [];
  32245. var ar2 = [];
  32246. for (i = 0; i < pathArray[0].length - offset; i++) {
  32247. ar1.push(pathArray[0][i]);
  32248. ar2.push(pathArray[0][i + offset]);
  32249. }
  32250. pathArray = [ar1, ar2];
  32251. }
  32252. // positions and horizontal distances (u)
  32253. var idc = 0;
  32254. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32255. var path;
  32256. var l;
  32257. minlg = pathArray[0].length;
  32258. var vectlg;
  32259. var dist;
  32260. for (p = 0; p < pathArray.length; p++) {
  32261. uTotalDistance[p] = 0;
  32262. us[p] = [0];
  32263. path = pathArray[p];
  32264. l = path.length;
  32265. minlg = (minlg < l) ? minlg : l;
  32266. j = 0;
  32267. while (j < l) {
  32268. positions.push(path[j].x, path[j].y, path[j].z);
  32269. if (j > 0) {
  32270. vectlg = path[j].subtract(path[j - 1]).length();
  32271. dist = vectlg + uTotalDistance[p];
  32272. us[p].push(dist);
  32273. uTotalDistance[p] = dist;
  32274. }
  32275. j++;
  32276. }
  32277. if (closePath) {
  32278. j--;
  32279. positions.push(path[0].x, path[0].y, path[0].z);
  32280. vectlg = path[j].subtract(path[0]).length();
  32281. dist = vectlg + uTotalDistance[p];
  32282. us[p].push(dist);
  32283. uTotalDistance[p] = dist;
  32284. }
  32285. lg[p] = l + closePathCorr;
  32286. idx[p] = idc;
  32287. idc += (l + closePathCorr);
  32288. }
  32289. // vertical distances (v)
  32290. var path1;
  32291. var path2;
  32292. var vertex1 = null;
  32293. var vertex2 = null;
  32294. for (i = 0; i < minlg + closePathCorr; i++) {
  32295. vTotalDistance[i] = 0;
  32296. vs[i] = [0];
  32297. for (p = 0; p < pathArray.length - 1; p++) {
  32298. path1 = pathArray[p];
  32299. path2 = pathArray[p + 1];
  32300. if (i === minlg) {
  32301. vertex1 = path1[0];
  32302. vertex2 = path2[0];
  32303. }
  32304. else {
  32305. vertex1 = path1[i];
  32306. vertex2 = path2[i];
  32307. }
  32308. vectlg = vertex2.subtract(vertex1).length();
  32309. dist = vectlg + vTotalDistance[i];
  32310. vs[i].push(dist);
  32311. vTotalDistance[i] = dist;
  32312. }
  32313. if (closeArray && vertex2 && vertex1) {
  32314. path1 = pathArray[p];
  32315. path2 = pathArray[0];
  32316. if (i === minlg) {
  32317. vertex2 = path2[0];
  32318. }
  32319. vectlg = vertex2.subtract(vertex1).length();
  32320. dist = vectlg + vTotalDistance[i];
  32321. vTotalDistance[i] = dist;
  32322. }
  32323. }
  32324. // uvs
  32325. var u;
  32326. var v;
  32327. if (customUV) {
  32328. for (p = 0; p < customUV.length; p++) {
  32329. uvs.push(customUV[p].x, customUV[p].y);
  32330. }
  32331. }
  32332. else {
  32333. for (p = 0; p < pathArray.length; p++) {
  32334. for (i = 0; i < minlg + closePathCorr; i++) {
  32335. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32336. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32337. if (invertUV) {
  32338. uvs.push(v, u);
  32339. }
  32340. else {
  32341. uvs.push(u, v);
  32342. }
  32343. }
  32344. }
  32345. }
  32346. // indices
  32347. p = 0; // path index
  32348. var pi = 0; // positions array index
  32349. var l1 = lg[p] - 1; // path1 length
  32350. var l2 = lg[p + 1] - 1; // path2 length
  32351. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32352. var shft = idx[1] - idx[0]; // shift
  32353. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32354. while (pi <= min && p < path1nb) {
  32355. // 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
  32356. indices.push(pi, pi + shft, pi + 1);
  32357. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32358. pi += 1;
  32359. if (pi === min) {
  32360. p++;
  32361. if (p === lg.length - 1) {
  32362. shft = idx[0] - idx[p];
  32363. l1 = lg[p] - 1;
  32364. l2 = lg[0] - 1;
  32365. }
  32366. else {
  32367. shft = idx[p + 1] - idx[p];
  32368. l1 = lg[p] - 1;
  32369. l2 = lg[p + 1] - 1;
  32370. }
  32371. pi = idx[p];
  32372. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32373. }
  32374. }
  32375. // normals
  32376. VertexData.ComputeNormals(positions, indices, normals);
  32377. if (closePath) {
  32378. var indexFirst = 0;
  32379. var indexLast = 0;
  32380. for (p = 0; p < pathArray.length; p++) {
  32381. indexFirst = idx[p] * 3;
  32382. if (p + 1 < pathArray.length) {
  32383. indexLast = (idx[p + 1] - 1) * 3;
  32384. }
  32385. else {
  32386. indexLast = normals.length - 3;
  32387. }
  32388. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32389. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32390. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32391. normals[indexLast] = normals[indexFirst];
  32392. normals[indexLast + 1] = normals[indexFirst + 1];
  32393. normals[indexLast + 2] = normals[indexFirst + 2];
  32394. }
  32395. }
  32396. // sides
  32397. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32398. // Colors
  32399. var colors = null;
  32400. if (customColors) {
  32401. colors = new Float32Array(customColors.length * 4);
  32402. for (var c = 0; c < customColors.length; c++) {
  32403. colors[c * 4] = customColors[c].r;
  32404. colors[c * 4 + 1] = customColors[c].g;
  32405. colors[c * 4 + 2] = customColors[c].b;
  32406. colors[c * 4 + 3] = customColors[c].a;
  32407. }
  32408. }
  32409. // Result
  32410. var vertexData = new VertexData();
  32411. var positions32 = new Float32Array(positions);
  32412. var normals32 = new Float32Array(normals);
  32413. var uvs32 = new Float32Array(uvs);
  32414. vertexData.indices = indices;
  32415. vertexData.positions = positions32;
  32416. vertexData.normals = normals32;
  32417. vertexData.uvs = uvs32;
  32418. if (colors) {
  32419. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32420. }
  32421. if (closePath) {
  32422. vertexData._idx = idx;
  32423. }
  32424. return vertexData;
  32425. };
  32426. /**
  32427. * Creates the VertexData of the Box.
  32428. */
  32429. VertexData.CreateBox = function (options) {
  32430. var normalsSource = [
  32431. new BABYLON.Vector3(0, 0, 1),
  32432. new BABYLON.Vector3(0, 0, -1),
  32433. new BABYLON.Vector3(1, 0, 0),
  32434. new BABYLON.Vector3(-1, 0, 0),
  32435. new BABYLON.Vector3(0, 1, 0),
  32436. new BABYLON.Vector3(0, -1, 0)
  32437. ];
  32438. var indices = [];
  32439. var positions = [];
  32440. var normals = [];
  32441. var uvs = [];
  32442. var width = options.width || options.size || 1;
  32443. var height = options.height || options.size || 1;
  32444. var depth = options.depth || options.size || 1;
  32445. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32446. var faceUV = options.faceUV || new Array(6);
  32447. var faceColors = options.faceColors;
  32448. var colors = [];
  32449. // default face colors and UV if undefined
  32450. for (var f = 0; f < 6; f++) {
  32451. if (faceUV[f] === undefined) {
  32452. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32453. }
  32454. if (faceColors && faceColors[f] === undefined) {
  32455. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32456. }
  32457. }
  32458. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32459. // Create each face in turn.
  32460. for (var index = 0; index < normalsSource.length; index++) {
  32461. var normal = normalsSource[index];
  32462. // Get two vectors perpendicular to the face normal and to each other.
  32463. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32464. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32465. // Six indices (two triangles) per face.
  32466. var verticesLength = positions.length / 3;
  32467. indices.push(verticesLength);
  32468. indices.push(verticesLength + 1);
  32469. indices.push(verticesLength + 2);
  32470. indices.push(verticesLength);
  32471. indices.push(verticesLength + 2);
  32472. indices.push(verticesLength + 3);
  32473. // Four vertices per face.
  32474. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32475. positions.push(vertex.x, vertex.y, vertex.z);
  32476. normals.push(normal.x, normal.y, normal.z);
  32477. uvs.push(faceUV[index].z, faceUV[index].w);
  32478. if (faceColors) {
  32479. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32480. }
  32481. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32482. positions.push(vertex.x, vertex.y, vertex.z);
  32483. normals.push(normal.x, normal.y, normal.z);
  32484. uvs.push(faceUV[index].x, faceUV[index].w);
  32485. if (faceColors) {
  32486. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32487. }
  32488. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32489. positions.push(vertex.x, vertex.y, vertex.z);
  32490. normals.push(normal.x, normal.y, normal.z);
  32491. uvs.push(faceUV[index].x, faceUV[index].y);
  32492. if (faceColors) {
  32493. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32494. }
  32495. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32496. positions.push(vertex.x, vertex.y, vertex.z);
  32497. normals.push(normal.x, normal.y, normal.z);
  32498. uvs.push(faceUV[index].z, faceUV[index].y);
  32499. if (faceColors) {
  32500. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32501. }
  32502. }
  32503. // sides
  32504. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32505. // Result
  32506. var vertexData = new VertexData();
  32507. vertexData.indices = indices;
  32508. vertexData.positions = positions;
  32509. vertexData.normals = normals;
  32510. vertexData.uvs = uvs;
  32511. if (faceColors) {
  32512. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32513. vertexData.colors = totalColors;
  32514. }
  32515. return vertexData;
  32516. };
  32517. /**
  32518. * Creates the VertexData of the Sphere.
  32519. */
  32520. VertexData.CreateSphere = function (options) {
  32521. var segments = options.segments || 32;
  32522. var diameterX = options.diameterX || options.diameter || 1;
  32523. var diameterY = options.diameterY || options.diameter || 1;
  32524. var diameterZ = options.diameterZ || options.diameter || 1;
  32525. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32526. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32527. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32528. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32529. var totalZRotationSteps = 2 + segments;
  32530. var totalYRotationSteps = 2 * totalZRotationSteps;
  32531. var indices = [];
  32532. var positions = [];
  32533. var normals = [];
  32534. var uvs = [];
  32535. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32536. var normalizedZ = zRotationStep / totalZRotationSteps;
  32537. var angleZ = normalizedZ * Math.PI * slice;
  32538. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32539. var normalizedY = yRotationStep / totalYRotationSteps;
  32540. var angleY = normalizedY * Math.PI * 2 * arc;
  32541. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32542. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32543. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32544. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32545. var vertex = complete.multiply(radius);
  32546. var normal = complete.divide(radius).normalize();
  32547. positions.push(vertex.x, vertex.y, vertex.z);
  32548. normals.push(normal.x, normal.y, normal.z);
  32549. uvs.push(normalizedY, normalizedZ);
  32550. }
  32551. if (zRotationStep > 0) {
  32552. var verticesCount = positions.length / 3;
  32553. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32554. indices.push((firstIndex));
  32555. indices.push((firstIndex + 1));
  32556. indices.push(firstIndex + totalYRotationSteps + 1);
  32557. indices.push((firstIndex + totalYRotationSteps + 1));
  32558. indices.push((firstIndex + 1));
  32559. indices.push((firstIndex + totalYRotationSteps + 2));
  32560. }
  32561. }
  32562. }
  32563. // Sides
  32564. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32565. // Result
  32566. var vertexData = new VertexData();
  32567. vertexData.indices = indices;
  32568. vertexData.positions = positions;
  32569. vertexData.normals = normals;
  32570. vertexData.uvs = uvs;
  32571. return vertexData;
  32572. };
  32573. /**
  32574. * Creates the VertexData of the Cylinder or Cone.
  32575. */
  32576. VertexData.CreateCylinder = function (options) {
  32577. var height = options.height || 2;
  32578. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32579. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32580. var tessellation = options.tessellation || 24;
  32581. var subdivisions = options.subdivisions || 1;
  32582. var hasRings = options.hasRings ? true : false;
  32583. var enclose = options.enclose ? true : false;
  32584. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32585. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32586. var faceUV = options.faceUV || new Array(3);
  32587. var faceColors = options.faceColors;
  32588. // default face colors and UV if undefined
  32589. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32590. var ringNb = (hasRings) ? subdivisions : 1;
  32591. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32592. var f;
  32593. for (f = 0; f < surfaceNb; f++) {
  32594. if (faceColors && faceColors[f] === undefined) {
  32595. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32596. }
  32597. }
  32598. for (f = 0; f < surfaceNb; f++) {
  32599. if (faceUV && faceUV[f] === undefined) {
  32600. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32601. }
  32602. }
  32603. var indices = new Array();
  32604. var positions = new Array();
  32605. var normals = new Array();
  32606. var uvs = new Array();
  32607. var colors = new Array();
  32608. var angle_step = Math.PI * 2 * arc / tessellation;
  32609. var angle;
  32610. var h;
  32611. var radius;
  32612. var tan = (diameterBottom - diameterTop) / 2 / height;
  32613. var ringVertex = BABYLON.Vector3.Zero();
  32614. var ringNormal = BABYLON.Vector3.Zero();
  32615. var ringFirstVertex = BABYLON.Vector3.Zero();
  32616. var ringFirstNormal = BABYLON.Vector3.Zero();
  32617. var quadNormal = BABYLON.Vector3.Zero();
  32618. var Y = BABYLON.Axis.Y;
  32619. // positions, normals, uvs
  32620. var i;
  32621. var j;
  32622. var r;
  32623. var ringIdx = 1;
  32624. var s = 1; // surface index
  32625. var cs = 0;
  32626. var v = 0;
  32627. for (i = 0; i <= subdivisions; i++) {
  32628. h = i / subdivisions;
  32629. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32630. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32631. for (r = 0; r < ringIdx; r++) {
  32632. if (hasRings) {
  32633. s += r;
  32634. }
  32635. if (enclose) {
  32636. s += 2 * r;
  32637. }
  32638. for (j = 0; j <= tessellation; j++) {
  32639. angle = j * angle_step;
  32640. // position
  32641. ringVertex.x = Math.cos(-angle) * radius;
  32642. ringVertex.y = -height / 2 + h * height;
  32643. ringVertex.z = Math.sin(-angle) * radius;
  32644. // normal
  32645. if (diameterTop === 0 && i === subdivisions) {
  32646. // if no top cap, reuse former normals
  32647. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32648. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32649. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32650. }
  32651. else {
  32652. ringNormal.x = ringVertex.x;
  32653. ringNormal.z = ringVertex.z;
  32654. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32655. ringNormal.normalize();
  32656. }
  32657. // keep first ring vertex values for enclose
  32658. if (j === 0) {
  32659. ringFirstVertex.copyFrom(ringVertex);
  32660. ringFirstNormal.copyFrom(ringNormal);
  32661. }
  32662. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32663. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32664. if (hasRings) {
  32665. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32666. }
  32667. else {
  32668. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32669. }
  32670. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32671. if (faceColors) {
  32672. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32673. }
  32674. }
  32675. // if enclose, add four vertices and their dedicated normals
  32676. if (arc !== 1 && enclose) {
  32677. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32678. positions.push(0, ringVertex.y, 0);
  32679. positions.push(0, ringVertex.y, 0);
  32680. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32681. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32682. quadNormal.normalize();
  32683. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32684. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32685. quadNormal.normalize();
  32686. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32687. if (hasRings) {
  32688. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32689. }
  32690. else {
  32691. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32692. }
  32693. uvs.push(faceUV[s + 1].x, v);
  32694. uvs.push(faceUV[s + 1].z, v);
  32695. if (hasRings) {
  32696. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32697. }
  32698. else {
  32699. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32700. }
  32701. uvs.push(faceUV[s + 2].x, v);
  32702. uvs.push(faceUV[s + 2].z, v);
  32703. if (faceColors) {
  32704. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32705. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32706. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32707. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32708. }
  32709. }
  32710. if (cs !== s) {
  32711. cs = s;
  32712. }
  32713. }
  32714. }
  32715. // indices
  32716. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32717. var s;
  32718. i = 0;
  32719. for (s = 0; s < subdivisions; s++) {
  32720. var i0 = 0;
  32721. var i1 = 0;
  32722. var i2 = 0;
  32723. var i3 = 0;
  32724. for (j = 0; j < tessellation; j++) {
  32725. i0 = i * (e + 1) + j;
  32726. i1 = (i + 1) * (e + 1) + j;
  32727. i2 = i * (e + 1) + (j + 1);
  32728. i3 = (i + 1) * (e + 1) + (j + 1);
  32729. indices.push(i0, i1, i2);
  32730. indices.push(i3, i2, i1);
  32731. }
  32732. if (arc !== 1 && enclose) {
  32733. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32734. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32735. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32736. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32737. }
  32738. i = (hasRings) ? (i + 2) : (i + 1);
  32739. }
  32740. // Caps
  32741. var createCylinderCap = function (isTop) {
  32742. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32743. if (radius === 0) {
  32744. return;
  32745. }
  32746. // Cap positions, normals & uvs
  32747. var angle;
  32748. var circleVector;
  32749. var i;
  32750. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32751. var c = null;
  32752. if (faceColors) {
  32753. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32754. }
  32755. // cap center
  32756. var vbase = positions.length / 3;
  32757. var offset = isTop ? height / 2 : -height / 2;
  32758. var center = new BABYLON.Vector3(0, offset, 0);
  32759. positions.push(center.x, center.y, center.z);
  32760. normals.push(0, isTop ? 1 : -1, 0);
  32761. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32762. if (c) {
  32763. colors.push(c.r, c.g, c.b, c.a);
  32764. }
  32765. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32766. for (i = 0; i <= tessellation; i++) {
  32767. angle = Math.PI * 2 * i * arc / tessellation;
  32768. var cos = Math.cos(-angle);
  32769. var sin = Math.sin(-angle);
  32770. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32771. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32772. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32773. normals.push(0, isTop ? 1 : -1, 0);
  32774. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32775. if (c) {
  32776. colors.push(c.r, c.g, c.b, c.a);
  32777. }
  32778. }
  32779. // Cap indices
  32780. for (i = 0; i < tessellation; i++) {
  32781. if (!isTop) {
  32782. indices.push(vbase);
  32783. indices.push(vbase + (i + 1));
  32784. indices.push(vbase + (i + 2));
  32785. }
  32786. else {
  32787. indices.push(vbase);
  32788. indices.push(vbase + (i + 2));
  32789. indices.push(vbase + (i + 1));
  32790. }
  32791. }
  32792. };
  32793. // add caps to geometry
  32794. createCylinderCap(false);
  32795. createCylinderCap(true);
  32796. // Sides
  32797. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32798. var vertexData = new VertexData();
  32799. vertexData.indices = indices;
  32800. vertexData.positions = positions;
  32801. vertexData.normals = normals;
  32802. vertexData.uvs = uvs;
  32803. if (faceColors) {
  32804. vertexData.colors = colors;
  32805. }
  32806. return vertexData;
  32807. };
  32808. /**
  32809. * Creates the VertexData of the Torus.
  32810. */
  32811. VertexData.CreateTorus = function (options) {
  32812. var indices = [];
  32813. var positions = [];
  32814. var normals = [];
  32815. var uvs = [];
  32816. var diameter = options.diameter || 1;
  32817. var thickness = options.thickness || 0.5;
  32818. var tessellation = options.tessellation || 16;
  32819. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32820. var stride = tessellation + 1;
  32821. for (var i = 0; i <= tessellation; i++) {
  32822. var u = i / tessellation;
  32823. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32824. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32825. for (var j = 0; j <= tessellation; j++) {
  32826. var v = 1 - j / tessellation;
  32827. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32828. var dx = Math.cos(innerAngle);
  32829. var dy = Math.sin(innerAngle);
  32830. // Create a vertex.
  32831. var normal = new BABYLON.Vector3(dx, dy, 0);
  32832. var position = normal.scale(thickness / 2);
  32833. var textureCoordinate = new BABYLON.Vector2(u, v);
  32834. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32835. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32836. positions.push(position.x, position.y, position.z);
  32837. normals.push(normal.x, normal.y, normal.z);
  32838. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32839. // And create indices for two triangles.
  32840. var nextI = (i + 1) % stride;
  32841. var nextJ = (j + 1) % stride;
  32842. indices.push(i * stride + j);
  32843. indices.push(i * stride + nextJ);
  32844. indices.push(nextI * stride + j);
  32845. indices.push(i * stride + nextJ);
  32846. indices.push(nextI * stride + nextJ);
  32847. indices.push(nextI * stride + j);
  32848. }
  32849. }
  32850. // Sides
  32851. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32852. // Result
  32853. var vertexData = new VertexData();
  32854. vertexData.indices = indices;
  32855. vertexData.positions = positions;
  32856. vertexData.normals = normals;
  32857. vertexData.uvs = uvs;
  32858. return vertexData;
  32859. };
  32860. /**
  32861. * Creates the VertexData of the LineSystem.
  32862. */
  32863. VertexData.CreateLineSystem = function (options) {
  32864. var indices = [];
  32865. var positions = [];
  32866. var lines = options.lines;
  32867. var colors = options.colors;
  32868. var vertexColors = [];
  32869. var idx = 0;
  32870. for (var l = 0; l < lines.length; l++) {
  32871. var points = lines[l];
  32872. for (var index = 0; index < points.length; index++) {
  32873. positions.push(points[index].x, points[index].y, points[index].z);
  32874. if (colors) {
  32875. var color = colors[l];
  32876. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  32877. }
  32878. if (index > 0) {
  32879. indices.push(idx - 1);
  32880. indices.push(idx);
  32881. }
  32882. idx++;
  32883. }
  32884. }
  32885. var vertexData = new VertexData();
  32886. vertexData.indices = indices;
  32887. vertexData.positions = positions;
  32888. if (colors) {
  32889. vertexData.colors = vertexColors;
  32890. }
  32891. return vertexData;
  32892. };
  32893. /**
  32894. * Create the VertexData of the DashedLines.
  32895. */
  32896. VertexData.CreateDashedLines = function (options) {
  32897. var dashSize = options.dashSize || 3;
  32898. var gapSize = options.gapSize || 1;
  32899. var dashNb = options.dashNb || 200;
  32900. var points = options.points;
  32901. var positions = new Array();
  32902. var indices = new Array();
  32903. var curvect = BABYLON.Vector3.Zero();
  32904. var lg = 0;
  32905. var nb = 0;
  32906. var shft = 0;
  32907. var dashshft = 0;
  32908. var curshft = 0;
  32909. var idx = 0;
  32910. var i = 0;
  32911. for (i = 0; i < points.length - 1; i++) {
  32912. points[i + 1].subtractToRef(points[i], curvect);
  32913. lg += curvect.length();
  32914. }
  32915. shft = lg / dashNb;
  32916. dashshft = dashSize * shft / (dashSize + gapSize);
  32917. for (i = 0; i < points.length - 1; i++) {
  32918. points[i + 1].subtractToRef(points[i], curvect);
  32919. nb = Math.floor(curvect.length() / shft);
  32920. curvect.normalize();
  32921. for (var j = 0; j < nb; j++) {
  32922. curshft = shft * j;
  32923. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  32924. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  32925. indices.push(idx, idx + 1);
  32926. idx += 2;
  32927. }
  32928. }
  32929. // Result
  32930. var vertexData = new VertexData();
  32931. vertexData.positions = positions;
  32932. vertexData.indices = indices;
  32933. return vertexData;
  32934. };
  32935. /**
  32936. * Creates the VertexData of the Ground.
  32937. */
  32938. VertexData.CreateGround = function (options) {
  32939. var indices = [];
  32940. var positions = [];
  32941. var normals = [];
  32942. var uvs = [];
  32943. var row, col;
  32944. var width = options.width || 1;
  32945. var height = options.height || 1;
  32946. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  32947. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  32948. for (row = 0; row <= subdivisionsY; row++) {
  32949. for (col = 0; col <= subdivisionsX; col++) {
  32950. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  32951. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32952. positions.push(position.x, position.y, position.z);
  32953. normals.push(normal.x, normal.y, normal.z);
  32954. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  32955. }
  32956. }
  32957. for (row = 0; row < subdivisionsY; row++) {
  32958. for (col = 0; col < subdivisionsX; col++) {
  32959. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32960. indices.push(col + 1 + row * (subdivisionsX + 1));
  32961. indices.push(col + row * (subdivisionsX + 1));
  32962. indices.push(col + (row + 1) * (subdivisionsX + 1));
  32963. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32964. indices.push(col + row * (subdivisionsX + 1));
  32965. }
  32966. }
  32967. // Result
  32968. var vertexData = new VertexData();
  32969. vertexData.indices = indices;
  32970. vertexData.positions = positions;
  32971. vertexData.normals = normals;
  32972. vertexData.uvs = uvs;
  32973. return vertexData;
  32974. };
  32975. /**
  32976. * Creates the VertexData of the TiledGround.
  32977. */
  32978. VertexData.CreateTiledGround = function (options) {
  32979. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  32980. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  32981. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  32982. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  32983. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  32984. var precision = options.precision || { w: 1, h: 1 };
  32985. var indices = new Array();
  32986. var positions = new Array();
  32987. var normals = new Array();
  32988. var uvs = new Array();
  32989. var row, col, tileRow, tileCol;
  32990. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  32991. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  32992. precision.w = (precision.w < 1) ? 1 : precision.w;
  32993. precision.h = (precision.h < 1) ? 1 : precision.h;
  32994. var tileSize = {
  32995. 'w': (xmax - xmin) / subdivisions.w,
  32996. 'h': (zmax - zmin) / subdivisions.h
  32997. };
  32998. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  32999. // Indices
  33000. var base = positions.length / 3;
  33001. var rowLength = precision.w + 1;
  33002. for (row = 0; row < precision.h; row++) {
  33003. for (col = 0; col < precision.w; col++) {
  33004. var square = [
  33005. base + col + row * rowLength,
  33006. base + (col + 1) + row * rowLength,
  33007. base + (col + 1) + (row + 1) * rowLength,
  33008. base + col + (row + 1) * rowLength
  33009. ];
  33010. indices.push(square[1]);
  33011. indices.push(square[2]);
  33012. indices.push(square[3]);
  33013. indices.push(square[0]);
  33014. indices.push(square[1]);
  33015. indices.push(square[3]);
  33016. }
  33017. }
  33018. // Position, normals and uvs
  33019. var position = BABYLON.Vector3.Zero();
  33020. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33021. for (row = 0; row <= precision.h; row++) {
  33022. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33023. for (col = 0; col <= precision.w; col++) {
  33024. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33025. position.y = 0;
  33026. positions.push(position.x, position.y, position.z);
  33027. normals.push(normal.x, normal.y, normal.z);
  33028. uvs.push(col / precision.w, row / precision.h);
  33029. }
  33030. }
  33031. }
  33032. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33033. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33034. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33035. }
  33036. }
  33037. // Result
  33038. var vertexData = new VertexData();
  33039. vertexData.indices = indices;
  33040. vertexData.positions = positions;
  33041. vertexData.normals = normals;
  33042. vertexData.uvs = uvs;
  33043. return vertexData;
  33044. };
  33045. /**
  33046. * Creates the VertexData of the Ground designed from a heightmap.
  33047. */
  33048. VertexData.CreateGroundFromHeightMap = function (options) {
  33049. var indices = [];
  33050. var positions = [];
  33051. var normals = [];
  33052. var uvs = [];
  33053. var row, col;
  33054. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33055. // Vertices
  33056. for (row = 0; row <= options.subdivisions; row++) {
  33057. for (col = 0; col <= options.subdivisions; col++) {
  33058. 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));
  33059. // Compute height
  33060. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33061. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33062. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33063. var r = options.buffer[pos] / 255.0;
  33064. var g = options.buffer[pos + 1] / 255.0;
  33065. var b = options.buffer[pos + 2] / 255.0;
  33066. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33067. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33068. // Add vertex
  33069. positions.push(position.x, position.y, position.z);
  33070. normals.push(0, 0, 0);
  33071. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33072. }
  33073. }
  33074. // Indices
  33075. for (row = 0; row < options.subdivisions; row++) {
  33076. for (col = 0; col < options.subdivisions; col++) {
  33077. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33078. indices.push(col + 1 + row * (options.subdivisions + 1));
  33079. indices.push(col + row * (options.subdivisions + 1));
  33080. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33081. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33082. indices.push(col + row * (options.subdivisions + 1));
  33083. }
  33084. }
  33085. // Normals
  33086. VertexData.ComputeNormals(positions, indices, normals);
  33087. // Result
  33088. var vertexData = new VertexData();
  33089. vertexData.indices = indices;
  33090. vertexData.positions = positions;
  33091. vertexData.normals = normals;
  33092. vertexData.uvs = uvs;
  33093. return vertexData;
  33094. };
  33095. /**
  33096. * Creates the VertexData of the Plane.
  33097. */
  33098. VertexData.CreatePlane = function (options) {
  33099. var indices = [];
  33100. var positions = [];
  33101. var normals = [];
  33102. var uvs = [];
  33103. var width = options.width || options.size || 1;
  33104. var height = options.height || options.size || 1;
  33105. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33106. // Vertices
  33107. var halfWidth = width / 2.0;
  33108. var halfHeight = height / 2.0;
  33109. positions.push(-halfWidth, -halfHeight, 0);
  33110. normals.push(0, 0, -1.0);
  33111. uvs.push(0.0, 0.0);
  33112. positions.push(halfWidth, -halfHeight, 0);
  33113. normals.push(0, 0, -1.0);
  33114. uvs.push(1.0, 0.0);
  33115. positions.push(halfWidth, halfHeight, 0);
  33116. normals.push(0, 0, -1.0);
  33117. uvs.push(1.0, 1.0);
  33118. positions.push(-halfWidth, halfHeight, 0);
  33119. normals.push(0, 0, -1.0);
  33120. uvs.push(0.0, 1.0);
  33121. // Indices
  33122. indices.push(0);
  33123. indices.push(1);
  33124. indices.push(2);
  33125. indices.push(0);
  33126. indices.push(2);
  33127. indices.push(3);
  33128. // Sides
  33129. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33130. // Result
  33131. var vertexData = new VertexData();
  33132. vertexData.indices = indices;
  33133. vertexData.positions = positions;
  33134. vertexData.normals = normals;
  33135. vertexData.uvs = uvs;
  33136. return vertexData;
  33137. };
  33138. /**
  33139. * Creates the VertexData of the Disc or regular Polygon.
  33140. */
  33141. VertexData.CreateDisc = function (options) {
  33142. var positions = new Array();
  33143. var indices = new Array();
  33144. var normals = new Array();
  33145. var uvs = new Array();
  33146. var radius = options.radius || 0.5;
  33147. var tessellation = options.tessellation || 64;
  33148. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33149. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33150. // positions and uvs
  33151. positions.push(0, 0, 0); // disc center first
  33152. uvs.push(0.5, 0.5);
  33153. var theta = Math.PI * 2 * arc;
  33154. var step = theta / tessellation;
  33155. for (var a = 0; a < theta; a += step) {
  33156. var x = Math.cos(a);
  33157. var y = Math.sin(a);
  33158. var u = (x + 1) / 2;
  33159. var v = (1 - y) / 2;
  33160. positions.push(radius * x, radius * y, 0);
  33161. uvs.push(u, v);
  33162. }
  33163. if (arc === 1) {
  33164. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33165. uvs.push(uvs[2], uvs[3]);
  33166. }
  33167. //indices
  33168. var vertexNb = positions.length / 3;
  33169. for (var i = 1; i < vertexNb - 1; i++) {
  33170. indices.push(i + 1, 0, i);
  33171. }
  33172. // result
  33173. VertexData.ComputeNormals(positions, indices, normals);
  33174. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33175. var vertexData = new VertexData();
  33176. vertexData.indices = indices;
  33177. vertexData.positions = positions;
  33178. vertexData.normals = normals;
  33179. vertexData.uvs = uvs;
  33180. return vertexData;
  33181. };
  33182. /**
  33183. * Re-creates the VertexData of the Polygon for sideOrientation.
  33184. */
  33185. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33186. var faceUV = fUV || new Array(3);
  33187. var faceColors = fColors;
  33188. var colors = [];
  33189. // default face colors and UV if undefined
  33190. for (var f = 0; f < 3; f++) {
  33191. if (faceUV[f] === undefined) {
  33192. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33193. }
  33194. if (faceColors && faceColors[f] === undefined) {
  33195. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33196. }
  33197. }
  33198. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33199. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33200. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33201. var indices = polygon.getIndices();
  33202. // set face colours and textures
  33203. var idx = 0;
  33204. var face = 0;
  33205. for (var index = 0; index < normals.length; index += 3) {
  33206. //Edge Face no. 1
  33207. if (Math.abs(normals[index + 1]) < 0.001) {
  33208. face = 1;
  33209. }
  33210. //Top Face no. 0
  33211. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33212. face = 0;
  33213. }
  33214. //Bottom Face no. 2
  33215. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33216. face = 2;
  33217. }
  33218. idx = index / 3;
  33219. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33220. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33221. if (faceColors) {
  33222. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33223. }
  33224. }
  33225. // sides
  33226. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33227. // Result
  33228. var vertexData = new VertexData();
  33229. vertexData.indices = indices;
  33230. vertexData.positions = positions;
  33231. vertexData.normals = normals;
  33232. vertexData.uvs = uvs;
  33233. if (faceColors) {
  33234. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33235. vertexData.colors = totalColors;
  33236. }
  33237. return vertexData;
  33238. };
  33239. /**
  33240. * Creates the VertexData of the IcoSphere.
  33241. */
  33242. VertexData.CreateIcoSphere = function (options) {
  33243. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33244. var radius = options.radius || 1;
  33245. var flat = (options.flat === undefined) ? true : options.flat;
  33246. var subdivisions = options.subdivisions || 4;
  33247. var radiusX = options.radiusX || radius;
  33248. var radiusY = options.radiusY || radius;
  33249. var radiusZ = options.radiusZ || radius;
  33250. var t = (1 + Math.sqrt(5)) / 2;
  33251. // 12 vertex x,y,z
  33252. var ico_vertices = [
  33253. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33254. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33255. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33256. ];
  33257. // index of 3 vertex makes a face of icopshere
  33258. var ico_indices = [
  33259. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33260. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33261. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33262. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33263. ];
  33264. // vertex for uv have aliased position, not for UV
  33265. var vertices_unalias_id = [
  33266. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33267. // vertex alias
  33268. 0,
  33269. 2,
  33270. 3,
  33271. 3,
  33272. 3,
  33273. 4,
  33274. 7,
  33275. 8,
  33276. 9,
  33277. 9,
  33278. 10,
  33279. 11 // 23: B + 12
  33280. ];
  33281. // uv as integer step (not pixels !)
  33282. var ico_vertexuv = [
  33283. 5, 1, 3, 1, 6, 4, 0, 0,
  33284. 5, 3, 4, 2, 2, 2, 4, 0,
  33285. 2, 0, 1, 1, 6, 0, 6, 2,
  33286. // vertex alias (for same vertex on different faces)
  33287. 0, 4,
  33288. 3, 3,
  33289. 4, 4,
  33290. 3, 1,
  33291. 4, 2,
  33292. 4, 4,
  33293. 0, 2,
  33294. 1, 1,
  33295. 2, 2,
  33296. 3, 3,
  33297. 1, 3,
  33298. 2, 4 // 23: B + 12
  33299. ];
  33300. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33301. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33302. // First island of uv mapping
  33303. // v = 4h 3+ 2
  33304. // v = 3h 9+ 4
  33305. // v = 2h 9+ 5 B
  33306. // v = 1h 9 1 0
  33307. // v = 0h 3 8 7 A
  33308. // u = 0 1 2 3 4 5 6 *a
  33309. // Second island of uv mapping
  33310. // v = 4h 0+ B+ 4+
  33311. // v = 3h A+ 2+
  33312. // v = 2h 7+ 6 3+
  33313. // v = 1h 8+ 3+
  33314. // v = 0h
  33315. // u = 0 1 2 3 4 5 6 *a
  33316. // Face layout on texture UV mapping
  33317. // ============
  33318. // \ 4 /\ 16 / ======
  33319. // \ / \ / /\ 11 /
  33320. // \/ 7 \/ / \ /
  33321. // ======= / 10 \/
  33322. // /\ 17 /\ =======
  33323. // / \ / \ \ 15 /\
  33324. // / 8 \/ 12 \ \ / \
  33325. // ============ \/ 6 \
  33326. // \ 18 /\ ============
  33327. // \ / \ \ 5 /\ 0 /
  33328. // \/ 13 \ \ / \ /
  33329. // ======= \/ 1 \/
  33330. // =============
  33331. // /\ 19 /\ 2 /\
  33332. // / \ / \ / \
  33333. // / 14 \/ 9 \/ 3 \
  33334. // ===================
  33335. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33336. var ustep = 138 / 1024;
  33337. var vstep = 239 / 1024;
  33338. var uoffset = 60 / 1024;
  33339. var voffset = 26 / 1024;
  33340. // Second island should have margin, not to touch the first island
  33341. // avoid any borderline artefact in pixel rounding
  33342. var island_u_offset = -40 / 1024;
  33343. var island_v_offset = +20 / 1024;
  33344. // face is either island 0 or 1 :
  33345. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33346. var island = [
  33347. 0, 0, 0, 0, 1,
  33348. 0, 0, 1, 1, 0,
  33349. 0, 0, 1, 1, 0,
  33350. 0, 1, 1, 1, 0 // 15 - 19
  33351. ];
  33352. var indices = new Array();
  33353. var positions = new Array();
  33354. var normals = new Array();
  33355. var uvs = new Array();
  33356. var current_indice = 0;
  33357. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33358. var face_vertex_pos = new Array(3);
  33359. var face_vertex_uv = new Array(3);
  33360. var v012;
  33361. for (v012 = 0; v012 < 3; v012++) {
  33362. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33363. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33364. }
  33365. // create all with normals
  33366. for (var face = 0; face < 20; face++) {
  33367. // 3 vertex per face
  33368. for (v012 = 0; v012 < 3; v012++) {
  33369. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33370. var v_id = ico_indices[3 * face + v012];
  33371. // vertex have 3D position (x,y,z)
  33372. 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]);
  33373. // Normalize to get normal, then scale to radius
  33374. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33375. // uv Coordinates from vertex ID
  33376. 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);
  33377. }
  33378. // Subdivide the face (interpolate pos, norm, uv)
  33379. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33380. // - norm is linear interpolation of vertex corner normal
  33381. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33382. // - uv is linear interpolation
  33383. //
  33384. // Topology is as below for sub-divide by 2
  33385. // vertex shown as v0,v1,v2
  33386. // interp index is i1 to progress in range [v0,v1[
  33387. // interp index is i2 to progress in range [v0,v2[
  33388. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33389. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33390. //
  33391. //
  33392. // i2 v2
  33393. // ^ ^
  33394. // / / \
  33395. // / / \
  33396. // / / \
  33397. // / / (0,1) \
  33398. // / #---------\
  33399. // / / \ (0,0)'/ \
  33400. // / / \ / \
  33401. // / / \ / \
  33402. // / / (0,0) \ / (1,0) \
  33403. // / #---------#---------\
  33404. // v0 v1
  33405. //
  33406. // --------------------> i1
  33407. //
  33408. // interp of (i1,i2):
  33409. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33410. // along i1 : lerp(x0,x1, i1/(S-i2))
  33411. //
  33412. // centroid of triangle is needed to get help normal computation
  33413. // (c1,c2) are used for centroid location
  33414. var interp_vertex = function (i1, i2, c1, c2) {
  33415. // vertex is interpolated from
  33416. // - face_vertex_pos[0..2]
  33417. // - face_vertex_uv[0..2]
  33418. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33419. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33420. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33421. pos_interp.normalize();
  33422. var vertex_normal;
  33423. if (flat) {
  33424. // in flat mode, recalculate normal as face centroid normal
  33425. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33426. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33427. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33428. }
  33429. else {
  33430. // in smooth mode, recalculate normal from each single vertex position
  33431. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33432. }
  33433. // Vertex normal need correction due to X,Y,Z radius scaling
  33434. vertex_normal.x /= radiusX;
  33435. vertex_normal.y /= radiusY;
  33436. vertex_normal.z /= radiusZ;
  33437. vertex_normal.normalize();
  33438. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33439. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33440. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33441. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33442. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33443. uvs.push(uv_interp.x, uv_interp.y);
  33444. // push each vertex has member of a face
  33445. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33446. indices.push(current_indice);
  33447. current_indice++;
  33448. };
  33449. for (var i2 = 0; i2 < subdivisions; i2++) {
  33450. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33451. // face : (i1,i2) for /\ :
  33452. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33453. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33454. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33455. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33456. if (i1 + i2 + 1 < subdivisions) {
  33457. // face : (i1,i2)' for \/ :
  33458. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33459. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33460. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33461. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33462. }
  33463. }
  33464. }
  33465. }
  33466. // Sides
  33467. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33468. // Result
  33469. var vertexData = new VertexData();
  33470. vertexData.indices = indices;
  33471. vertexData.positions = positions;
  33472. vertexData.normals = normals;
  33473. vertexData.uvs = uvs;
  33474. return vertexData;
  33475. };
  33476. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33477. /**
  33478. * Creates the VertexData of the Polyhedron.
  33479. */
  33480. VertexData.CreatePolyhedron = function (options) {
  33481. // provided polyhedron types :
  33482. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33483. // 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)
  33484. var polyhedra = [];
  33485. 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]] };
  33486. 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]] };
  33487. polyhedra[2] = {
  33488. 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]],
  33489. 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]]
  33490. };
  33491. polyhedra[3] = {
  33492. 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]],
  33493. 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]]
  33494. };
  33495. polyhedra[4] = {
  33496. 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]],
  33497. 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]]
  33498. };
  33499. 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]] };
  33500. 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]] };
  33501. 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]] };
  33502. 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]] };
  33503. 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]] };
  33504. 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]] };
  33505. 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]] };
  33506. 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]] };
  33507. 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]] };
  33508. polyhedra[14] = {
  33509. 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]],
  33510. 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]]
  33511. };
  33512. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33513. var size = options.size;
  33514. var sizeX = options.sizeX || size || 1;
  33515. var sizeY = options.sizeY || size || 1;
  33516. var sizeZ = options.sizeZ || size || 1;
  33517. var data = options.custom || polyhedra[type];
  33518. var nbfaces = data.face.length;
  33519. var faceUV = options.faceUV || new Array(nbfaces);
  33520. var faceColors = options.faceColors;
  33521. var flat = (options.flat === undefined) ? true : options.flat;
  33522. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33523. var positions = new Array();
  33524. var indices = new Array();
  33525. var normals = new Array();
  33526. var uvs = new Array();
  33527. var colors = new Array();
  33528. var index = 0;
  33529. var faceIdx = 0; // face cursor in the array "indexes"
  33530. var indexes = new Array();
  33531. var i = 0;
  33532. var f = 0;
  33533. var u, v, ang, x, y, tmp;
  33534. // default face colors and UV if undefined
  33535. if (flat) {
  33536. for (f = 0; f < nbfaces; f++) {
  33537. if (faceColors && faceColors[f] === undefined) {
  33538. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33539. }
  33540. if (faceUV && faceUV[f] === undefined) {
  33541. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33542. }
  33543. }
  33544. }
  33545. if (!flat) {
  33546. for (i = 0; i < data.vertex.length; i++) {
  33547. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33548. uvs.push(0, 0);
  33549. }
  33550. for (f = 0; f < nbfaces; f++) {
  33551. for (i = 0; i < data.face[f].length - 2; i++) {
  33552. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33553. }
  33554. }
  33555. }
  33556. else {
  33557. for (f = 0; f < nbfaces; f++) {
  33558. var fl = data.face[f].length; // number of vertices of the current face
  33559. ang = 2 * Math.PI / fl;
  33560. x = 0.5 * Math.tan(ang / 2);
  33561. y = 0.5;
  33562. // positions, uvs, colors
  33563. for (i = 0; i < fl; i++) {
  33564. // positions
  33565. 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);
  33566. indexes.push(index);
  33567. index++;
  33568. // uvs
  33569. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33570. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33571. uvs.push(u, v);
  33572. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33573. y = x * Math.sin(ang) + y * Math.cos(ang);
  33574. x = tmp;
  33575. // colors
  33576. if (faceColors) {
  33577. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33578. }
  33579. }
  33580. // indices from indexes
  33581. for (i = 0; i < fl - 2; i++) {
  33582. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33583. }
  33584. faceIdx += fl;
  33585. }
  33586. }
  33587. VertexData.ComputeNormals(positions, indices, normals);
  33588. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33589. var vertexData = new VertexData();
  33590. vertexData.positions = positions;
  33591. vertexData.indices = indices;
  33592. vertexData.normals = normals;
  33593. vertexData.uvs = uvs;
  33594. if (faceColors && flat) {
  33595. vertexData.colors = colors;
  33596. }
  33597. return vertexData;
  33598. };
  33599. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33600. /**
  33601. * Creates the VertexData of the Torus Knot.
  33602. */
  33603. VertexData.CreateTorusKnot = function (options) {
  33604. var indices = new Array();
  33605. var positions = new Array();
  33606. var normals = new Array();
  33607. var uvs = new Array();
  33608. var radius = options.radius || 2;
  33609. var tube = options.tube || 0.5;
  33610. var radialSegments = options.radialSegments || 32;
  33611. var tubularSegments = options.tubularSegments || 32;
  33612. var p = options.p || 2;
  33613. var q = options.q || 3;
  33614. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33615. // Helper
  33616. var getPos = function (angle) {
  33617. var cu = Math.cos(angle);
  33618. var su = Math.sin(angle);
  33619. var quOverP = q / p * angle;
  33620. var cs = Math.cos(quOverP);
  33621. var tx = radius * (2 + cs) * 0.5 * cu;
  33622. var ty = radius * (2 + cs) * su * 0.5;
  33623. var tz = radius * Math.sin(quOverP) * 0.5;
  33624. return new BABYLON.Vector3(tx, ty, tz);
  33625. };
  33626. // Vertices
  33627. var i;
  33628. var j;
  33629. for (i = 0; i <= radialSegments; i++) {
  33630. var modI = i % radialSegments;
  33631. var u = modI / radialSegments * 2 * p * Math.PI;
  33632. var p1 = getPos(u);
  33633. var p2 = getPos(u + 0.01);
  33634. var tang = p2.subtract(p1);
  33635. var n = p2.add(p1);
  33636. var bitan = BABYLON.Vector3.Cross(tang, n);
  33637. n = BABYLON.Vector3.Cross(bitan, tang);
  33638. bitan.normalize();
  33639. n.normalize();
  33640. for (j = 0; j < tubularSegments; j++) {
  33641. var modJ = j % tubularSegments;
  33642. var v = modJ / tubularSegments * 2 * Math.PI;
  33643. var cx = -tube * Math.cos(v);
  33644. var cy = tube * Math.sin(v);
  33645. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33646. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33647. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33648. uvs.push(i / radialSegments);
  33649. uvs.push(j / tubularSegments);
  33650. }
  33651. }
  33652. for (i = 0; i < radialSegments; i++) {
  33653. for (j = 0; j < tubularSegments; j++) {
  33654. var jNext = (j + 1) % tubularSegments;
  33655. var a = i * tubularSegments + j;
  33656. var b = (i + 1) * tubularSegments + j;
  33657. var c = (i + 1) * tubularSegments + jNext;
  33658. var d = i * tubularSegments + jNext;
  33659. indices.push(d);
  33660. indices.push(b);
  33661. indices.push(a);
  33662. indices.push(d);
  33663. indices.push(c);
  33664. indices.push(b);
  33665. }
  33666. }
  33667. // Normals
  33668. VertexData.ComputeNormals(positions, indices, normals);
  33669. // Sides
  33670. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33671. // Result
  33672. var vertexData = new VertexData();
  33673. vertexData.indices = indices;
  33674. vertexData.positions = positions;
  33675. vertexData.normals = normals;
  33676. vertexData.uvs = uvs;
  33677. return vertexData;
  33678. };
  33679. // Tools
  33680. /**
  33681. * @param {any} - positions (number[] or Float32Array)
  33682. * @param {any} - indices (number[] or Uint16Array)
  33683. * @param {any} - normals (number[] or Float32Array)
  33684. * options (optional) :
  33685. * facetPositions : optional array of facet positions (vector3)
  33686. * facetNormals : optional array of facet normals (vector3)
  33687. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  33688. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  33689. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  33690. * bbSize : optional bounding box size data, required for facetPartitioning computation
  33691. * bInfo : optional bounding info, required for facetPartitioning computation
  33692. * useRightHandedSystem: optional boolean to for right handed system computation
  33693. * depthSort : optional boolean to enable the facet depth sort computation
  33694. * distanceTo : optional Vector3 to compute the facet depth from this location
  33695. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  33696. */
  33697. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  33698. // temporary scalar variables
  33699. var index = 0; // facet index
  33700. var p1p2x = 0.0; // p1p2 vector x coordinate
  33701. var p1p2y = 0.0; // p1p2 vector y coordinate
  33702. var p1p2z = 0.0; // p1p2 vector z coordinate
  33703. var p3p2x = 0.0; // p3p2 vector x coordinate
  33704. var p3p2y = 0.0; // p3p2 vector y coordinate
  33705. var p3p2z = 0.0; // p3p2 vector z coordinate
  33706. var faceNormalx = 0.0; // facet normal x coordinate
  33707. var faceNormaly = 0.0; // facet normal y coordinate
  33708. var faceNormalz = 0.0; // facet normal z coordinate
  33709. var length = 0.0; // facet normal length before normalization
  33710. var v1x = 0; // vector1 x index in the positions array
  33711. var v1y = 0; // vector1 y index in the positions array
  33712. var v1z = 0; // vector1 z index in the positions array
  33713. var v2x = 0; // vector2 x index in the positions array
  33714. var v2y = 0; // vector2 y index in the positions array
  33715. var v2z = 0; // vector2 z index in the positions array
  33716. var v3x = 0; // vector3 x index in the positions array
  33717. var v3y = 0; // vector3 y index in the positions array
  33718. var v3z = 0; // vector3 z index in the positions array
  33719. var computeFacetNormals = false;
  33720. var computeFacetPositions = false;
  33721. var computeFacetPartitioning = false;
  33722. var computeDepthSort = false;
  33723. var faceNormalSign = 1;
  33724. var ratio = 0;
  33725. var distanceTo = null;
  33726. if (options) {
  33727. computeFacetNormals = (options.facetNormals) ? true : false;
  33728. computeFacetPositions = (options.facetPositions) ? true : false;
  33729. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  33730. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  33731. ratio = options.ratio || 0;
  33732. computeDepthSort = (options.depthSort) ? true : false;
  33733. distanceTo = (options.distanceTo);
  33734. if (computeDepthSort) {
  33735. if (distanceTo === undefined) {
  33736. distanceTo = BABYLON.Vector3.Zero();
  33737. }
  33738. var depthSortedFacets = options.depthSortedFacets;
  33739. }
  33740. }
  33741. // facetPartitioning reinit if needed
  33742. var xSubRatio = 0;
  33743. var ySubRatio = 0;
  33744. var zSubRatio = 0;
  33745. var subSq = 0;
  33746. if (computeFacetPartitioning && options && options.bbSize) {
  33747. var ox = 0; // X partitioning index for facet position
  33748. var oy = 0; // Y partinioning index for facet position
  33749. var oz = 0; // Z partinioning index for facet position
  33750. var b1x = 0; // X partitioning index for facet v1 vertex
  33751. var b1y = 0; // Y partitioning index for facet v1 vertex
  33752. var b1z = 0; // z partitioning index for facet v1 vertex
  33753. var b2x = 0; // X partitioning index for facet v2 vertex
  33754. var b2y = 0; // Y partitioning index for facet v2 vertex
  33755. var b2z = 0; // Z partitioning index for facet v2 vertex
  33756. var b3x = 0; // X partitioning index for facet v3 vertex
  33757. var b3y = 0; // Y partitioning index for facet v3 vertex
  33758. var b3z = 0; // Z partitioning index for facet v3 vertex
  33759. var block_idx_o = 0; // facet barycenter block index
  33760. var block_idx_v1 = 0; // v1 vertex block index
  33761. var block_idx_v2 = 0; // v2 vertex block index
  33762. var block_idx_v3 = 0; // v3 vertex block index
  33763. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  33764. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  33765. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  33766. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  33767. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  33768. subSq = options.subDiv.max * options.subDiv.max;
  33769. options.facetPartitioning.length = 0;
  33770. }
  33771. // reset the normals
  33772. for (index = 0; index < positions.length; index++) {
  33773. normals[index] = 0.0;
  33774. }
  33775. // Loop : 1 indice triplet = 1 facet
  33776. var nbFaces = (indices.length / 3) | 0;
  33777. for (index = 0; index < nbFaces; index++) {
  33778. // get the indexes of the coordinates of each vertex of the facet
  33779. v1x = indices[index * 3] * 3;
  33780. v1y = v1x + 1;
  33781. v1z = v1x + 2;
  33782. v2x = indices[index * 3 + 1] * 3;
  33783. v2y = v2x + 1;
  33784. v2z = v2x + 2;
  33785. v3x = indices[index * 3 + 2] * 3;
  33786. v3y = v3x + 1;
  33787. v3z = v3x + 2;
  33788. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  33789. p1p2y = positions[v1y] - positions[v2y];
  33790. p1p2z = positions[v1z] - positions[v2z];
  33791. p3p2x = positions[v3x] - positions[v2x];
  33792. p3p2y = positions[v3y] - positions[v2y];
  33793. p3p2z = positions[v3z] - positions[v2z];
  33794. // compute the face normal with the cross product
  33795. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  33796. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  33797. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  33798. // normalize this normal and store it in the array facetData
  33799. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33800. length = (length === 0) ? 1.0 : length;
  33801. faceNormalx /= length;
  33802. faceNormaly /= length;
  33803. faceNormalz /= length;
  33804. if (computeFacetNormals && options) {
  33805. options.facetNormals[index].x = faceNormalx;
  33806. options.facetNormals[index].y = faceNormaly;
  33807. options.facetNormals[index].z = faceNormalz;
  33808. }
  33809. if (computeFacetPositions && options) {
  33810. // compute and the facet barycenter coordinates in the array facetPositions
  33811. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  33812. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  33813. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  33814. }
  33815. if (computeFacetPartitioning && options) {
  33816. // store the facet indexes in arrays in the main facetPartitioning array :
  33817. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  33818. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  33819. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  33820. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  33821. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33822. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33823. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33824. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33825. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33826. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33827. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33828. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33829. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33830. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  33831. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  33832. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  33833. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  33834. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  33835. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  33836. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  33837. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  33838. // push each facet index in each block containing the vertex
  33839. options.facetPartitioning[block_idx_v1].push(index);
  33840. if (block_idx_v2 != block_idx_v1) {
  33841. options.facetPartitioning[block_idx_v2].push(index);
  33842. }
  33843. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  33844. options.facetPartitioning[block_idx_v3].push(index);
  33845. }
  33846. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  33847. options.facetPartitioning[block_idx_o].push(index);
  33848. }
  33849. }
  33850. if (computeDepthSort && options && options.facetPositions) {
  33851. var dsf = depthSortedFacets[index];
  33852. dsf.ind = index * 3;
  33853. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  33854. }
  33855. // compute the normals anyway
  33856. normals[v1x] += faceNormalx; // accumulate all the normals per face
  33857. normals[v1y] += faceNormaly;
  33858. normals[v1z] += faceNormalz;
  33859. normals[v2x] += faceNormalx;
  33860. normals[v2y] += faceNormaly;
  33861. normals[v2z] += faceNormalz;
  33862. normals[v3x] += faceNormalx;
  33863. normals[v3y] += faceNormaly;
  33864. normals[v3z] += faceNormalz;
  33865. }
  33866. // last normalization of each normal
  33867. for (index = 0; index < normals.length / 3; index++) {
  33868. faceNormalx = normals[index * 3];
  33869. faceNormaly = normals[index * 3 + 1];
  33870. faceNormalz = normals[index * 3 + 2];
  33871. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33872. length = (length === 0) ? 1.0 : length;
  33873. faceNormalx /= length;
  33874. faceNormaly /= length;
  33875. faceNormalz /= length;
  33876. normals[index * 3] = faceNormalx;
  33877. normals[index * 3 + 1] = faceNormaly;
  33878. normals[index * 3 + 2] = faceNormalz;
  33879. }
  33880. };
  33881. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  33882. var li = indices.length;
  33883. var ln = normals.length;
  33884. var i;
  33885. var n;
  33886. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33887. switch (sideOrientation) {
  33888. case BABYLON.Mesh.FRONTSIDE:
  33889. // nothing changed
  33890. break;
  33891. case BABYLON.Mesh.BACKSIDE:
  33892. var tmp;
  33893. // indices
  33894. for (i = 0; i < li; i += 3) {
  33895. tmp = indices[i];
  33896. indices[i] = indices[i + 2];
  33897. indices[i + 2] = tmp;
  33898. }
  33899. // normals
  33900. for (n = 0; n < ln; n++) {
  33901. normals[n] = -normals[n];
  33902. }
  33903. break;
  33904. case BABYLON.Mesh.DOUBLESIDE:
  33905. // positions
  33906. var lp = positions.length;
  33907. var l = lp / 3;
  33908. for (var p = 0; p < lp; p++) {
  33909. positions[lp + p] = positions[p];
  33910. }
  33911. // indices
  33912. for (i = 0; i < li; i += 3) {
  33913. indices[i + li] = indices[i + 2] + l;
  33914. indices[i + 1 + li] = indices[i + 1] + l;
  33915. indices[i + 2 + li] = indices[i] + l;
  33916. }
  33917. // normals
  33918. for (n = 0; n < ln; n++) {
  33919. normals[ln + n] = -normals[n];
  33920. }
  33921. // uvs
  33922. var lu = uvs.length;
  33923. var u = 0;
  33924. for (u = 0; u < lu; u++) {
  33925. uvs[u + lu] = uvs[u];
  33926. }
  33927. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33928. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33929. u = 0;
  33930. for (i = 0; i < lu / 2; i++) {
  33931. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  33932. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  33933. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  33934. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  33935. u += 2;
  33936. }
  33937. break;
  33938. }
  33939. };
  33940. /**
  33941. * Creates a new VertexData from the imported parameters.
  33942. */
  33943. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  33944. var vertexData = new VertexData();
  33945. // positions
  33946. var positions = parsedVertexData.positions;
  33947. if (positions) {
  33948. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  33949. }
  33950. // normals
  33951. var normals = parsedVertexData.normals;
  33952. if (normals) {
  33953. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  33954. }
  33955. // tangents
  33956. var tangents = parsedVertexData.tangents;
  33957. if (tangents) {
  33958. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  33959. }
  33960. // uvs
  33961. var uvs = parsedVertexData.uvs;
  33962. if (uvs) {
  33963. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  33964. }
  33965. // uv2s
  33966. var uv2s = parsedVertexData.uv2s;
  33967. if (uv2s) {
  33968. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  33969. }
  33970. // uv3s
  33971. var uv3s = parsedVertexData.uv3s;
  33972. if (uv3s) {
  33973. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  33974. }
  33975. // uv4s
  33976. var uv4s = parsedVertexData.uv4s;
  33977. if (uv4s) {
  33978. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  33979. }
  33980. // uv5s
  33981. var uv5s = parsedVertexData.uv5s;
  33982. if (uv5s) {
  33983. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  33984. }
  33985. // uv6s
  33986. var uv6s = parsedVertexData.uv6s;
  33987. if (uv6s) {
  33988. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  33989. }
  33990. // colors
  33991. var colors = parsedVertexData.colors;
  33992. if (colors) {
  33993. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  33994. }
  33995. // matricesIndices
  33996. var matricesIndices = parsedVertexData.matricesIndices;
  33997. if (matricesIndices) {
  33998. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  33999. }
  34000. // matricesWeights
  34001. var matricesWeights = parsedVertexData.matricesWeights;
  34002. if (matricesWeights) {
  34003. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34004. }
  34005. // indices
  34006. var indices = parsedVertexData.indices;
  34007. if (indices) {
  34008. vertexData.indices = indices;
  34009. }
  34010. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34011. };
  34012. return VertexData;
  34013. }());
  34014. BABYLON.VertexData = VertexData;
  34015. })(BABYLON || (BABYLON = {}));
  34016. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34017. var BABYLON;
  34018. (function (BABYLON) {
  34019. /**
  34020. * Class used to store geometry data (vertex buffers + index buffer)
  34021. */
  34022. var Geometry = /** @class */ (function () {
  34023. /**
  34024. * Creates a new geometry
  34025. * @param id defines the unique ID
  34026. * @param scene defines the hosting scene
  34027. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34028. * @param updatable defines if geometry must be updatable (false by default)
  34029. * @param mesh defines the mesh that will be associated with the geometry
  34030. */
  34031. function Geometry(id, scene, vertexData, updatable, mesh) {
  34032. if (updatable === void 0) { updatable = false; }
  34033. if (mesh === void 0) { mesh = null; }
  34034. /**
  34035. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34036. */
  34037. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34038. this._totalVertices = 0;
  34039. this._isDisposed = false;
  34040. this._indexBufferIsUpdatable = false;
  34041. this.id = id;
  34042. this._engine = scene.getEngine();
  34043. this._meshes = [];
  34044. this._scene = scene;
  34045. //Init vertex buffer cache
  34046. this._vertexBuffers = {};
  34047. this._indices = [];
  34048. this._updatable = updatable;
  34049. // vertexData
  34050. if (vertexData) {
  34051. this.setAllVerticesData(vertexData, updatable);
  34052. }
  34053. else {
  34054. this._totalVertices = 0;
  34055. this._indices = [];
  34056. }
  34057. if (this._engine.getCaps().vertexArrayObject) {
  34058. this._vertexArrayObjects = {};
  34059. }
  34060. // applyToMesh
  34061. if (mesh) {
  34062. if (mesh.getClassName() === "LinesMesh") {
  34063. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34064. this.updateExtend();
  34065. }
  34066. this.applyToMesh(mesh);
  34067. mesh.computeWorldMatrix(true);
  34068. }
  34069. }
  34070. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34071. /**
  34072. * 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
  34073. */
  34074. get: function () {
  34075. return this._boundingBias;
  34076. },
  34077. /**
  34078. * 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
  34079. */
  34080. set: function (value) {
  34081. if (this._boundingBias && this._boundingBias.equals(value)) {
  34082. return;
  34083. }
  34084. this._boundingBias = value.clone();
  34085. this.updateBoundingInfo(true, null);
  34086. },
  34087. enumerable: true,
  34088. configurable: true
  34089. });
  34090. /**
  34091. * Static function used to attach a new empty geometry to a mesh
  34092. * @param mesh defines the mesh to attach the geometry to
  34093. * @returns the new {BABYLON.Geometry}
  34094. */
  34095. Geometry.CreateGeometryForMesh = function (mesh) {
  34096. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34097. geometry.applyToMesh(mesh);
  34098. return geometry;
  34099. };
  34100. Object.defineProperty(Geometry.prototype, "extend", {
  34101. /**
  34102. * Gets the current extend of the geometry
  34103. */
  34104. get: function () {
  34105. return this._extend;
  34106. },
  34107. enumerable: true,
  34108. configurable: true
  34109. });
  34110. /**
  34111. * Gets the hosting scene
  34112. * @returns the hosting {BABYLON.Scene}
  34113. */
  34114. Geometry.prototype.getScene = function () {
  34115. return this._scene;
  34116. };
  34117. /**
  34118. * Gets the hosting engine
  34119. * @returns the hosting {BABYLON.Engine}
  34120. */
  34121. Geometry.prototype.getEngine = function () {
  34122. return this._engine;
  34123. };
  34124. /**
  34125. * Defines if the geometry is ready to use
  34126. * @returns true if the geometry is ready to be used
  34127. */
  34128. Geometry.prototype.isReady = function () {
  34129. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34130. };
  34131. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34132. /**
  34133. * Gets a value indicating that the geometry should not be serialized
  34134. */
  34135. get: function () {
  34136. for (var index = 0; index < this._meshes.length; index++) {
  34137. if (!this._meshes[index].doNotSerialize) {
  34138. return false;
  34139. }
  34140. }
  34141. return true;
  34142. },
  34143. enumerable: true,
  34144. configurable: true
  34145. });
  34146. /** @ignore */
  34147. Geometry.prototype._rebuild = function () {
  34148. if (this._vertexArrayObjects) {
  34149. this._vertexArrayObjects = {};
  34150. }
  34151. // Index buffer
  34152. if (this._meshes.length !== 0 && this._indices) {
  34153. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34154. }
  34155. // Vertex buffers
  34156. for (var key in this._vertexBuffers) {
  34157. var vertexBuffer = this._vertexBuffers[key];
  34158. vertexBuffer._rebuild();
  34159. }
  34160. };
  34161. /**
  34162. * Affects all gemetry data in one call
  34163. * @param vertexData defines the geometry data
  34164. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34165. */
  34166. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34167. vertexData.applyToGeometry(this, updatable);
  34168. this.notifyUpdate();
  34169. };
  34170. /**
  34171. * Set specific vertex data
  34172. * @param kind defines the data kind (Position, normal, etc...)
  34173. * @param data defines the vertex data to use
  34174. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34175. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34176. */
  34177. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34178. if (updatable === void 0) { updatable = false; }
  34179. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34180. this.setVerticesBuffer(buffer);
  34181. };
  34182. /**
  34183. * Removes a specific vertex data
  34184. * @param kind defines the data kind (Position, normal, etc...)
  34185. */
  34186. Geometry.prototype.removeVerticesData = function (kind) {
  34187. if (this._vertexBuffers[kind]) {
  34188. this._vertexBuffers[kind].dispose();
  34189. delete this._vertexBuffers[kind];
  34190. }
  34191. };
  34192. /**
  34193. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34194. * @param buffer defines the vertex buffer to use
  34195. */
  34196. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34197. var kind = buffer.getKind();
  34198. if (this._vertexBuffers[kind]) {
  34199. this._vertexBuffers[kind].dispose();
  34200. }
  34201. this._vertexBuffers[kind] = buffer;
  34202. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34203. var data = buffer.getData();
  34204. var stride = buffer.getStrideSize();
  34205. this._totalVertices = data.length / stride;
  34206. this.updateExtend(data, stride);
  34207. this._resetPointsArrayCache();
  34208. var meshes = this._meshes;
  34209. var numOfMeshes = meshes.length;
  34210. for (var index = 0; index < numOfMeshes; index++) {
  34211. var mesh = meshes[index];
  34212. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34213. mesh._createGlobalSubMesh(false);
  34214. mesh.computeWorldMatrix(true);
  34215. }
  34216. }
  34217. this.notifyUpdate(kind);
  34218. if (this._vertexArrayObjects) {
  34219. this._disposeVertexArrayObjects();
  34220. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34221. }
  34222. };
  34223. /**
  34224. * Update a specific vertex buffer
  34225. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34226. * It will do nothing if the buffer is not updatable
  34227. * @param kind defines the data kind (Position, normal, etc...)
  34228. * @param data defines the data to use
  34229. * @param offset defines the offset in the target buffer where to store the data
  34230. */
  34231. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34232. var vertexBuffer = this.getVertexBuffer(kind);
  34233. if (!vertexBuffer) {
  34234. return;
  34235. }
  34236. vertexBuffer.updateDirectly(data, offset);
  34237. this.notifyUpdate(kind);
  34238. };
  34239. /**
  34240. * Update a specific vertex buffer
  34241. * This function will create a new buffer if the current one is not updatable
  34242. * @param kind defines the data kind (Position, normal, etc...)
  34243. * @param data defines the data to use
  34244. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34245. */
  34246. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34247. if (updateExtends === void 0) { updateExtends = false; }
  34248. var vertexBuffer = this.getVertexBuffer(kind);
  34249. if (!vertexBuffer) {
  34250. return;
  34251. }
  34252. vertexBuffer.update(data);
  34253. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34254. var stride = vertexBuffer.getStrideSize();
  34255. this._totalVertices = data.length / stride;
  34256. this.updateBoundingInfo(updateExtends, data);
  34257. }
  34258. this.notifyUpdate(kind);
  34259. };
  34260. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34261. if (updateExtends) {
  34262. this.updateExtend(data);
  34263. }
  34264. var meshes = this._meshes;
  34265. var numOfMeshes = meshes.length;
  34266. this._resetPointsArrayCache();
  34267. for (var index = 0; index < numOfMeshes; index++) {
  34268. var mesh = meshes[index];
  34269. if (updateExtends) {
  34270. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34271. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34272. var subMesh = mesh.subMeshes[subIndex];
  34273. subMesh.refreshBoundingInfo();
  34274. }
  34275. }
  34276. }
  34277. };
  34278. /** @ignore */
  34279. Geometry.prototype._bind = function (effect, indexToBind) {
  34280. if (!effect) {
  34281. return;
  34282. }
  34283. if (indexToBind === undefined) {
  34284. indexToBind = this._indexBuffer;
  34285. }
  34286. var vbs = this.getVertexBuffers();
  34287. if (!vbs) {
  34288. return;
  34289. }
  34290. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34291. this._engine.bindBuffers(vbs, indexToBind, effect);
  34292. return;
  34293. }
  34294. // Using VAO
  34295. if (!this._vertexArrayObjects[effect.key]) {
  34296. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34297. }
  34298. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34299. };
  34300. /**
  34301. * Gets total number of vertices
  34302. * @returns the total number of vertices
  34303. */
  34304. Geometry.prototype.getTotalVertices = function () {
  34305. if (!this.isReady()) {
  34306. return 0;
  34307. }
  34308. return this._totalVertices;
  34309. };
  34310. /**
  34311. * Gets a specific vertex data attached to this geometry
  34312. * @param kind defines the data kind (Position, normal, etc...)
  34313. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34314. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34315. * @returns a float array containing vertex data
  34316. */
  34317. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34318. var vertexBuffer = this.getVertexBuffer(kind);
  34319. if (!vertexBuffer) {
  34320. return null;
  34321. }
  34322. var orig = vertexBuffer.getData();
  34323. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34324. return orig;
  34325. }
  34326. else {
  34327. var len = orig.length;
  34328. var copy = [];
  34329. for (var i = 0; i < len; i++) {
  34330. copy.push(orig[i]);
  34331. }
  34332. return copy;
  34333. }
  34334. };
  34335. /**
  34336. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34337. * @param kind defines the data kind (Position, normal, etc...)
  34338. * @returns true if the vertex buffer with the specified kind is updatable
  34339. */
  34340. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34341. var vb = this._vertexBuffers[kind];
  34342. if (!vb) {
  34343. return false;
  34344. }
  34345. return vb.isUpdatable();
  34346. };
  34347. /**
  34348. * Gets a specific vertex buffer
  34349. * @param kind defines the data kind (Position, normal, etc...)
  34350. * @returns a {BABYLON.VertexBuffer}
  34351. */
  34352. Geometry.prototype.getVertexBuffer = function (kind) {
  34353. if (!this.isReady()) {
  34354. return null;
  34355. }
  34356. return this._vertexBuffers[kind];
  34357. };
  34358. /**
  34359. * Returns all vertex buffers
  34360. * @return an object holding all vertex buffers indexed by kind
  34361. */
  34362. Geometry.prototype.getVertexBuffers = function () {
  34363. if (!this.isReady()) {
  34364. return null;
  34365. }
  34366. return this._vertexBuffers;
  34367. };
  34368. /**
  34369. * Gets a boolean indicating if specific vertex buffer is present
  34370. * @param kind defines the data kind (Position, normal, etc...)
  34371. * @returns true if data is present
  34372. */
  34373. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34374. if (!this._vertexBuffers) {
  34375. if (this._delayInfo) {
  34376. return this._delayInfo.indexOf(kind) !== -1;
  34377. }
  34378. return false;
  34379. }
  34380. return this._vertexBuffers[kind] !== undefined;
  34381. };
  34382. /**
  34383. * Gets a list of all attached data kinds (Position, normal, etc...)
  34384. * @returns a list of string containing all kinds
  34385. */
  34386. Geometry.prototype.getVerticesDataKinds = function () {
  34387. var result = [];
  34388. var kind;
  34389. if (!this._vertexBuffers && this._delayInfo) {
  34390. for (kind in this._delayInfo) {
  34391. result.push(kind);
  34392. }
  34393. }
  34394. else {
  34395. for (kind in this._vertexBuffers) {
  34396. result.push(kind);
  34397. }
  34398. }
  34399. return result;
  34400. };
  34401. /**
  34402. * Update index buffer
  34403. * @param indices defines the indices to store in the index buffer
  34404. * @param offset defines the offset in the target buffer where to store the data
  34405. */
  34406. Geometry.prototype.updateIndices = function (indices, offset) {
  34407. if (!this._indexBuffer) {
  34408. return;
  34409. }
  34410. if (!this._indexBufferIsUpdatable) {
  34411. this.setIndices(indices, null, true);
  34412. }
  34413. else {
  34414. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34415. }
  34416. };
  34417. /**
  34418. * Creates a new index buffer
  34419. * @param indices defines the indices to store in the index buffer
  34420. * @param totalVertices defines the total number of vertices (could be null)
  34421. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34422. */
  34423. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34424. if (totalVertices === void 0) { totalVertices = null; }
  34425. if (updatable === void 0) { updatable = false; }
  34426. if (this._indexBuffer) {
  34427. this._engine._releaseBuffer(this._indexBuffer);
  34428. }
  34429. this._disposeVertexArrayObjects();
  34430. this._indices = indices;
  34431. this._indexBufferIsUpdatable = updatable;
  34432. if (this._meshes.length !== 0 && this._indices) {
  34433. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34434. }
  34435. if (totalVertices != undefined) {
  34436. this._totalVertices = totalVertices;
  34437. }
  34438. var meshes = this._meshes;
  34439. var numOfMeshes = meshes.length;
  34440. for (var index = 0; index < numOfMeshes; index++) {
  34441. meshes[index]._createGlobalSubMesh(true);
  34442. }
  34443. this.notifyUpdate();
  34444. };
  34445. /**
  34446. * Return the total number of indices
  34447. * @returns the total number of indices
  34448. */
  34449. Geometry.prototype.getTotalIndices = function () {
  34450. if (!this.isReady()) {
  34451. return 0;
  34452. }
  34453. return this._indices.length;
  34454. };
  34455. /**
  34456. * Gets the index buffer array
  34457. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34458. * @returns the index buffer array
  34459. */
  34460. Geometry.prototype.getIndices = function (copyWhenShared) {
  34461. if (!this.isReady()) {
  34462. return null;
  34463. }
  34464. var orig = this._indices;
  34465. if (!copyWhenShared || this._meshes.length === 1) {
  34466. return orig;
  34467. }
  34468. else {
  34469. var len = orig.length;
  34470. var copy = [];
  34471. for (var i = 0; i < len; i++) {
  34472. copy.push(orig[i]);
  34473. }
  34474. return copy;
  34475. }
  34476. };
  34477. /**
  34478. * Gets the index buffer
  34479. * @return the index buffer
  34480. */
  34481. Geometry.prototype.getIndexBuffer = function () {
  34482. if (!this.isReady()) {
  34483. return null;
  34484. }
  34485. return this._indexBuffer;
  34486. };
  34487. /** @ignore */
  34488. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34489. if (effect === void 0) { effect = null; }
  34490. if (!effect || !this._vertexArrayObjects) {
  34491. return;
  34492. }
  34493. if (this._vertexArrayObjects[effect.key]) {
  34494. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34495. delete this._vertexArrayObjects[effect.key];
  34496. }
  34497. };
  34498. /**
  34499. * Release the associated resources for a specific mesh
  34500. * @param mesh defines the source mesh
  34501. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34502. */
  34503. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34504. var meshes = this._meshes;
  34505. var index = meshes.indexOf(mesh);
  34506. if (index === -1) {
  34507. return;
  34508. }
  34509. meshes.splice(index, 1);
  34510. mesh._geometry = null;
  34511. if (meshes.length === 0 && shouldDispose) {
  34512. this.dispose();
  34513. }
  34514. };
  34515. /**
  34516. * Apply current geometry to a given mesh
  34517. * @param mesh defines the mesh to apply geometry to
  34518. */
  34519. Geometry.prototype.applyToMesh = function (mesh) {
  34520. if (mesh._geometry === this) {
  34521. return;
  34522. }
  34523. var previousGeometry = mesh._geometry;
  34524. if (previousGeometry) {
  34525. previousGeometry.releaseForMesh(mesh);
  34526. }
  34527. var meshes = this._meshes;
  34528. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34529. mesh._geometry = this;
  34530. this._scene.pushGeometry(this);
  34531. meshes.push(mesh);
  34532. if (this.isReady()) {
  34533. this._applyToMesh(mesh);
  34534. }
  34535. else {
  34536. mesh._boundingInfo = this._boundingInfo;
  34537. }
  34538. };
  34539. Geometry.prototype.updateExtend = function (data, stride) {
  34540. if (data === void 0) { data = null; }
  34541. if (!data) {
  34542. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34543. }
  34544. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34545. };
  34546. Geometry.prototype._applyToMesh = function (mesh) {
  34547. var numOfMeshes = this._meshes.length;
  34548. // vertexBuffers
  34549. for (var kind in this._vertexBuffers) {
  34550. if (numOfMeshes === 1) {
  34551. this._vertexBuffers[kind].create();
  34552. }
  34553. var buffer = this._vertexBuffers[kind].getBuffer();
  34554. if (buffer)
  34555. buffer.references = numOfMeshes;
  34556. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34557. if (!this._extend) {
  34558. this.updateExtend(this._vertexBuffers[kind].getData());
  34559. }
  34560. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34561. mesh._createGlobalSubMesh(false);
  34562. //bounding info was just created again, world matrix should be applied again.
  34563. mesh._updateBoundingInfo();
  34564. }
  34565. }
  34566. // indexBuffer
  34567. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34568. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34569. }
  34570. if (this._indexBuffer) {
  34571. this._indexBuffer.references = numOfMeshes;
  34572. }
  34573. };
  34574. Geometry.prototype.notifyUpdate = function (kind) {
  34575. if (this.onGeometryUpdated) {
  34576. this.onGeometryUpdated(this, kind);
  34577. }
  34578. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  34579. var mesh = _a[_i];
  34580. mesh._markSubMeshesAsAttributesDirty();
  34581. }
  34582. };
  34583. /**
  34584. * Load the geometry if it was flagged as delay loaded
  34585. * @param scene defines the hosting scene
  34586. * @param onLoaded defines a callback called when the geometry is loaded
  34587. */
  34588. Geometry.prototype.load = function (scene, onLoaded) {
  34589. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34590. return;
  34591. }
  34592. if (this.isReady()) {
  34593. if (onLoaded) {
  34594. onLoaded();
  34595. }
  34596. return;
  34597. }
  34598. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34599. this._queueLoad(scene, onLoaded);
  34600. };
  34601. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34602. var _this = this;
  34603. if (!this.delayLoadingFile) {
  34604. return;
  34605. }
  34606. scene._addPendingData(this);
  34607. scene._loadFile(this.delayLoadingFile, function (data) {
  34608. if (!_this._delayLoadingFunction) {
  34609. return;
  34610. }
  34611. _this._delayLoadingFunction(JSON.parse(data), _this);
  34612. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34613. _this._delayInfo = [];
  34614. scene._removePendingData(_this);
  34615. var meshes = _this._meshes;
  34616. var numOfMeshes = meshes.length;
  34617. for (var index = 0; index < numOfMeshes; index++) {
  34618. _this._applyToMesh(meshes[index]);
  34619. }
  34620. if (onLoaded) {
  34621. onLoaded();
  34622. }
  34623. }, undefined, true);
  34624. };
  34625. /**
  34626. * Invert the geometry to move from a right handed system to a left handed one.
  34627. */
  34628. Geometry.prototype.toLeftHanded = function () {
  34629. // Flip faces
  34630. var tIndices = this.getIndices(false);
  34631. if (tIndices != null && tIndices.length > 0) {
  34632. for (var i = 0; i < tIndices.length; i += 3) {
  34633. var tTemp = tIndices[i + 0];
  34634. tIndices[i + 0] = tIndices[i + 2];
  34635. tIndices[i + 2] = tTemp;
  34636. }
  34637. this.setIndices(tIndices);
  34638. }
  34639. // Negate position.z
  34640. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34641. if (tPositions != null && tPositions.length > 0) {
  34642. for (var i = 0; i < tPositions.length; i += 3) {
  34643. tPositions[i + 2] = -tPositions[i + 2];
  34644. }
  34645. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34646. }
  34647. // Negate normal.z
  34648. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34649. if (tNormals != null && tNormals.length > 0) {
  34650. for (var i = 0; i < tNormals.length; i += 3) {
  34651. tNormals[i + 2] = -tNormals[i + 2];
  34652. }
  34653. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34654. }
  34655. };
  34656. // Cache
  34657. /** @ignore */
  34658. Geometry.prototype._resetPointsArrayCache = function () {
  34659. this._positions = null;
  34660. };
  34661. /** @ignore */
  34662. Geometry.prototype._generatePointsArray = function () {
  34663. if (this._positions)
  34664. return true;
  34665. this._positions = [];
  34666. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34667. if (!data) {
  34668. return false;
  34669. }
  34670. for (var index = 0; index < data.length; index += 3) {
  34671. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  34672. }
  34673. return true;
  34674. };
  34675. /**
  34676. * Gets a value indicating if the geometry is disposed
  34677. * @returns true if the geometry was disposed
  34678. */
  34679. Geometry.prototype.isDisposed = function () {
  34680. return this._isDisposed;
  34681. };
  34682. Geometry.prototype._disposeVertexArrayObjects = function () {
  34683. if (this._vertexArrayObjects) {
  34684. for (var kind in this._vertexArrayObjects) {
  34685. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  34686. }
  34687. this._vertexArrayObjects = {};
  34688. }
  34689. };
  34690. /**
  34691. * Free all associated resources
  34692. */
  34693. Geometry.prototype.dispose = function () {
  34694. var meshes = this._meshes;
  34695. var numOfMeshes = meshes.length;
  34696. var index;
  34697. for (index = 0; index < numOfMeshes; index++) {
  34698. this.releaseForMesh(meshes[index]);
  34699. }
  34700. this._meshes = [];
  34701. this._disposeVertexArrayObjects();
  34702. for (var kind in this._vertexBuffers) {
  34703. this._vertexBuffers[kind].dispose();
  34704. }
  34705. this._vertexBuffers = {};
  34706. this._totalVertices = 0;
  34707. if (this._indexBuffer) {
  34708. this._engine._releaseBuffer(this._indexBuffer);
  34709. }
  34710. this._indexBuffer = null;
  34711. this._indices = [];
  34712. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34713. this.delayLoadingFile = null;
  34714. this._delayLoadingFunction = null;
  34715. this._delayInfo = [];
  34716. this._boundingInfo = null;
  34717. this._scene.removeGeometry(this);
  34718. this._isDisposed = true;
  34719. };
  34720. /**
  34721. * Clone the current geometry into a new geometry
  34722. * @param id defines the unique ID of the new geometry
  34723. * @returns a new geometry object
  34724. */
  34725. Geometry.prototype.copy = function (id) {
  34726. var vertexData = new BABYLON.VertexData();
  34727. vertexData.indices = [];
  34728. var indices = this.getIndices();
  34729. if (indices) {
  34730. for (var index = 0; index < indices.length; index++) {
  34731. vertexData.indices.push(indices[index]);
  34732. }
  34733. }
  34734. var updatable = false;
  34735. var stopChecking = false;
  34736. var kind;
  34737. for (kind in this._vertexBuffers) {
  34738. // using slice() to make a copy of the array and not just reference it
  34739. var data = this.getVerticesData(kind);
  34740. if (data instanceof Float32Array) {
  34741. vertexData.set(new Float32Array(data), kind);
  34742. }
  34743. else {
  34744. vertexData.set(data.slice(0), kind);
  34745. }
  34746. if (!stopChecking) {
  34747. var vb = this.getVertexBuffer(kind);
  34748. if (vb) {
  34749. updatable = vb.isUpdatable();
  34750. stopChecking = !updatable;
  34751. }
  34752. }
  34753. }
  34754. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  34755. geometry.delayLoadState = this.delayLoadState;
  34756. geometry.delayLoadingFile = this.delayLoadingFile;
  34757. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34758. for (kind in this._delayInfo) {
  34759. geometry._delayInfo = geometry._delayInfo || [];
  34760. geometry._delayInfo.push(kind);
  34761. }
  34762. // Bounding info
  34763. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34764. return geometry;
  34765. };
  34766. /**
  34767. * Serialize the current geometry info (and not the vertices data) into a JSON object
  34768. * @return a JSON representation of the current geometry data (without the vertices data)
  34769. */
  34770. Geometry.prototype.serialize = function () {
  34771. var serializationObject = {};
  34772. serializationObject.id = this.id;
  34773. serializationObject.updatable = this._updatable;
  34774. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34775. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34776. }
  34777. return serializationObject;
  34778. };
  34779. Geometry.prototype.toNumberArray = function (origin) {
  34780. if (Array.isArray(origin)) {
  34781. return origin;
  34782. }
  34783. else {
  34784. return Array.prototype.slice.call(origin);
  34785. }
  34786. };
  34787. /**
  34788. * Serialize all vertices data into a JSON oject
  34789. * @returns a JSON representation of the current geometry data
  34790. */
  34791. Geometry.prototype.serializeVerticeData = function () {
  34792. var serializationObject = this.serialize();
  34793. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34794. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  34795. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34796. serializationObject.positions._updatable = true;
  34797. }
  34798. }
  34799. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34800. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  34801. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34802. serializationObject.normals._updatable = true;
  34803. }
  34804. }
  34805. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34806. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  34807. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  34808. serializationObject.tangets._updatable = true;
  34809. }
  34810. }
  34811. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34812. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  34813. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  34814. serializationObject.uvs._updatable = true;
  34815. }
  34816. }
  34817. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34818. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  34819. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  34820. serializationObject.uv2s._updatable = true;
  34821. }
  34822. }
  34823. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34824. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  34825. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  34826. serializationObject.uv3s._updatable = true;
  34827. }
  34828. }
  34829. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34830. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  34831. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  34832. serializationObject.uv4s._updatable = true;
  34833. }
  34834. }
  34835. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34836. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  34837. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  34838. serializationObject.uv5s._updatable = true;
  34839. }
  34840. }
  34841. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34842. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  34843. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  34844. serializationObject.uv6s._updatable = true;
  34845. }
  34846. }
  34847. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34848. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  34849. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  34850. serializationObject.colors._updatable = true;
  34851. }
  34852. }
  34853. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34854. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  34855. serializationObject.matricesIndices._isExpanded = true;
  34856. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34857. serializationObject.matricesIndices._updatable = true;
  34858. }
  34859. }
  34860. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34861. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  34862. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34863. serializationObject.matricesWeights._updatable = true;
  34864. }
  34865. }
  34866. serializationObject.indices = this.toNumberArray(this.getIndices());
  34867. return serializationObject;
  34868. };
  34869. // Statics
  34870. /**
  34871. * Extracts a clone of a mesh geometry
  34872. * @param mesh defines the source mesh
  34873. * @param id defines the unique ID of the new geometry object
  34874. * @returns the new geometry object
  34875. */
  34876. Geometry.ExtractFromMesh = function (mesh, id) {
  34877. var geometry = mesh._geometry;
  34878. if (!geometry) {
  34879. return null;
  34880. }
  34881. return geometry.copy(id);
  34882. };
  34883. /**
  34884. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  34885. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34886. * Be aware Math.random() could cause collisions, but:
  34887. * "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"
  34888. * @returns a string containing a new GUID
  34889. */
  34890. Geometry.RandomId = function () {
  34891. return BABYLON.Tools.RandomId();
  34892. };
  34893. /** @ignore */
  34894. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  34895. var scene = mesh.getScene();
  34896. // Geometry
  34897. var geometryId = parsedGeometry.geometryId;
  34898. if (geometryId) {
  34899. var geometry = scene.getGeometryByID(geometryId);
  34900. if (geometry) {
  34901. geometry.applyToMesh(mesh);
  34902. }
  34903. }
  34904. else if (parsedGeometry instanceof ArrayBuffer) {
  34905. var binaryInfo = mesh._binaryInfo;
  34906. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34907. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34908. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34909. }
  34910. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34911. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34912. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34913. }
  34914. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  34915. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  34916. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  34917. }
  34918. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34919. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34920. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34921. }
  34922. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34923. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34924. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34925. }
  34926. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34927. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34928. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34929. }
  34930. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34931. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34932. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34933. }
  34934. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34935. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34936. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34937. }
  34938. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34939. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34940. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34941. }
  34942. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34943. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34944. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34945. }
  34946. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34947. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34948. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34949. }
  34950. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34951. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34952. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34953. }
  34954. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34955. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34956. mesh.setIndices(indicesData, null);
  34957. }
  34958. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34959. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34960. mesh.subMeshes = [];
  34961. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34962. var materialIndex = subMeshesData[(i * 5) + 0];
  34963. var verticesStart = subMeshesData[(i * 5) + 1];
  34964. var verticesCount = subMeshesData[(i * 5) + 2];
  34965. var indexStart = subMeshesData[(i * 5) + 3];
  34966. var indexCount = subMeshesData[(i * 5) + 4];
  34967. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34968. }
  34969. }
  34970. }
  34971. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34972. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  34973. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  34974. if (parsedGeometry.tangents) {
  34975. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  34976. }
  34977. if (parsedGeometry.uvs) {
  34978. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  34979. }
  34980. if (parsedGeometry.uvs2) {
  34981. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  34982. }
  34983. if (parsedGeometry.uvs3) {
  34984. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  34985. }
  34986. if (parsedGeometry.uvs4) {
  34987. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  34988. }
  34989. if (parsedGeometry.uvs5) {
  34990. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  34991. }
  34992. if (parsedGeometry.uvs6) {
  34993. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  34994. }
  34995. if (parsedGeometry.colors) {
  34996. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  34997. }
  34998. if (parsedGeometry.matricesIndices) {
  34999. if (!parsedGeometry.matricesIndices._isExpanded) {
  35000. var floatIndices = [];
  35001. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35002. var matricesIndex = parsedGeometry.matricesIndices[i];
  35003. floatIndices.push(matricesIndex & 0x000000FF);
  35004. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35005. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35006. floatIndices.push(matricesIndex >> 24);
  35007. }
  35008. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35009. }
  35010. else {
  35011. delete parsedGeometry.matricesIndices._isExpanded;
  35012. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35013. }
  35014. }
  35015. if (parsedGeometry.matricesIndicesExtra) {
  35016. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35017. var floatIndices = [];
  35018. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35019. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35020. floatIndices.push(matricesIndex & 0x000000FF);
  35021. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35022. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35023. floatIndices.push(matricesIndex >> 24);
  35024. }
  35025. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35026. }
  35027. else {
  35028. delete parsedGeometry.matricesIndices._isExpanded;
  35029. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35030. }
  35031. }
  35032. if (parsedGeometry.matricesWeights) {
  35033. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35034. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35035. }
  35036. if (parsedGeometry.matricesWeightsExtra) {
  35037. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35038. }
  35039. mesh.setIndices(parsedGeometry.indices, null);
  35040. }
  35041. // SubMeshes
  35042. if (parsedGeometry.subMeshes) {
  35043. mesh.subMeshes = [];
  35044. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35045. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35046. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35047. }
  35048. }
  35049. // Flat shading
  35050. if (mesh._shouldGenerateFlatShading) {
  35051. mesh.convertToFlatShadedMesh();
  35052. delete mesh._shouldGenerateFlatShading;
  35053. }
  35054. // Update
  35055. mesh.computeWorldMatrix(true);
  35056. // Octree
  35057. var sceneOctree = scene.selectionOctree;
  35058. if (sceneOctree !== undefined && sceneOctree !== null) {
  35059. sceneOctree.addMesh(mesh);
  35060. }
  35061. };
  35062. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35063. var epsilon = 1e-3;
  35064. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35065. return;
  35066. }
  35067. var noInfluenceBoneIndex = 0.0;
  35068. if (parsedGeometry.skeletonId > -1) {
  35069. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35070. if (!skeleton) {
  35071. return;
  35072. }
  35073. noInfluenceBoneIndex = skeleton.bones.length;
  35074. }
  35075. else {
  35076. return;
  35077. }
  35078. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35079. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35080. var matricesWeights = parsedGeometry.matricesWeights;
  35081. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35082. var influencers = parsedGeometry.numBoneInfluencer;
  35083. var size = matricesWeights.length;
  35084. for (var i = 0; i < size; i += 4) {
  35085. var weight = 0.0;
  35086. var firstZeroWeight = -1;
  35087. for (var j = 0; j < 4; j++) {
  35088. var w = matricesWeights[i + j];
  35089. weight += w;
  35090. if (w < epsilon && firstZeroWeight < 0) {
  35091. firstZeroWeight = j;
  35092. }
  35093. }
  35094. if (matricesWeightsExtra) {
  35095. for (var j = 0; j < 4; j++) {
  35096. var w = matricesWeightsExtra[i + j];
  35097. weight += w;
  35098. if (w < epsilon && firstZeroWeight < 0) {
  35099. firstZeroWeight = j + 4;
  35100. }
  35101. }
  35102. }
  35103. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35104. firstZeroWeight = influencers - 1;
  35105. }
  35106. if (weight > epsilon) {
  35107. var mweight = 1.0 / weight;
  35108. for (var j = 0; j < 4; j++) {
  35109. matricesWeights[i + j] *= mweight;
  35110. }
  35111. if (matricesWeightsExtra) {
  35112. for (var j = 0; j < 4; j++) {
  35113. matricesWeightsExtra[i + j] *= mweight;
  35114. }
  35115. }
  35116. }
  35117. else {
  35118. if (firstZeroWeight >= 4) {
  35119. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35120. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35121. }
  35122. else {
  35123. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35124. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35125. }
  35126. }
  35127. }
  35128. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35129. if (parsedGeometry.matricesWeightsExtra) {
  35130. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35131. }
  35132. };
  35133. /**
  35134. * Create a new geometry from persisted data (Using .babylon file format)
  35135. * @param parsedVertexData defines the persisted data
  35136. * @param scene defines the hosting scene
  35137. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35138. * @returns the new geometry object
  35139. */
  35140. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35141. if (scene.getGeometryByID(parsedVertexData.id)) {
  35142. return null; // null since geometry could be something else than a box...
  35143. }
  35144. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35145. if (BABYLON.Tags) {
  35146. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35147. }
  35148. if (parsedVertexData.delayLoadingFile) {
  35149. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35150. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35151. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35152. geometry._delayInfo = [];
  35153. if (parsedVertexData.hasUVs) {
  35154. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35155. }
  35156. if (parsedVertexData.hasUVs2) {
  35157. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35158. }
  35159. if (parsedVertexData.hasUVs3) {
  35160. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35161. }
  35162. if (parsedVertexData.hasUVs4) {
  35163. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35164. }
  35165. if (parsedVertexData.hasUVs5) {
  35166. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35167. }
  35168. if (parsedVertexData.hasUVs6) {
  35169. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35170. }
  35171. if (parsedVertexData.hasColors) {
  35172. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35173. }
  35174. if (parsedVertexData.hasMatricesIndices) {
  35175. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35176. }
  35177. if (parsedVertexData.hasMatricesWeights) {
  35178. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35179. }
  35180. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35181. }
  35182. else {
  35183. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35184. }
  35185. scene.pushGeometry(geometry, true);
  35186. return geometry;
  35187. };
  35188. return Geometry;
  35189. }());
  35190. BABYLON.Geometry = Geometry;
  35191. // Primitives
  35192. /// Abstract class
  35193. /**
  35194. * Abstract class used to provide common services for all typed geometries
  35195. */
  35196. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35197. __extends(_PrimitiveGeometry, _super);
  35198. /**
  35199. * Creates a new typed geometry
  35200. * @param id defines the unique ID of the geometry
  35201. * @param scene defines the hosting scene
  35202. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35203. * @param mesh defines the hosting mesh (can be null)
  35204. */
  35205. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35206. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35207. if (mesh === void 0) { mesh = null; }
  35208. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35209. _this._canBeRegenerated = _canBeRegenerated;
  35210. _this._beingRegenerated = true;
  35211. _this.regenerate();
  35212. _this._beingRegenerated = false;
  35213. return _this;
  35214. }
  35215. /**
  35216. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35217. * @returns true if the geometry can be regenerated
  35218. */
  35219. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35220. return this._canBeRegenerated;
  35221. };
  35222. /**
  35223. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35224. */
  35225. _PrimitiveGeometry.prototype.regenerate = function () {
  35226. if (!this._canBeRegenerated) {
  35227. return;
  35228. }
  35229. this._beingRegenerated = true;
  35230. this.setAllVerticesData(this._regenerateVertexData(), false);
  35231. this._beingRegenerated = false;
  35232. };
  35233. /**
  35234. * Clone the geometry
  35235. * @param id defines the unique ID of the new geometry
  35236. * @returns the new geometry
  35237. */
  35238. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35239. return _super.prototype.copy.call(this, id);
  35240. };
  35241. // overrides
  35242. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35243. if (!this._beingRegenerated) {
  35244. return;
  35245. }
  35246. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35247. };
  35248. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35249. if (!this._beingRegenerated) {
  35250. return;
  35251. }
  35252. _super.prototype.setVerticesData.call(this, kind, data, false);
  35253. };
  35254. // to override
  35255. /** @ignore */
  35256. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35257. throw new Error("Abstract method");
  35258. };
  35259. _PrimitiveGeometry.prototype.copy = function (id) {
  35260. throw new Error("Must be overriden in sub-classes.");
  35261. };
  35262. _PrimitiveGeometry.prototype.serialize = function () {
  35263. var serializationObject = _super.prototype.serialize.call(this);
  35264. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35265. return serializationObject;
  35266. };
  35267. return _PrimitiveGeometry;
  35268. }(Geometry));
  35269. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35270. /**
  35271. * Creates a ribbon geometry
  35272. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35273. */
  35274. var RibbonGeometry = /** @class */ (function (_super) {
  35275. __extends(RibbonGeometry, _super);
  35276. /**
  35277. * Creates a ribbon geometry
  35278. * @param id defines the unique ID of the geometry
  35279. * @param scene defines the hosting scene
  35280. * @param pathArray defines the array of paths to use
  35281. * @param closeArray defines if the last path and the first path must be joined
  35282. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35283. * @param offset defines the offset between points
  35284. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35285. * @param mesh defines the hosting mesh (can be null)
  35286. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35287. */
  35288. function RibbonGeometry(id, scene,
  35289. /**
  35290. * Defines the array of paths to use
  35291. */
  35292. pathArray,
  35293. /**
  35294. * Defines if the last and first points of each path in your pathArray must be joined
  35295. */
  35296. closeArray,
  35297. /**
  35298. * Defines if the last and first points of each path in your pathArray must be joined
  35299. */
  35300. closePath,
  35301. /**
  35302. * Defines the offset between points
  35303. */
  35304. offset, canBeRegenerated, mesh,
  35305. /**
  35306. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35307. */
  35308. side) {
  35309. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35310. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35311. _this.pathArray = pathArray;
  35312. _this.closeArray = closeArray;
  35313. _this.closePath = closePath;
  35314. _this.offset = offset;
  35315. _this.side = side;
  35316. return _this;
  35317. }
  35318. /** @ignore */
  35319. RibbonGeometry.prototype._regenerateVertexData = function () {
  35320. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35321. };
  35322. RibbonGeometry.prototype.copy = function (id) {
  35323. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35324. };
  35325. return RibbonGeometry;
  35326. }(_PrimitiveGeometry));
  35327. BABYLON.RibbonGeometry = RibbonGeometry;
  35328. /**
  35329. * Creates a box geometry
  35330. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35331. */
  35332. var BoxGeometry = /** @class */ (function (_super) {
  35333. __extends(BoxGeometry, _super);
  35334. /**
  35335. * Creates a box geometry
  35336. * @param id defines the unique ID of the geometry
  35337. * @param scene defines the hosting scene
  35338. * @param size defines the zise of the box (width, height and depth are the same)
  35339. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35340. * @param mesh defines the hosting mesh (can be null)
  35341. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35342. */
  35343. function BoxGeometry(id, scene,
  35344. /**
  35345. * Defines the zise of the box (width, height and depth are the same)
  35346. */
  35347. size, canBeRegenerated, mesh,
  35348. /**
  35349. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35350. */
  35351. side) {
  35352. if (mesh === void 0) { mesh = null; }
  35353. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35354. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35355. _this.size = size;
  35356. _this.side = side;
  35357. return _this;
  35358. }
  35359. BoxGeometry.prototype._regenerateVertexData = function () {
  35360. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35361. };
  35362. BoxGeometry.prototype.copy = function (id) {
  35363. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35364. };
  35365. BoxGeometry.prototype.serialize = function () {
  35366. var serializationObject = _super.prototype.serialize.call(this);
  35367. serializationObject.size = this.size;
  35368. return serializationObject;
  35369. };
  35370. BoxGeometry.Parse = function (parsedBox, scene) {
  35371. if (scene.getGeometryByID(parsedBox.id)) {
  35372. return null; // null since geometry could be something else than a box...
  35373. }
  35374. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35375. if (BABYLON.Tags) {
  35376. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35377. }
  35378. scene.pushGeometry(box, true);
  35379. return box;
  35380. };
  35381. return BoxGeometry;
  35382. }(_PrimitiveGeometry));
  35383. BABYLON.BoxGeometry = BoxGeometry;
  35384. /**
  35385. * Creates a sphere geometry
  35386. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35387. */
  35388. var SphereGeometry = /** @class */ (function (_super) {
  35389. __extends(SphereGeometry, _super);
  35390. /**
  35391. * Create a new sphere geometry
  35392. * @param id defines the unique ID of the geometry
  35393. * @param scene defines the hosting scene
  35394. * @param segments defines the number of segments to use to create the sphere
  35395. * @param diameter defines the diameter of the sphere
  35396. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35397. * @param mesh defines the hosting mesh (can be null)
  35398. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35399. */
  35400. function SphereGeometry(id, scene,
  35401. /**
  35402. * Defines the number of segments to use to create the sphere
  35403. */
  35404. segments,
  35405. /**
  35406. * Defines the diameter of the sphere
  35407. */
  35408. diameter, canBeRegenerated, mesh,
  35409. /**
  35410. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35411. */
  35412. side) {
  35413. if (mesh === void 0) { mesh = null; }
  35414. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35415. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35416. _this.segments = segments;
  35417. _this.diameter = diameter;
  35418. _this.side = side;
  35419. return _this;
  35420. }
  35421. SphereGeometry.prototype._regenerateVertexData = function () {
  35422. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35423. };
  35424. SphereGeometry.prototype.copy = function (id) {
  35425. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35426. };
  35427. SphereGeometry.prototype.serialize = function () {
  35428. var serializationObject = _super.prototype.serialize.call(this);
  35429. serializationObject.segments = this.segments;
  35430. serializationObject.diameter = this.diameter;
  35431. return serializationObject;
  35432. };
  35433. SphereGeometry.Parse = function (parsedSphere, scene) {
  35434. if (scene.getGeometryByID(parsedSphere.id)) {
  35435. return null; // null since geometry could be something else than a sphere...
  35436. }
  35437. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35438. if (BABYLON.Tags) {
  35439. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35440. }
  35441. scene.pushGeometry(sphere, true);
  35442. return sphere;
  35443. };
  35444. return SphereGeometry;
  35445. }(_PrimitiveGeometry));
  35446. BABYLON.SphereGeometry = SphereGeometry;
  35447. /**
  35448. * Creates a disc geometry
  35449. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35450. */
  35451. var DiscGeometry = /** @class */ (function (_super) {
  35452. __extends(DiscGeometry, _super);
  35453. /**
  35454. * Creates a new disc geometry
  35455. * @param id defines the unique ID of the geometry
  35456. * @param scene defines the hosting scene
  35457. * @param radius defines the radius of the disc
  35458. * @param tessellation defines the tesselation factor to apply to the disc
  35459. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35460. * @param mesh defines the hosting mesh (can be null)
  35461. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35462. */
  35463. function DiscGeometry(id, scene,
  35464. /**
  35465. * Defines the radius of the disc
  35466. */
  35467. radius,
  35468. /**
  35469. * Defines the tesselation factor to apply to the disc
  35470. */
  35471. tessellation, canBeRegenerated, mesh,
  35472. /**
  35473. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35474. */
  35475. side) {
  35476. if (mesh === void 0) { mesh = null; }
  35477. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35478. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35479. _this.radius = radius;
  35480. _this.tessellation = tessellation;
  35481. _this.side = side;
  35482. return _this;
  35483. }
  35484. DiscGeometry.prototype._regenerateVertexData = function () {
  35485. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35486. };
  35487. DiscGeometry.prototype.copy = function (id) {
  35488. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35489. };
  35490. return DiscGeometry;
  35491. }(_PrimitiveGeometry));
  35492. BABYLON.DiscGeometry = DiscGeometry;
  35493. /**
  35494. * Creates a new cylinder geometry
  35495. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35496. */
  35497. var CylinderGeometry = /** @class */ (function (_super) {
  35498. __extends(CylinderGeometry, _super);
  35499. /**
  35500. * Creates a new cylinder geometry
  35501. * @param id defines the unique ID of the geometry
  35502. * @param scene defines the hosting scene
  35503. * @param height defines the height of the cylinder
  35504. * @param diameterTop defines the diameter of the cylinder's top cap
  35505. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35506. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35507. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35508. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35509. * @param mesh defines the hosting mesh (can be null)
  35510. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35511. */
  35512. function CylinderGeometry(id, scene,
  35513. /**
  35514. * Defines the height of the cylinder
  35515. */
  35516. height,
  35517. /**
  35518. * Defines the diameter of the cylinder's top cap
  35519. */
  35520. diameterTop,
  35521. /**
  35522. * Defines the diameter of the cylinder's bottom cap
  35523. */
  35524. diameterBottom,
  35525. /**
  35526. * Defines the tessellation factor to apply to the cylinder
  35527. */
  35528. tessellation,
  35529. /**
  35530. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  35531. */
  35532. subdivisions, canBeRegenerated, mesh,
  35533. /**
  35534. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35535. */
  35536. side) {
  35537. if (subdivisions === void 0) { subdivisions = 1; }
  35538. if (mesh === void 0) { mesh = null; }
  35539. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35540. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35541. _this.height = height;
  35542. _this.diameterTop = diameterTop;
  35543. _this.diameterBottom = diameterBottom;
  35544. _this.tessellation = tessellation;
  35545. _this.subdivisions = subdivisions;
  35546. _this.side = side;
  35547. return _this;
  35548. }
  35549. CylinderGeometry.prototype._regenerateVertexData = function () {
  35550. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35551. };
  35552. CylinderGeometry.prototype.copy = function (id) {
  35553. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35554. };
  35555. CylinderGeometry.prototype.serialize = function () {
  35556. var serializationObject = _super.prototype.serialize.call(this);
  35557. serializationObject.height = this.height;
  35558. serializationObject.diameterTop = this.diameterTop;
  35559. serializationObject.diameterBottom = this.diameterBottom;
  35560. serializationObject.tessellation = this.tessellation;
  35561. return serializationObject;
  35562. };
  35563. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  35564. if (scene.getGeometryByID(parsedCylinder.id)) {
  35565. return null; // null since geometry could be something else than a cylinder...
  35566. }
  35567. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35568. if (BABYLON.Tags) {
  35569. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35570. }
  35571. scene.pushGeometry(cylinder, true);
  35572. return cylinder;
  35573. };
  35574. return CylinderGeometry;
  35575. }(_PrimitiveGeometry));
  35576. BABYLON.CylinderGeometry = CylinderGeometry;
  35577. /**
  35578. * Creates a new torus geometry
  35579. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  35580. */
  35581. var TorusGeometry = /** @class */ (function (_super) {
  35582. __extends(TorusGeometry, _super);
  35583. /**
  35584. * Creates a new torus geometry
  35585. * @param id defines the unique ID of the geometry
  35586. * @param scene defines the hosting scene
  35587. * @param diameter defines the diameter of the torus
  35588. * @param thickness defines the thickness of the torus (ie. internal diameter)
  35589. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  35590. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35591. * @param mesh defines the hosting mesh (can be null)
  35592. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35593. */
  35594. function TorusGeometry(id, scene,
  35595. /**
  35596. * Defines the diameter of the torus
  35597. */
  35598. diameter,
  35599. /**
  35600. * Defines the thickness of the torus (ie. internal diameter)
  35601. */
  35602. thickness,
  35603. /**
  35604. * Defines the tesselation factor to apply to the torus
  35605. */
  35606. tessellation, canBeRegenerated, mesh,
  35607. /**
  35608. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35609. */
  35610. side) {
  35611. if (mesh === void 0) { mesh = null; }
  35612. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35613. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35614. _this.diameter = diameter;
  35615. _this.thickness = thickness;
  35616. _this.tessellation = tessellation;
  35617. _this.side = side;
  35618. return _this;
  35619. }
  35620. TorusGeometry.prototype._regenerateVertexData = function () {
  35621. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35622. };
  35623. TorusGeometry.prototype.copy = function (id) {
  35624. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35625. };
  35626. TorusGeometry.prototype.serialize = function () {
  35627. var serializationObject = _super.prototype.serialize.call(this);
  35628. serializationObject.diameter = this.diameter;
  35629. serializationObject.thickness = this.thickness;
  35630. serializationObject.tessellation = this.tessellation;
  35631. return serializationObject;
  35632. };
  35633. TorusGeometry.Parse = function (parsedTorus, scene) {
  35634. if (scene.getGeometryByID(parsedTorus.id)) {
  35635. return null; // null since geometry could be something else than a torus...
  35636. }
  35637. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35638. if (BABYLON.Tags) {
  35639. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35640. }
  35641. scene.pushGeometry(torus, true);
  35642. return torus;
  35643. };
  35644. return TorusGeometry;
  35645. }(_PrimitiveGeometry));
  35646. BABYLON.TorusGeometry = TorusGeometry;
  35647. /**
  35648. * Creates a new ground geometry
  35649. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  35650. */
  35651. var GroundGeometry = /** @class */ (function (_super) {
  35652. __extends(GroundGeometry, _super);
  35653. /**
  35654. * Creates a new ground geometry
  35655. * @param id defines the unique ID of the geometry
  35656. * @param scene defines the hosting scene
  35657. * @param width defines the width of the ground
  35658. * @param height defines the height of the ground
  35659. * @param subdivisions defines the subdivisions to apply to the ground
  35660. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35661. * @param mesh defines the hosting mesh (can be null)
  35662. */
  35663. function GroundGeometry(id, scene,
  35664. /**
  35665. * Defines the width of the ground
  35666. */
  35667. width,
  35668. /**
  35669. * Defines the height of the ground
  35670. */
  35671. height,
  35672. /**
  35673. * Defines the subdivisions to apply to the ground
  35674. */
  35675. subdivisions, canBeRegenerated, mesh) {
  35676. if (mesh === void 0) { mesh = null; }
  35677. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35678. _this.width = width;
  35679. _this.height = height;
  35680. _this.subdivisions = subdivisions;
  35681. return _this;
  35682. }
  35683. GroundGeometry.prototype._regenerateVertexData = function () {
  35684. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35685. };
  35686. GroundGeometry.prototype.copy = function (id) {
  35687. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35688. };
  35689. GroundGeometry.prototype.serialize = function () {
  35690. var serializationObject = _super.prototype.serialize.call(this);
  35691. serializationObject.width = this.width;
  35692. serializationObject.height = this.height;
  35693. serializationObject.subdivisions = this.subdivisions;
  35694. return serializationObject;
  35695. };
  35696. GroundGeometry.Parse = function (parsedGround, scene) {
  35697. if (scene.getGeometryByID(parsedGround.id)) {
  35698. return null; // null since geometry could be something else than a ground...
  35699. }
  35700. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35701. if (BABYLON.Tags) {
  35702. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35703. }
  35704. scene.pushGeometry(ground, true);
  35705. return ground;
  35706. };
  35707. return GroundGeometry;
  35708. }(_PrimitiveGeometry));
  35709. BABYLON.GroundGeometry = GroundGeometry;
  35710. /**
  35711. * Creates a tiled ground geometry
  35712. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  35713. */
  35714. var TiledGroundGeometry = /** @class */ (function (_super) {
  35715. __extends(TiledGroundGeometry, _super);
  35716. /**
  35717. * Creates a tiled ground geometry
  35718. * @param id defines the unique ID of the geometry
  35719. * @param scene defines the hosting scene
  35720. * @param xmin defines the minimum value on X axis
  35721. * @param zmin defines the minimum value on Z axis
  35722. * @param xmax defines the maximum value on X axis
  35723. * @param zmax defines the maximum value on Z axis
  35724. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  35725. * @param precision defines the precision to use when computing the tiles
  35726. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35727. * @param mesh defines the hosting mesh (can be null)
  35728. */
  35729. function TiledGroundGeometry(id, scene,
  35730. /**
  35731. * Defines the minimum value on X axis
  35732. */
  35733. xmin,
  35734. /**
  35735. * Defines the minimum value on Z axis
  35736. */
  35737. zmin,
  35738. /**
  35739. * Defines the maximum value on X axis
  35740. */
  35741. xmax,
  35742. /**
  35743. * Defines the maximum value on Z axis
  35744. */
  35745. zmax,
  35746. /**
  35747. * Defines the subdivisions to apply to the ground
  35748. */
  35749. subdivisions,
  35750. /**
  35751. * Defines the precision to use when computing the tiles
  35752. */
  35753. precision, canBeRegenerated, mesh) {
  35754. if (mesh === void 0) { mesh = null; }
  35755. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35756. _this.xmin = xmin;
  35757. _this.zmin = zmin;
  35758. _this.xmax = xmax;
  35759. _this.zmax = zmax;
  35760. _this.subdivisions = subdivisions;
  35761. _this.precision = precision;
  35762. return _this;
  35763. }
  35764. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  35765. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35766. };
  35767. TiledGroundGeometry.prototype.copy = function (id) {
  35768. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35769. };
  35770. return TiledGroundGeometry;
  35771. }(_PrimitiveGeometry));
  35772. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  35773. /**
  35774. * Creates a plane geometry
  35775. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  35776. */
  35777. var PlaneGeometry = /** @class */ (function (_super) {
  35778. __extends(PlaneGeometry, _super);
  35779. /**
  35780. * Creates a plane geometry
  35781. * @param id defines the unique ID of the geometry
  35782. * @param scene defines the hosting scene
  35783. * @param size defines the size of the plane (width === height)
  35784. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35785. * @param mesh defines the hosting mesh (can be null)
  35786. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35787. */
  35788. function PlaneGeometry(id, scene,
  35789. /**
  35790. * Defines the size of the plane (width === height)
  35791. */
  35792. size, canBeRegenerated, mesh,
  35793. /**
  35794. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35795. */
  35796. side) {
  35797. if (mesh === void 0) { mesh = null; }
  35798. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35799. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35800. _this.size = size;
  35801. _this.side = side;
  35802. return _this;
  35803. }
  35804. PlaneGeometry.prototype._regenerateVertexData = function () {
  35805. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35806. };
  35807. PlaneGeometry.prototype.copy = function (id) {
  35808. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35809. };
  35810. PlaneGeometry.prototype.serialize = function () {
  35811. var serializationObject = _super.prototype.serialize.call(this);
  35812. serializationObject.size = this.size;
  35813. return serializationObject;
  35814. };
  35815. PlaneGeometry.Parse = function (parsedPlane, scene) {
  35816. if (scene.getGeometryByID(parsedPlane.id)) {
  35817. return null; // null since geometry could be something else than a ground...
  35818. }
  35819. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35820. if (BABYLON.Tags) {
  35821. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35822. }
  35823. scene.pushGeometry(plane, true);
  35824. return plane;
  35825. };
  35826. return PlaneGeometry;
  35827. }(_PrimitiveGeometry));
  35828. BABYLON.PlaneGeometry = PlaneGeometry;
  35829. /**
  35830. * Creates a torus knot geometry
  35831. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  35832. */
  35833. var TorusKnotGeometry = /** @class */ (function (_super) {
  35834. __extends(TorusKnotGeometry, _super);
  35835. /**
  35836. * Creates a torus knot geometry
  35837. * @param id defines the unique ID of the geometry
  35838. * @param scene defines the hosting scene
  35839. * @param radius defines the radius of the torus knot
  35840. * @param tube defines the thickness of the torus knot tube
  35841. * @param radialSegments defines the number of radial segments
  35842. * @param tubularSegments defines the number of tubular segments
  35843. * @param p defines the first number of windings
  35844. * @param q defines the second number of windings
  35845. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35846. * @param mesh defines the hosting mesh (can be null)
  35847. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35848. */
  35849. function TorusKnotGeometry(id, scene,
  35850. /**
  35851. * Defines the radius of the torus knot
  35852. */
  35853. radius,
  35854. /**
  35855. * Defines the thickness of the torus knot tube
  35856. */
  35857. tube,
  35858. /**
  35859. * Defines the number of radial segments
  35860. */
  35861. radialSegments,
  35862. /**
  35863. * Defines the number of tubular segments
  35864. */
  35865. tubularSegments,
  35866. /**
  35867. * Defines the first number of windings
  35868. */
  35869. p,
  35870. /**
  35871. * Defines the second number of windings
  35872. */
  35873. q, canBeRegenerated, mesh,
  35874. /**
  35875. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35876. */
  35877. side) {
  35878. if (mesh === void 0) { mesh = null; }
  35879. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35880. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35881. _this.radius = radius;
  35882. _this.tube = tube;
  35883. _this.radialSegments = radialSegments;
  35884. _this.tubularSegments = tubularSegments;
  35885. _this.p = p;
  35886. _this.q = q;
  35887. _this.side = side;
  35888. return _this;
  35889. }
  35890. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  35891. 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 });
  35892. };
  35893. TorusKnotGeometry.prototype.copy = function (id) {
  35894. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35895. };
  35896. TorusKnotGeometry.prototype.serialize = function () {
  35897. var serializationObject = _super.prototype.serialize.call(this);
  35898. serializationObject.radius = this.radius;
  35899. serializationObject.tube = this.tube;
  35900. serializationObject.radialSegments = this.radialSegments;
  35901. serializationObject.tubularSegments = this.tubularSegments;
  35902. serializationObject.p = this.p;
  35903. serializationObject.q = this.q;
  35904. return serializationObject;
  35905. };
  35906. ;
  35907. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  35908. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35909. return null; // null since geometry could be something else than a ground...
  35910. }
  35911. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35912. if (BABYLON.Tags) {
  35913. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35914. }
  35915. scene.pushGeometry(torusKnot, true);
  35916. return torusKnot;
  35917. };
  35918. return TorusKnotGeometry;
  35919. }(_PrimitiveGeometry));
  35920. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  35921. //}
  35922. })(BABYLON || (BABYLON = {}));
  35923. //# sourceMappingURL=babylon.geometry.js.map
  35924. var BABYLON;
  35925. (function (BABYLON) {
  35926. /**
  35927. * PostProcessManager is used to manage one or more post processes or post process pipelines
  35928. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  35929. */
  35930. var PostProcessManager = /** @class */ (function () {
  35931. /**
  35932. * Creates a new instance of @see PostProcess
  35933. * @param scene The scene that the post process is associated with.
  35934. */
  35935. function PostProcessManager(scene) {
  35936. this._vertexBuffers = {};
  35937. this._scene = scene;
  35938. }
  35939. PostProcessManager.prototype._prepareBuffers = function () {
  35940. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  35941. return;
  35942. }
  35943. // VBO
  35944. var vertices = [];
  35945. vertices.push(1, 1);
  35946. vertices.push(-1, 1);
  35947. vertices.push(-1, -1);
  35948. vertices.push(1, -1);
  35949. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  35950. this._buildIndexBuffer();
  35951. };
  35952. PostProcessManager.prototype._buildIndexBuffer = function () {
  35953. // Indices
  35954. var indices = [];
  35955. indices.push(0);
  35956. indices.push(1);
  35957. indices.push(2);
  35958. indices.push(0);
  35959. indices.push(2);
  35960. indices.push(3);
  35961. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  35962. };
  35963. /**
  35964. * Rebuilds the vertex buffers of the manager.
  35965. */
  35966. PostProcessManager.prototype._rebuild = function () {
  35967. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35968. if (!vb) {
  35969. return;
  35970. }
  35971. vb._rebuild();
  35972. this._buildIndexBuffer();
  35973. };
  35974. // Methods
  35975. /**
  35976. * Prepares a frame to be run through a post process.
  35977. * @param sourceTexture The input texture to the post procesess. (default: null)
  35978. * @param postProcesses An array of post processes to be run. (default: null)
  35979. * @returns True if the post processes were able to be run.
  35980. */
  35981. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  35982. if (sourceTexture === void 0) { sourceTexture = null; }
  35983. if (postProcesses === void 0) { postProcesses = null; }
  35984. var camera = this._scene.activeCamera;
  35985. if (!camera) {
  35986. return false;
  35987. }
  35988. var postProcesses = postProcesses || camera._postProcesses;
  35989. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35990. return false;
  35991. }
  35992. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  35993. return true;
  35994. };
  35995. /**
  35996. * Manually render a set of post processes to a texture.
  35997. * @param postProcesses An array of post processes to be run.
  35998. * @param targetTexture The target texture to render to.
  35999. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36000. */
  36001. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36002. if (targetTexture === void 0) { targetTexture = null; }
  36003. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36004. var engine = this._scene.getEngine();
  36005. for (var index = 0; index < postProcesses.length; index++) {
  36006. if (index < postProcesses.length - 1) {
  36007. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36008. }
  36009. else {
  36010. if (targetTexture) {
  36011. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36012. }
  36013. else {
  36014. engine.restoreDefaultFramebuffer();
  36015. }
  36016. }
  36017. var pp = postProcesses[index];
  36018. var effect = pp.apply();
  36019. if (effect) {
  36020. pp.onBeforeRenderObservable.notifyObservers(effect);
  36021. // VBOs
  36022. this._prepareBuffers();
  36023. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36024. // Draw order
  36025. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36026. pp.onAfterRenderObservable.notifyObservers(effect);
  36027. }
  36028. }
  36029. // Restore depth buffer
  36030. engine.setDepthBuffer(true);
  36031. engine.setDepthWrite(true);
  36032. };
  36033. /**
  36034. * Finalize the result of the output of the postprocesses.
  36035. * @param doNotPresent If true the result will not be displayed to the screen.
  36036. * @param targetTexture The target texture to render to.
  36037. * @param faceIndex The index of the face to bind the target texture to.
  36038. * @param postProcesses The array of post processes to render.
  36039. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36040. */
  36041. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36042. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36043. var camera = this._scene.activeCamera;
  36044. if (!camera) {
  36045. return;
  36046. }
  36047. postProcesses = postProcesses || camera._postProcesses;
  36048. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36049. return;
  36050. }
  36051. var engine = this._scene.getEngine();
  36052. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36053. if (index < len - 1) {
  36054. postProcesses[index + 1].activate(camera, targetTexture);
  36055. }
  36056. else {
  36057. if (targetTexture) {
  36058. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36059. }
  36060. else {
  36061. engine.restoreDefaultFramebuffer();
  36062. }
  36063. }
  36064. if (doNotPresent) {
  36065. break;
  36066. }
  36067. var pp = postProcesses[index];
  36068. var effect = pp.apply();
  36069. if (effect) {
  36070. pp.onBeforeRenderObservable.notifyObservers(effect);
  36071. // VBOs
  36072. this._prepareBuffers();
  36073. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36074. // Draw order
  36075. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36076. pp.onAfterRenderObservable.notifyObservers(effect);
  36077. }
  36078. }
  36079. // Restore states
  36080. engine.setDepthBuffer(true);
  36081. engine.setDepthWrite(true);
  36082. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36083. };
  36084. /**
  36085. * Disposes of the post process manager.
  36086. */
  36087. PostProcessManager.prototype.dispose = function () {
  36088. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36089. if (buffer) {
  36090. buffer.dispose();
  36091. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36092. }
  36093. if (this._indexBuffer) {
  36094. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36095. this._indexBuffer = null;
  36096. }
  36097. };
  36098. return PostProcessManager;
  36099. }());
  36100. BABYLON.PostProcessManager = PostProcessManager;
  36101. })(BABYLON || (BABYLON = {}));
  36102. //# sourceMappingURL=babylon.postProcessManager.js.map
  36103. var BABYLON;
  36104. (function (BABYLON) {
  36105. /**
  36106. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36107. */
  36108. var PerformanceMonitor = /** @class */ (function () {
  36109. /**
  36110. * constructor
  36111. * @param frameSampleSize The number of samples required to saturate the sliding window
  36112. */
  36113. function PerformanceMonitor(frameSampleSize) {
  36114. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36115. this._enabled = true;
  36116. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36117. }
  36118. /**
  36119. * Samples current frame
  36120. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36121. */
  36122. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36123. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36124. if (!this._enabled)
  36125. return;
  36126. if (this._lastFrameTimeMs != null) {
  36127. var dt = timeMs - this._lastFrameTimeMs;
  36128. this._rollingFrameTime.add(dt);
  36129. }
  36130. this._lastFrameTimeMs = timeMs;
  36131. };
  36132. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36133. /**
  36134. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36135. * @return Average frame time in milliseconds
  36136. */
  36137. get: function () {
  36138. return this._rollingFrameTime.average;
  36139. },
  36140. enumerable: true,
  36141. configurable: true
  36142. });
  36143. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36144. /**
  36145. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36146. * @return Frame time variance in milliseconds squared
  36147. */
  36148. get: function () {
  36149. return this._rollingFrameTime.variance;
  36150. },
  36151. enumerable: true,
  36152. configurable: true
  36153. });
  36154. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36155. /**
  36156. * Returns the frame time of the most recent frame
  36157. * @return Frame time in milliseconds
  36158. */
  36159. get: function () {
  36160. return this._rollingFrameTime.history(0);
  36161. },
  36162. enumerable: true,
  36163. configurable: true
  36164. });
  36165. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36166. /**
  36167. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36168. * @return Framerate in frames per second
  36169. */
  36170. get: function () {
  36171. return 1000.0 / this._rollingFrameTime.average;
  36172. },
  36173. enumerable: true,
  36174. configurable: true
  36175. });
  36176. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36177. /**
  36178. * Returns the average framerate in frames per second using the most recent frame time
  36179. * @return Framerate in frames per second
  36180. */
  36181. get: function () {
  36182. var history = this._rollingFrameTime.history(0);
  36183. if (history === 0) {
  36184. return 0;
  36185. }
  36186. return 1000.0 / history;
  36187. },
  36188. enumerable: true,
  36189. configurable: true
  36190. });
  36191. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36192. /**
  36193. * Returns true if enough samples have been taken to completely fill the sliding window
  36194. * @return true if saturated
  36195. */
  36196. get: function () {
  36197. return this._rollingFrameTime.isSaturated();
  36198. },
  36199. enumerable: true,
  36200. configurable: true
  36201. });
  36202. /**
  36203. * Enables contributions to the sliding window sample set
  36204. */
  36205. PerformanceMonitor.prototype.enable = function () {
  36206. this._enabled = true;
  36207. };
  36208. /**
  36209. * Disables contributions to the sliding window sample set
  36210. * Samples will not be interpolated over the disabled period
  36211. */
  36212. PerformanceMonitor.prototype.disable = function () {
  36213. this._enabled = false;
  36214. //clear last sample to avoid interpolating over the disabled period when next enabled
  36215. this._lastFrameTimeMs = null;
  36216. };
  36217. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36218. /**
  36219. * Returns true if sampling is enabled
  36220. * @return true if enabled
  36221. */
  36222. get: function () {
  36223. return this._enabled;
  36224. },
  36225. enumerable: true,
  36226. configurable: true
  36227. });
  36228. /**
  36229. * Resets performance monitor
  36230. */
  36231. PerformanceMonitor.prototype.reset = function () {
  36232. //clear last sample to avoid interpolating over the disabled period when next enabled
  36233. this._lastFrameTimeMs = null;
  36234. //wipe record
  36235. this._rollingFrameTime.reset();
  36236. };
  36237. return PerformanceMonitor;
  36238. }());
  36239. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36240. /**
  36241. * RollingAverage
  36242. *
  36243. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36244. */
  36245. var RollingAverage = /** @class */ (function () {
  36246. /**
  36247. * constructor
  36248. * @param length The number of samples required to saturate the sliding window
  36249. */
  36250. function RollingAverage(length) {
  36251. this._samples = new Array(length);
  36252. this.reset();
  36253. }
  36254. /**
  36255. * Adds a sample to the sample set
  36256. * @param v The sample value
  36257. */
  36258. RollingAverage.prototype.add = function (v) {
  36259. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36260. var delta;
  36261. //we need to check if we've already wrapped round
  36262. if (this.isSaturated()) {
  36263. //remove bottom of stack from mean
  36264. var bottomValue = this._samples[this._pos];
  36265. delta = bottomValue - this.average;
  36266. this.average -= delta / (this._sampleCount - 1);
  36267. this._m2 -= delta * (bottomValue - this.average);
  36268. }
  36269. else {
  36270. this._sampleCount++;
  36271. }
  36272. //add new value to mean
  36273. delta = v - this.average;
  36274. this.average += delta / (this._sampleCount);
  36275. this._m2 += delta * (v - this.average);
  36276. //set the new variance
  36277. this.variance = this._m2 / (this._sampleCount - 1);
  36278. this._samples[this._pos] = v;
  36279. this._pos++;
  36280. this._pos %= this._samples.length; //positive wrap around
  36281. };
  36282. /**
  36283. * Returns previously added values or null if outside of history or outside the sliding window domain
  36284. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36285. * @return Value previously recorded with add() or null if outside of range
  36286. */
  36287. RollingAverage.prototype.history = function (i) {
  36288. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36289. return 0;
  36290. }
  36291. var i0 = this._wrapPosition(this._pos - 1.0);
  36292. return this._samples[this._wrapPosition(i0 - i)];
  36293. };
  36294. /**
  36295. * Returns true if enough samples have been taken to completely fill the sliding window
  36296. * @return true if sample-set saturated
  36297. */
  36298. RollingAverage.prototype.isSaturated = function () {
  36299. return this._sampleCount >= this._samples.length;
  36300. };
  36301. /**
  36302. * Resets the rolling average (equivalent to 0 samples taken so far)
  36303. */
  36304. RollingAverage.prototype.reset = function () {
  36305. this.average = 0;
  36306. this.variance = 0;
  36307. this._sampleCount = 0;
  36308. this._pos = 0;
  36309. this._m2 = 0;
  36310. };
  36311. /**
  36312. * Wraps a value around the sample range boundaries
  36313. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36314. * @return Wrapped position in sample range
  36315. */
  36316. RollingAverage.prototype._wrapPosition = function (i) {
  36317. var max = this._samples.length;
  36318. return ((i % max) + max) % max;
  36319. };
  36320. return RollingAverage;
  36321. }());
  36322. BABYLON.RollingAverage = RollingAverage;
  36323. })(BABYLON || (BABYLON = {}));
  36324. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36325. var BABYLON;
  36326. (function (BABYLON) {
  36327. /**
  36328. * This groups together the common properties used for image processing either in direct forward pass
  36329. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36330. * or not.
  36331. */
  36332. var ImageProcessingConfiguration = /** @class */ (function () {
  36333. function ImageProcessingConfiguration() {
  36334. /**
  36335. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36336. */
  36337. this.colorCurves = new BABYLON.ColorCurves();
  36338. this._colorCurvesEnabled = false;
  36339. this._colorGradingEnabled = false;
  36340. this._colorGradingWithGreenDepth = true;
  36341. this._colorGradingBGR = true;
  36342. this._exposure = 1.0;
  36343. this._toneMappingEnabled = false;
  36344. this._contrast = 1.0;
  36345. /**
  36346. * Vignette stretch size.
  36347. */
  36348. this.vignetteStretch = 0;
  36349. /**
  36350. * Vignette centre X Offset.
  36351. */
  36352. this.vignetteCentreX = 0;
  36353. /**
  36354. * Vignette centre Y Offset.
  36355. */
  36356. this.vignetteCentreY = 0;
  36357. /**
  36358. * Vignette weight or intensity of the vignette effect.
  36359. */
  36360. this.vignetteWeight = 1.5;
  36361. /**
  36362. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36363. * if vignetteEnabled is set to true.
  36364. */
  36365. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36366. /**
  36367. * Camera field of view used by the Vignette effect.
  36368. */
  36369. this.vignetteCameraFov = 0.5;
  36370. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36371. this._vignetteEnabled = false;
  36372. this._applyByPostProcess = false;
  36373. this._isEnabled = true;
  36374. /**
  36375. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36376. * @type {BABYLON.Observable}
  36377. */
  36378. this.onUpdateParameters = new BABYLON.Observable();
  36379. }
  36380. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36381. /**
  36382. * Gets wether the color curves effect is enabled.
  36383. */
  36384. get: function () {
  36385. return this._colorCurvesEnabled;
  36386. },
  36387. /**
  36388. * Sets wether the color curves effect is enabled.
  36389. */
  36390. set: function (value) {
  36391. if (this._colorCurvesEnabled === value) {
  36392. return;
  36393. }
  36394. this._colorCurvesEnabled = value;
  36395. this._updateParameters();
  36396. },
  36397. enumerable: true,
  36398. configurable: true
  36399. });
  36400. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36401. /**
  36402. * Gets wether the color grading effect is enabled.
  36403. */
  36404. get: function () {
  36405. return this._colorGradingEnabled;
  36406. },
  36407. /**
  36408. * Sets wether the color grading effect is enabled.
  36409. */
  36410. set: function (value) {
  36411. if (this._colorGradingEnabled === value) {
  36412. return;
  36413. }
  36414. this._colorGradingEnabled = value;
  36415. this._updateParameters();
  36416. },
  36417. enumerable: true,
  36418. configurable: true
  36419. });
  36420. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36421. /**
  36422. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36423. */
  36424. get: function () {
  36425. return this._colorGradingWithGreenDepth;
  36426. },
  36427. /**
  36428. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36429. */
  36430. set: function (value) {
  36431. if (this._colorGradingWithGreenDepth === value) {
  36432. return;
  36433. }
  36434. this._colorGradingWithGreenDepth = value;
  36435. this._updateParameters();
  36436. },
  36437. enumerable: true,
  36438. configurable: true
  36439. });
  36440. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36441. /**
  36442. * Gets wether the color grading texture contains BGR values.
  36443. */
  36444. get: function () {
  36445. return this._colorGradingBGR;
  36446. },
  36447. /**
  36448. * Sets wether the color grading texture contains BGR values.
  36449. */
  36450. set: function (value) {
  36451. if (this._colorGradingBGR === value) {
  36452. return;
  36453. }
  36454. this._colorGradingBGR = value;
  36455. this._updateParameters();
  36456. },
  36457. enumerable: true,
  36458. configurable: true
  36459. });
  36460. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36461. /**
  36462. * Gets the Exposure used in the effect.
  36463. */
  36464. get: function () {
  36465. return this._exposure;
  36466. },
  36467. /**
  36468. * Sets the Exposure used in the effect.
  36469. */
  36470. set: function (value) {
  36471. if (this._exposure === value) {
  36472. return;
  36473. }
  36474. this._exposure = value;
  36475. this._updateParameters();
  36476. },
  36477. enumerable: true,
  36478. configurable: true
  36479. });
  36480. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36481. /**
  36482. * Gets wether the tone mapping effect is enabled.
  36483. */
  36484. get: function () {
  36485. return this._toneMappingEnabled;
  36486. },
  36487. /**
  36488. * Sets wether the tone mapping effect is enabled.
  36489. */
  36490. set: function (value) {
  36491. if (this._toneMappingEnabled === value) {
  36492. return;
  36493. }
  36494. this._toneMappingEnabled = value;
  36495. this._updateParameters();
  36496. },
  36497. enumerable: true,
  36498. configurable: true
  36499. });
  36500. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36501. /**
  36502. * Gets the contrast used in the effect.
  36503. */
  36504. get: function () {
  36505. return this._contrast;
  36506. },
  36507. /**
  36508. * Sets the contrast used in the effect.
  36509. */
  36510. set: function (value) {
  36511. if (this._contrast === value) {
  36512. return;
  36513. }
  36514. this._contrast = value;
  36515. this._updateParameters();
  36516. },
  36517. enumerable: true,
  36518. configurable: true
  36519. });
  36520. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  36521. /**
  36522. * Gets the vignette blend mode allowing different kind of effect.
  36523. */
  36524. get: function () {
  36525. return this._vignetteBlendMode;
  36526. },
  36527. /**
  36528. * Sets the vignette blend mode allowing different kind of effect.
  36529. */
  36530. set: function (value) {
  36531. if (this._vignetteBlendMode === value) {
  36532. return;
  36533. }
  36534. this._vignetteBlendMode = value;
  36535. this._updateParameters();
  36536. },
  36537. enumerable: true,
  36538. configurable: true
  36539. });
  36540. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  36541. /**
  36542. * Gets wether the vignette effect is enabled.
  36543. */
  36544. get: function () {
  36545. return this._vignetteEnabled;
  36546. },
  36547. /**
  36548. * Sets wether the vignette effect is enabled.
  36549. */
  36550. set: function (value) {
  36551. if (this._vignetteEnabled === value) {
  36552. return;
  36553. }
  36554. this._vignetteEnabled = value;
  36555. this._updateParameters();
  36556. },
  36557. enumerable: true,
  36558. configurable: true
  36559. });
  36560. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  36561. /**
  36562. * Gets wether the image processing is applied through a post process or not.
  36563. */
  36564. get: function () {
  36565. return this._applyByPostProcess;
  36566. },
  36567. /**
  36568. * Sets wether the image processing is applied through a post process or not.
  36569. */
  36570. set: function (value) {
  36571. if (this._applyByPostProcess === value) {
  36572. return;
  36573. }
  36574. this._applyByPostProcess = value;
  36575. this._updateParameters();
  36576. },
  36577. enumerable: true,
  36578. configurable: true
  36579. });
  36580. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  36581. /**
  36582. * Gets wether the image processing is enabled or not.
  36583. */
  36584. get: function () {
  36585. return this._isEnabled;
  36586. },
  36587. /**
  36588. * Sets wether the image processing is enabled or not.
  36589. */
  36590. set: function (value) {
  36591. if (this._isEnabled === value) {
  36592. return;
  36593. }
  36594. this._isEnabled = value;
  36595. this._updateParameters();
  36596. },
  36597. enumerable: true,
  36598. configurable: true
  36599. });
  36600. /**
  36601. * Method called each time the image processing information changes requires to recompile the effect.
  36602. */
  36603. ImageProcessingConfiguration.prototype._updateParameters = function () {
  36604. this.onUpdateParameters.notifyObservers(this);
  36605. };
  36606. ImageProcessingConfiguration.prototype.getClassName = function () {
  36607. return "ImageProcessingConfiguration";
  36608. };
  36609. /**
  36610. * Prepare the list of uniforms associated with the Image Processing effects.
  36611. * @param uniformsList The list of uniforms used in the effect
  36612. * @param defines the list of defines currently in use
  36613. */
  36614. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  36615. if (defines.EXPOSURE) {
  36616. uniforms.push("exposureLinear");
  36617. }
  36618. if (defines.CONTRAST) {
  36619. uniforms.push("contrast");
  36620. }
  36621. if (defines.COLORGRADING) {
  36622. uniforms.push("colorTransformSettings");
  36623. }
  36624. if (defines.VIGNETTE) {
  36625. uniforms.push("vInverseScreenSize");
  36626. uniforms.push("vignetteSettings1");
  36627. uniforms.push("vignetteSettings2");
  36628. }
  36629. if (defines.COLORCURVES) {
  36630. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  36631. }
  36632. };
  36633. /**
  36634. * Prepare the list of samplers associated with the Image Processing effects.
  36635. * @param uniformsList The list of uniforms used in the effect
  36636. * @param defines the list of defines currently in use
  36637. */
  36638. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  36639. if (defines.COLORGRADING) {
  36640. samplersList.push("txColorTransform");
  36641. }
  36642. };
  36643. /**
  36644. * Prepare the list of defines associated to the shader.
  36645. * @param defines the list of defines to complete
  36646. */
  36647. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  36648. if (forPostProcess === void 0) { forPostProcess = false; }
  36649. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  36650. defines.VIGNETTE = false;
  36651. defines.TONEMAPPING = false;
  36652. defines.CONTRAST = false;
  36653. defines.EXPOSURE = false;
  36654. defines.COLORCURVES = false;
  36655. defines.COLORGRADING = false;
  36656. defines.COLORGRADING3D = false;
  36657. defines.IMAGEPROCESSING = false;
  36658. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  36659. return;
  36660. }
  36661. defines.VIGNETTE = this.vignetteEnabled;
  36662. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  36663. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  36664. defines.TONEMAPPING = this.toneMappingEnabled;
  36665. defines.CONTRAST = (this.contrast !== 1.0);
  36666. defines.EXPOSURE = (this.exposure !== 1.0);
  36667. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  36668. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  36669. if (defines.COLORGRADING) {
  36670. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  36671. }
  36672. else {
  36673. defines.COLORGRADING3D = false;
  36674. }
  36675. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  36676. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  36677. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  36678. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  36679. };
  36680. /**
  36681. * Returns true if all the image processing information are ready.
  36682. */
  36683. ImageProcessingConfiguration.prototype.isReady = function () {
  36684. // Color Grading texure can not be none blocking.
  36685. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  36686. };
  36687. /**
  36688. * Binds the image processing to the shader.
  36689. * @param effect The effect to bind to
  36690. */
  36691. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  36692. if (aspectRatio === void 0) { aspectRatio = 1; }
  36693. // Color Curves
  36694. if (this._colorCurvesEnabled && this.colorCurves) {
  36695. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  36696. }
  36697. // Vignette
  36698. if (this._vignetteEnabled) {
  36699. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  36700. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  36701. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  36702. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  36703. var vignetteScaleX = vignetteScaleY * aspectRatio;
  36704. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  36705. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  36706. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  36707. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  36708. var vignettePower = -2.0 * this.vignetteWeight;
  36709. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  36710. }
  36711. // Exposure
  36712. effect.setFloat("exposureLinear", this.exposure);
  36713. // Contrast
  36714. effect.setFloat("contrast", this.contrast);
  36715. // Color transform settings
  36716. if (this.colorGradingTexture) {
  36717. effect.setTexture("txColorTransform", this.colorGradingTexture);
  36718. var textureSize = this.colorGradingTexture.getSize().height;
  36719. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  36720. 0.5 / textureSize, // textureOffset
  36721. textureSize, // textureSize
  36722. this.colorGradingTexture.level // weight
  36723. );
  36724. }
  36725. };
  36726. /**
  36727. * Clones the current image processing instance.
  36728. * @return The cloned image processing
  36729. */
  36730. ImageProcessingConfiguration.prototype.clone = function () {
  36731. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  36732. };
  36733. /**
  36734. * Serializes the current image processing instance to a json representation.
  36735. * @return a JSON representation
  36736. */
  36737. ImageProcessingConfiguration.prototype.serialize = function () {
  36738. return BABYLON.SerializationHelper.Serialize(this);
  36739. };
  36740. /**
  36741. * Parses the image processing from a json representation.
  36742. * @param source the JSON source to parse
  36743. * @return The parsed image processing
  36744. */
  36745. ImageProcessingConfiguration.Parse = function (source) {
  36746. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  36747. };
  36748. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  36749. /**
  36750. * Used to apply the vignette as a mix with the pixel color.
  36751. */
  36752. get: function () {
  36753. return this._VIGNETTEMODE_MULTIPLY;
  36754. },
  36755. enumerable: true,
  36756. configurable: true
  36757. });
  36758. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  36759. /**
  36760. * Used to apply the vignette as a replacement of the pixel color.
  36761. */
  36762. get: function () {
  36763. return this._VIGNETTEMODE_OPAQUE;
  36764. },
  36765. enumerable: true,
  36766. configurable: true
  36767. });
  36768. // Static constants associated to the image processing.
  36769. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  36770. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  36771. __decorate([
  36772. BABYLON.serializeAsColorCurves()
  36773. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  36774. __decorate([
  36775. BABYLON.serialize()
  36776. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  36777. __decorate([
  36778. BABYLON.serializeAsTexture()
  36779. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  36780. __decorate([
  36781. BABYLON.serialize()
  36782. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  36783. __decorate([
  36784. BABYLON.serialize()
  36785. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  36786. __decorate([
  36787. BABYLON.serialize()
  36788. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  36789. __decorate([
  36790. BABYLON.serialize()
  36791. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  36792. __decorate([
  36793. BABYLON.serialize()
  36794. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  36795. __decorate([
  36796. BABYLON.serialize()
  36797. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  36798. __decorate([
  36799. BABYLON.serialize()
  36800. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  36801. __decorate([
  36802. BABYLON.serialize()
  36803. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  36804. __decorate([
  36805. BABYLON.serialize()
  36806. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  36807. __decorate([
  36808. BABYLON.serialize()
  36809. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  36810. __decorate([
  36811. BABYLON.serializeAsColor4()
  36812. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  36813. __decorate([
  36814. BABYLON.serialize()
  36815. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  36816. __decorate([
  36817. BABYLON.serialize()
  36818. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  36819. __decorate([
  36820. BABYLON.serialize()
  36821. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  36822. __decorate([
  36823. BABYLON.serialize()
  36824. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  36825. __decorate([
  36826. BABYLON.serialize()
  36827. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  36828. return ImageProcessingConfiguration;
  36829. }());
  36830. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  36831. })(BABYLON || (BABYLON = {}));
  36832. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  36833. var BABYLON;
  36834. (function (BABYLON) {
  36835. /**
  36836. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  36837. * It can help converting any input color in a desired output one. This can then be used to create effects
  36838. * from sepia, black and white to sixties or futuristic rendering...
  36839. *
  36840. * The only supported format is currently 3dl.
  36841. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  36842. */
  36843. var ColorGradingTexture = /** @class */ (function (_super) {
  36844. __extends(ColorGradingTexture, _super);
  36845. /**
  36846. * Instantiates a ColorGradingTexture from the following parameters.
  36847. *
  36848. * @param url The location of the color gradind data (currently only supporting 3dl)
  36849. * @param scene The scene the texture will be used in
  36850. */
  36851. function ColorGradingTexture(url, scene) {
  36852. var _this = _super.call(this, scene) || this;
  36853. if (!url) {
  36854. return _this;
  36855. }
  36856. _this._engine = scene.getEngine();
  36857. _this._textureMatrix = BABYLON.Matrix.Identity();
  36858. _this.name = url;
  36859. _this.url = url;
  36860. _this.hasAlpha = false;
  36861. _this.isCube = false;
  36862. _this.is3D = _this._engine.webGLVersion > 1;
  36863. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36864. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36865. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36866. _this.anisotropicFilteringLevel = 1;
  36867. _this._texture = _this._getFromCache(url, true);
  36868. if (!_this._texture) {
  36869. if (!scene.useDelayedTextureLoading) {
  36870. _this.loadTexture();
  36871. }
  36872. else {
  36873. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36874. }
  36875. }
  36876. return _this;
  36877. }
  36878. /**
  36879. * Returns the texture matrix used in most of the material.
  36880. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  36881. */
  36882. ColorGradingTexture.prototype.getTextureMatrix = function () {
  36883. return this._textureMatrix;
  36884. };
  36885. /**
  36886. * Occurs when the file being loaded is a .3dl LUT file.
  36887. */
  36888. ColorGradingTexture.prototype.load3dlTexture = function () {
  36889. var engine = this._engine;
  36890. var texture;
  36891. if (engine.webGLVersion === 1) {
  36892. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36893. }
  36894. else {
  36895. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36896. }
  36897. this._texture = texture;
  36898. var callback = function (text) {
  36899. if (typeof text !== "string") {
  36900. return;
  36901. }
  36902. var data = null;
  36903. var tempData = null;
  36904. var line;
  36905. var lines = text.split('\n');
  36906. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  36907. var maxColor = 0;
  36908. for (var i = 0; i < lines.length; i++) {
  36909. line = lines[i];
  36910. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  36911. continue;
  36912. if (line.indexOf('#') === 0)
  36913. continue;
  36914. var words = line.split(" ");
  36915. if (size === 0) {
  36916. // Number of space + one
  36917. size = words.length;
  36918. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  36919. tempData = new Float32Array(size * size * size * 4);
  36920. continue;
  36921. }
  36922. if (size != 0) {
  36923. var r = Math.max(parseInt(words[0]), 0);
  36924. var g = Math.max(parseInt(words[1]), 0);
  36925. var b = Math.max(parseInt(words[2]), 0);
  36926. maxColor = Math.max(r, maxColor);
  36927. maxColor = Math.max(g, maxColor);
  36928. maxColor = Math.max(b, maxColor);
  36929. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  36930. if (tempData) {
  36931. tempData[pixelStorageIndex + 0] = r;
  36932. tempData[pixelStorageIndex + 1] = g;
  36933. tempData[pixelStorageIndex + 2] = b;
  36934. }
  36935. pixelIndexSlice++;
  36936. if (pixelIndexSlice % size == 0) {
  36937. pixelIndexH++;
  36938. pixelIndexSlice = 0;
  36939. if (pixelIndexH % size == 0) {
  36940. pixelIndexW++;
  36941. pixelIndexH = 0;
  36942. }
  36943. }
  36944. }
  36945. }
  36946. if (tempData && data) {
  36947. for (var i = 0; i < tempData.length; i++) {
  36948. if (i > 0 && (i + 1) % 4 === 0) {
  36949. data[i] = 255;
  36950. }
  36951. else {
  36952. var value = tempData[i];
  36953. data[i] = (value / maxColor * 255);
  36954. }
  36955. }
  36956. }
  36957. if (texture.is3D) {
  36958. texture.updateSize(size, size, size);
  36959. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36960. }
  36961. else {
  36962. texture.updateSize(size * size, size);
  36963. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36964. }
  36965. };
  36966. var scene = this.getScene();
  36967. if (scene) {
  36968. scene._loadFile(this.url, callback);
  36969. }
  36970. else {
  36971. this._engine._loadFile(this.url, callback);
  36972. }
  36973. return this._texture;
  36974. };
  36975. /**
  36976. * Starts the loading process of the texture.
  36977. */
  36978. ColorGradingTexture.prototype.loadTexture = function () {
  36979. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  36980. this.load3dlTexture();
  36981. }
  36982. };
  36983. /**
  36984. * Clones the color gradind texture.
  36985. */
  36986. ColorGradingTexture.prototype.clone = function () {
  36987. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  36988. // Base texture
  36989. newTexture.level = this.level;
  36990. return newTexture;
  36991. };
  36992. /**
  36993. * Called during delayed load for textures.
  36994. */
  36995. ColorGradingTexture.prototype.delayLoad = function () {
  36996. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  36997. return;
  36998. }
  36999. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37000. this._texture = this._getFromCache(this.url, true);
  37001. if (!this._texture) {
  37002. this.loadTexture();
  37003. }
  37004. };
  37005. /**
  37006. * Parses a color grading texture serialized by Babylon.
  37007. * @param parsedTexture The texture information being parsedTexture
  37008. * @param scene The scene to load the texture in
  37009. * @param rootUrl The root url of the data assets to load
  37010. * @return A color gradind texture
  37011. */
  37012. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37013. var texture = null;
  37014. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37015. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37016. texture.name = parsedTexture.name;
  37017. texture.level = parsedTexture.level;
  37018. }
  37019. return texture;
  37020. };
  37021. /**
  37022. * Serializes the LUT texture to json format.
  37023. */
  37024. ColorGradingTexture.prototype.serialize = function () {
  37025. if (!this.name) {
  37026. return null;
  37027. }
  37028. var serializationObject = {};
  37029. serializationObject.name = this.name;
  37030. serializationObject.level = this.level;
  37031. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37032. return serializationObject;
  37033. };
  37034. /**
  37035. * Empty line regex stored for GC.
  37036. */
  37037. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37038. return ColorGradingTexture;
  37039. }(BABYLON.BaseTexture));
  37040. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37041. })(BABYLON || (BABYLON = {}));
  37042. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37043. var BABYLON;
  37044. (function (BABYLON) {
  37045. /**
  37046. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37047. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37048. * 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;
  37049. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37050. */
  37051. var ColorCurves = /** @class */ (function () {
  37052. function ColorCurves() {
  37053. this._dirty = true;
  37054. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37055. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37056. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37057. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37058. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37059. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37060. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37061. this._globalHue = 30;
  37062. this._globalDensity = 0;
  37063. this._globalSaturation = 0;
  37064. this._globalExposure = 0;
  37065. this._highlightsHue = 30;
  37066. this._highlightsDensity = 0;
  37067. this._highlightsSaturation = 0;
  37068. this._highlightsExposure = 0;
  37069. this._midtonesHue = 30;
  37070. this._midtonesDensity = 0;
  37071. this._midtonesSaturation = 0;
  37072. this._midtonesExposure = 0;
  37073. this._shadowsHue = 30;
  37074. this._shadowsDensity = 0;
  37075. this._shadowsSaturation = 0;
  37076. this._shadowsExposure = 0;
  37077. }
  37078. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37079. /**
  37080. * Gets the global Hue value.
  37081. * 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).
  37082. */
  37083. get: function () {
  37084. return this._globalHue;
  37085. },
  37086. /**
  37087. * Sets the global Hue value.
  37088. * 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).
  37089. */
  37090. set: function (value) {
  37091. this._globalHue = value;
  37092. this._dirty = true;
  37093. },
  37094. enumerable: true,
  37095. configurable: true
  37096. });
  37097. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37098. /**
  37099. * Gets the global Density value.
  37100. * 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.
  37101. * Values less than zero provide a filter of opposite hue.
  37102. */
  37103. get: function () {
  37104. return this._globalDensity;
  37105. },
  37106. /**
  37107. * Sets the global Density value.
  37108. * 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.
  37109. * Values less than zero provide a filter of opposite hue.
  37110. */
  37111. set: function (value) {
  37112. this._globalDensity = value;
  37113. this._dirty = true;
  37114. },
  37115. enumerable: true,
  37116. configurable: true
  37117. });
  37118. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37119. /**
  37120. * Gets the global Saturation value.
  37121. * 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.
  37122. */
  37123. get: function () {
  37124. return this._globalSaturation;
  37125. },
  37126. /**
  37127. * Sets the global Saturation value.
  37128. * 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.
  37129. */
  37130. set: function (value) {
  37131. this._globalSaturation = value;
  37132. this._dirty = true;
  37133. },
  37134. enumerable: true,
  37135. configurable: true
  37136. });
  37137. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37138. /**
  37139. * Gets the highlights Hue value.
  37140. * 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).
  37141. */
  37142. get: function () {
  37143. return this._highlightsHue;
  37144. },
  37145. /**
  37146. * Sets the highlights Hue value.
  37147. * 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).
  37148. */
  37149. set: function (value) {
  37150. this._highlightsHue = value;
  37151. this._dirty = true;
  37152. },
  37153. enumerable: true,
  37154. configurable: true
  37155. });
  37156. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37157. /**
  37158. * Gets the highlights Density value.
  37159. * 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.
  37160. * Values less than zero provide a filter of opposite hue.
  37161. */
  37162. get: function () {
  37163. return this._highlightsDensity;
  37164. },
  37165. /**
  37166. * Sets the highlights Density value.
  37167. * 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.
  37168. * Values less than zero provide a filter of opposite hue.
  37169. */
  37170. set: function (value) {
  37171. this._highlightsDensity = value;
  37172. this._dirty = true;
  37173. },
  37174. enumerable: true,
  37175. configurable: true
  37176. });
  37177. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37178. /**
  37179. * Gets the highlights Saturation value.
  37180. * 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.
  37181. */
  37182. get: function () {
  37183. return this._highlightsSaturation;
  37184. },
  37185. /**
  37186. * Sets the highlights Saturation value.
  37187. * 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.
  37188. */
  37189. set: function (value) {
  37190. this._highlightsSaturation = value;
  37191. this._dirty = true;
  37192. },
  37193. enumerable: true,
  37194. configurable: true
  37195. });
  37196. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37197. /**
  37198. * Gets the highlights Exposure value.
  37199. * 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.
  37200. */
  37201. get: function () {
  37202. return this._highlightsExposure;
  37203. },
  37204. /**
  37205. * Sets the highlights Exposure value.
  37206. * 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.
  37207. */
  37208. set: function (value) {
  37209. this._highlightsExposure = value;
  37210. this._dirty = true;
  37211. },
  37212. enumerable: true,
  37213. configurable: true
  37214. });
  37215. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37216. /**
  37217. * Gets the midtones Hue value.
  37218. * 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).
  37219. */
  37220. get: function () {
  37221. return this._midtonesHue;
  37222. },
  37223. /**
  37224. * Sets the midtones Hue value.
  37225. * 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).
  37226. */
  37227. set: function (value) {
  37228. this._midtonesHue = value;
  37229. this._dirty = true;
  37230. },
  37231. enumerable: true,
  37232. configurable: true
  37233. });
  37234. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37235. /**
  37236. * Gets the midtones Density value.
  37237. * 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.
  37238. * Values less than zero provide a filter of opposite hue.
  37239. */
  37240. get: function () {
  37241. return this._midtonesDensity;
  37242. },
  37243. /**
  37244. * Sets the midtones Density value.
  37245. * 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.
  37246. * Values less than zero provide a filter of opposite hue.
  37247. */
  37248. set: function (value) {
  37249. this._midtonesDensity = value;
  37250. this._dirty = true;
  37251. },
  37252. enumerable: true,
  37253. configurable: true
  37254. });
  37255. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37256. /**
  37257. * Gets the midtones Saturation value.
  37258. * 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.
  37259. */
  37260. get: function () {
  37261. return this._midtonesSaturation;
  37262. },
  37263. /**
  37264. * Sets the midtones Saturation value.
  37265. * 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.
  37266. */
  37267. set: function (value) {
  37268. this._midtonesSaturation = value;
  37269. this._dirty = true;
  37270. },
  37271. enumerable: true,
  37272. configurable: true
  37273. });
  37274. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37275. /**
  37276. * Gets the midtones Exposure value.
  37277. * 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.
  37278. */
  37279. get: function () {
  37280. return this._midtonesExposure;
  37281. },
  37282. /**
  37283. * Sets the midtones Exposure value.
  37284. * 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.
  37285. */
  37286. set: function (value) {
  37287. this._midtonesExposure = value;
  37288. this._dirty = true;
  37289. },
  37290. enumerable: true,
  37291. configurable: true
  37292. });
  37293. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37294. /**
  37295. * Gets the shadows Hue value.
  37296. * 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).
  37297. */
  37298. get: function () {
  37299. return this._shadowsHue;
  37300. },
  37301. /**
  37302. * Sets the shadows Hue value.
  37303. * 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).
  37304. */
  37305. set: function (value) {
  37306. this._shadowsHue = value;
  37307. this._dirty = true;
  37308. },
  37309. enumerable: true,
  37310. configurable: true
  37311. });
  37312. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37313. /**
  37314. * Gets the shadows Density value.
  37315. * 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.
  37316. * Values less than zero provide a filter of opposite hue.
  37317. */
  37318. get: function () {
  37319. return this._shadowsDensity;
  37320. },
  37321. /**
  37322. * Sets the shadows Density value.
  37323. * 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.
  37324. * Values less than zero provide a filter of opposite hue.
  37325. */
  37326. set: function (value) {
  37327. this._shadowsDensity = value;
  37328. this._dirty = true;
  37329. },
  37330. enumerable: true,
  37331. configurable: true
  37332. });
  37333. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37334. /**
  37335. * Gets the shadows Saturation value.
  37336. * 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.
  37337. */
  37338. get: function () {
  37339. return this._shadowsSaturation;
  37340. },
  37341. /**
  37342. * Sets the shadows Saturation value.
  37343. * 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.
  37344. */
  37345. set: function (value) {
  37346. this._shadowsSaturation = value;
  37347. this._dirty = true;
  37348. },
  37349. enumerable: true,
  37350. configurable: true
  37351. });
  37352. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37353. /**
  37354. * Gets the shadows Exposure value.
  37355. * 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.
  37356. */
  37357. get: function () {
  37358. return this._shadowsExposure;
  37359. },
  37360. /**
  37361. * Sets the shadows Exposure value.
  37362. * 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.
  37363. */
  37364. set: function (value) {
  37365. this._shadowsExposure = value;
  37366. this._dirty = true;
  37367. },
  37368. enumerable: true,
  37369. configurable: true
  37370. });
  37371. ColorCurves.prototype.getClassName = function () {
  37372. return "ColorCurves";
  37373. };
  37374. /**
  37375. * Binds the color curves to the shader.
  37376. * @param colorCurves The color curve to bind
  37377. * @param effect The effect to bind to
  37378. */
  37379. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37380. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37381. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37382. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37383. if (colorCurves._dirty) {
  37384. colorCurves._dirty = false;
  37385. // Fill in global info.
  37386. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37387. // Compute highlights info.
  37388. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37389. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37390. // Compute midtones info.
  37391. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37392. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37393. // Compute shadows info.
  37394. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37395. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37396. // Compute deltas (neutral is midtones).
  37397. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37398. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37399. }
  37400. if (effect) {
  37401. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37402. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37403. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37404. }
  37405. };
  37406. /**
  37407. * Prepare the list of uniforms associated with the ColorCurves effects.
  37408. * @param uniformsList The list of uniforms used in the effect
  37409. */
  37410. ColorCurves.PrepareUniforms = function (uniformsList) {
  37411. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37412. };
  37413. /**
  37414. * Returns color grading data based on a hue, density, saturation and exposure value.
  37415. * @param filterHue The hue of the color filter.
  37416. * @param filterDensity The density of the color filter.
  37417. * @param saturation The saturation.
  37418. * @param exposure The exposure.
  37419. * @param result The result data container.
  37420. */
  37421. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37422. if (hue == null) {
  37423. return;
  37424. }
  37425. hue = ColorCurves.clamp(hue, 0, 360);
  37426. density = ColorCurves.clamp(density, -100, 100);
  37427. saturation = ColorCurves.clamp(saturation, -100, 100);
  37428. exposure = ColorCurves.clamp(exposure, -100, 100);
  37429. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37430. // so that the maximum filter density is only 50% control. This provides fine control
  37431. // for small values and reasonable range.
  37432. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37433. density *= 0.5;
  37434. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37435. if (density < 0) {
  37436. density *= -1;
  37437. hue = (hue + 180) % 360;
  37438. }
  37439. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37440. result.scaleToRef(2, result);
  37441. result.a = 1 + 0.01 * saturation;
  37442. };
  37443. /**
  37444. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37445. * @param value The input slider value in range [-100,100].
  37446. * @returns Adjusted value.
  37447. */
  37448. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37449. value /= 100;
  37450. var x = Math.abs(value);
  37451. x = Math.pow(x, 2);
  37452. if (value < 0) {
  37453. x *= -1;
  37454. }
  37455. x *= 100;
  37456. return x;
  37457. };
  37458. /**
  37459. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37460. * @param hue The hue (H) input.
  37461. * @param saturation The saturation (S) input.
  37462. * @param brightness The brightness (B) input.
  37463. * @result An RGBA color represented as Vector4.
  37464. */
  37465. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37466. var h = ColorCurves.clamp(hue, 0, 360);
  37467. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37468. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37469. if (s === 0) {
  37470. result.r = v;
  37471. result.g = v;
  37472. result.b = v;
  37473. }
  37474. else {
  37475. // sector 0 to 5
  37476. h /= 60;
  37477. var i = Math.floor(h);
  37478. // fractional part of h
  37479. var f = h - i;
  37480. var p = v * (1 - s);
  37481. var q = v * (1 - s * f);
  37482. var t = v * (1 - s * (1 - f));
  37483. switch (i) {
  37484. case 0:
  37485. result.r = v;
  37486. result.g = t;
  37487. result.b = p;
  37488. break;
  37489. case 1:
  37490. result.r = q;
  37491. result.g = v;
  37492. result.b = p;
  37493. break;
  37494. case 2:
  37495. result.r = p;
  37496. result.g = v;
  37497. result.b = t;
  37498. break;
  37499. case 3:
  37500. result.r = p;
  37501. result.g = q;
  37502. result.b = v;
  37503. break;
  37504. case 4:
  37505. result.r = t;
  37506. result.g = p;
  37507. result.b = v;
  37508. break;
  37509. default:// case 5:
  37510. result.r = v;
  37511. result.g = p;
  37512. result.b = q;
  37513. break;
  37514. }
  37515. }
  37516. result.a = 1;
  37517. };
  37518. /**
  37519. * Returns a value clamped between min and max
  37520. * @param value The value to clamp
  37521. * @param min The minimum of value
  37522. * @param max The maximum of value
  37523. * @returns The clamped value.
  37524. */
  37525. ColorCurves.clamp = function (value, min, max) {
  37526. return Math.min(Math.max(value, min), max);
  37527. };
  37528. /**
  37529. * Clones the current color curve instance.
  37530. * @return The cloned curves
  37531. */
  37532. ColorCurves.prototype.clone = function () {
  37533. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  37534. };
  37535. /**
  37536. * Serializes the current color curve instance to a json representation.
  37537. * @return a JSON representation
  37538. */
  37539. ColorCurves.prototype.serialize = function () {
  37540. return BABYLON.SerializationHelper.Serialize(this);
  37541. };
  37542. /**
  37543. * Parses the color curve from a json representation.
  37544. * @param source the JSON source to parse
  37545. * @return The parsed curves
  37546. */
  37547. ColorCurves.Parse = function (source) {
  37548. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  37549. };
  37550. __decorate([
  37551. BABYLON.serialize()
  37552. ], ColorCurves.prototype, "_globalHue", void 0);
  37553. __decorate([
  37554. BABYLON.serialize()
  37555. ], ColorCurves.prototype, "_globalDensity", void 0);
  37556. __decorate([
  37557. BABYLON.serialize()
  37558. ], ColorCurves.prototype, "_globalSaturation", void 0);
  37559. __decorate([
  37560. BABYLON.serialize()
  37561. ], ColorCurves.prototype, "_globalExposure", void 0);
  37562. __decorate([
  37563. BABYLON.serialize()
  37564. ], ColorCurves.prototype, "_highlightsHue", void 0);
  37565. __decorate([
  37566. BABYLON.serialize()
  37567. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  37568. __decorate([
  37569. BABYLON.serialize()
  37570. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  37571. __decorate([
  37572. BABYLON.serialize()
  37573. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  37574. __decorate([
  37575. BABYLON.serialize()
  37576. ], ColorCurves.prototype, "_midtonesHue", void 0);
  37577. __decorate([
  37578. BABYLON.serialize()
  37579. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  37580. __decorate([
  37581. BABYLON.serialize()
  37582. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  37583. __decorate([
  37584. BABYLON.serialize()
  37585. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  37586. return ColorCurves;
  37587. }());
  37588. BABYLON.ColorCurves = ColorCurves;
  37589. })(BABYLON || (BABYLON = {}));
  37590. //# sourceMappingURL=babylon.colorCurves.js.map
  37591. //# sourceMappingURL=babylon.behavior.js.map
  37592. var BABYLON;
  37593. (function (BABYLON) {
  37594. /**
  37595. * "Static Class" containing the most commonly used helper while dealing with material for
  37596. * rendering purpose.
  37597. *
  37598. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  37599. *
  37600. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  37601. */
  37602. var MaterialHelper = /** @class */ (function () {
  37603. function MaterialHelper() {
  37604. }
  37605. /**
  37606. * Bind the current view position to an effect.
  37607. * @param effect The effect to be bound
  37608. * @param scene The scene the eyes position is used from
  37609. */
  37610. MaterialHelper.BindEyePosition = function (effect, scene) {
  37611. if (scene._forcedViewPosition) {
  37612. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  37613. return;
  37614. }
  37615. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37616. };
  37617. /**
  37618. * Helps preparing the defines values about the UVs in used in the effect.
  37619. * UVs are shared as much as we can accross chanels in the shaders.
  37620. * @param texture The texture we are preparing the UVs for
  37621. * @param defines The defines to update
  37622. * @param key The chanel key "diffuse", "specular"... used in the shader
  37623. */
  37624. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  37625. defines._needUVs = true;
  37626. defines[key] = true;
  37627. if (texture.getTextureMatrix().isIdentity(true)) {
  37628. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  37629. if (texture.coordinatesIndex === 0) {
  37630. defines["MAINUV1"] = true;
  37631. }
  37632. else {
  37633. defines["MAINUV2"] = true;
  37634. }
  37635. }
  37636. else {
  37637. defines[key + "DIRECTUV"] = 0;
  37638. }
  37639. };
  37640. /**
  37641. * Binds a texture matrix value to its corrsponding uniform
  37642. * @param texture The texture to bind the matrix for
  37643. * @param uniformBuffer The uniform buffer receivin the data
  37644. * @param key The chanel key "diffuse", "specular"... used in the shader
  37645. */
  37646. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  37647. var matrix = texture.getTextureMatrix();
  37648. if (!matrix.isIdentity(true)) {
  37649. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  37650. }
  37651. };
  37652. /**
  37653. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  37654. * @param mesh defines the current mesh
  37655. * @param scene defines the current scene
  37656. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  37657. * @param pointsCloud defines if point cloud rendering has to be turned on
  37658. * @param fogEnabled defines if fog has to be turned on
  37659. * @param alphaTest defines if alpha testing has to be turned on
  37660. * @param defines defines the current list of defines
  37661. */
  37662. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  37663. if (defines._areMiscDirty) {
  37664. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  37665. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  37666. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  37667. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  37668. defines["ALPHATEST"] = alphaTest;
  37669. }
  37670. };
  37671. /**
  37672. * Helper used to prepare the list of defines associated with frame values for shader compilation
  37673. * @param scene defines the current scene
  37674. * @param engine defines the current engine
  37675. * @param defines specifies the list of active defines
  37676. * @param useInstances defines if instances have to be turned on
  37677. * @param useClipPlane defines if clip plane have to be turned on
  37678. */
  37679. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  37680. if (useClipPlane === void 0) { useClipPlane = null; }
  37681. var changed = false;
  37682. if (useClipPlane == null) {
  37683. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  37684. }
  37685. if (defines["CLIPPLANE"] !== useClipPlane) {
  37686. defines["CLIPPLANE"] = useClipPlane;
  37687. changed = true;
  37688. }
  37689. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  37690. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  37691. changed = true;
  37692. }
  37693. if (defines["INSTANCES"] !== useInstances) {
  37694. defines["INSTANCES"] = useInstances;
  37695. changed = true;
  37696. }
  37697. if (changed) {
  37698. defines.markAsUnprocessed();
  37699. }
  37700. };
  37701. /**
  37702. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  37703. * @param mesh The mesh containing the geometry data we will draw
  37704. * @param defines The defines to update
  37705. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  37706. * @param useBones Precise whether bones should be used or not (override mesh info)
  37707. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  37708. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  37709. * @returns false if defines are considered not dirty and have not been checked
  37710. */
  37711. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  37712. if (useMorphTargets === void 0) { useMorphTargets = false; }
  37713. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  37714. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  37715. return false;
  37716. }
  37717. defines._normals = defines._needNormals;
  37718. defines._uvs = defines._needUVs;
  37719. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  37720. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37721. defines["TANGENT"] = true;
  37722. }
  37723. if (defines._needUVs) {
  37724. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  37725. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  37726. }
  37727. else {
  37728. defines["UV1"] = false;
  37729. defines["UV2"] = false;
  37730. }
  37731. if (useVertexColor) {
  37732. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  37733. defines["VERTEXCOLOR"] = hasVertexColors;
  37734. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  37735. }
  37736. if (useBones) {
  37737. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37738. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  37739. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  37740. }
  37741. else {
  37742. defines["NUM_BONE_INFLUENCERS"] = 0;
  37743. defines["BonesPerMesh"] = 0;
  37744. }
  37745. }
  37746. if (useMorphTargets) {
  37747. var manager = mesh.morphTargetManager;
  37748. if (manager) {
  37749. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  37750. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  37751. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  37752. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  37753. }
  37754. else {
  37755. defines["MORPHTARGETS_TANGENT"] = false;
  37756. defines["MORPHTARGETS_NORMAL"] = false;
  37757. defines["MORPHTARGETS"] = false;
  37758. defines["NUM_MORPH_INFLUENCERS"] = 0;
  37759. }
  37760. }
  37761. return true;
  37762. };
  37763. /**
  37764. * Prepares the defines related to the light information passed in parameter
  37765. * @param scene The scene we are intending to draw
  37766. * @param mesh The mesh the effect is compiling for
  37767. * @param defines The defines to update
  37768. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  37769. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  37770. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  37771. * @returns true if normals will be required for the rest of the effect
  37772. */
  37773. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  37774. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37775. if (disableLighting === void 0) { disableLighting = false; }
  37776. if (!defines._areLightsDirty) {
  37777. return defines._needNormals;
  37778. }
  37779. var lightIndex = 0;
  37780. var needNormals = false;
  37781. var needRebuild = false;
  37782. var lightmapMode = false;
  37783. var shadowEnabled = false;
  37784. var specularEnabled = false;
  37785. if (scene.lightsEnabled && !disableLighting) {
  37786. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  37787. var light = _a[_i];
  37788. needNormals = true;
  37789. if (defines["LIGHT" + lightIndex] === undefined) {
  37790. needRebuild = true;
  37791. }
  37792. defines["LIGHT" + lightIndex] = true;
  37793. defines["SPOTLIGHT" + lightIndex] = false;
  37794. defines["HEMILIGHT" + lightIndex] = false;
  37795. defines["POINTLIGHT" + lightIndex] = false;
  37796. defines["DIRLIGHT" + lightIndex] = false;
  37797. var type;
  37798. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  37799. type = "SPOTLIGHT" + lightIndex;
  37800. var spotLight = light;
  37801. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  37802. }
  37803. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  37804. type = "HEMILIGHT" + lightIndex;
  37805. }
  37806. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  37807. type = "POINTLIGHT" + lightIndex;
  37808. }
  37809. else {
  37810. type = "DIRLIGHT" + lightIndex;
  37811. }
  37812. defines[type] = true;
  37813. // Specular
  37814. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  37815. specularEnabled = true;
  37816. }
  37817. // Shadows
  37818. defines["SHADOW" + lightIndex] = false;
  37819. defines["SHADOWPCF" + lightIndex] = false;
  37820. defines["SHADOWESM" + lightIndex] = false;
  37821. defines["SHADOWCUBE" + lightIndex] = false;
  37822. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  37823. var shadowGenerator = light.getShadowGenerator();
  37824. if (shadowGenerator) {
  37825. shadowEnabled = true;
  37826. shadowGenerator.prepareDefines(defines, lightIndex);
  37827. }
  37828. }
  37829. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  37830. lightmapMode = true;
  37831. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  37832. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  37833. }
  37834. else {
  37835. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  37836. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  37837. }
  37838. lightIndex++;
  37839. if (lightIndex === maxSimultaneousLights)
  37840. break;
  37841. }
  37842. }
  37843. defines["SPECULARTERM"] = specularEnabled;
  37844. defines["SHADOWS"] = shadowEnabled;
  37845. // Resetting all other lights if any
  37846. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  37847. if (defines["LIGHT" + index] !== undefined) {
  37848. defines["LIGHT" + index] = false;
  37849. defines["HEMILIGHT" + lightIndex] = false;
  37850. defines["POINTLIGHT" + lightIndex] = false;
  37851. defines["DIRLIGHT" + lightIndex] = false;
  37852. defines["SPOTLIGHT" + lightIndex] = false;
  37853. defines["SHADOW" + lightIndex] = false;
  37854. }
  37855. }
  37856. var caps = scene.getEngine().getCaps();
  37857. if (defines["SHADOWFLOAT"] === undefined) {
  37858. needRebuild = true;
  37859. }
  37860. defines["SHADOWFLOAT"] = shadowEnabled &&
  37861. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  37862. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  37863. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  37864. if (needRebuild) {
  37865. defines.rebuild();
  37866. }
  37867. return needNormals;
  37868. };
  37869. /**
  37870. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  37871. * that won t be acctive due to defines being turned off.
  37872. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  37873. * @param samplersList The samplers list
  37874. * @param defines The defines helping in the list generation
  37875. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  37876. */
  37877. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  37878. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37879. var uniformsList;
  37880. var uniformBuffersList = null;
  37881. if (uniformsListOrOptions.uniformsNames) {
  37882. var options = uniformsListOrOptions;
  37883. uniformsList = options.uniformsNames;
  37884. uniformBuffersList = options.uniformBuffersNames;
  37885. samplersList = options.samplers;
  37886. defines = options.defines;
  37887. maxSimultaneousLights = options.maxSimultaneousLights;
  37888. }
  37889. else {
  37890. uniformsList = uniformsListOrOptions;
  37891. if (!samplersList) {
  37892. samplersList = [];
  37893. }
  37894. }
  37895. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37896. if (!defines["LIGHT" + lightIndex]) {
  37897. break;
  37898. }
  37899. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  37900. if (uniformBuffersList) {
  37901. uniformBuffersList.push("Light" + lightIndex);
  37902. }
  37903. samplersList.push("shadowSampler" + lightIndex);
  37904. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  37905. samplersList.push("projectionLightSampler" + lightIndex);
  37906. uniformsList.push("textureProjectionMatrix" + lightIndex);
  37907. }
  37908. }
  37909. if (defines["NUM_MORPH_INFLUENCERS"]) {
  37910. uniformsList.push("morphTargetInfluences");
  37911. }
  37912. };
  37913. /**
  37914. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  37915. * @param defines The defines to update while falling back
  37916. * @param fallbacks The authorized effect fallbacks
  37917. * @param maxSimultaneousLights The maximum number of lights allowed
  37918. * @param rank the current rank of the Effect
  37919. * @returns The newly affected rank
  37920. */
  37921. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  37922. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37923. if (rank === void 0) { rank = 0; }
  37924. var lightFallbackRank = 0;
  37925. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37926. if (!defines["LIGHT" + lightIndex]) {
  37927. break;
  37928. }
  37929. if (lightIndex > 0) {
  37930. lightFallbackRank = rank + lightIndex;
  37931. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  37932. }
  37933. if (!defines["SHADOWS"]) {
  37934. if (defines["SHADOW" + lightIndex]) {
  37935. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  37936. }
  37937. if (defines["SHADOWPCF" + lightIndex]) {
  37938. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  37939. }
  37940. if (defines["SHADOWESM" + lightIndex]) {
  37941. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  37942. }
  37943. }
  37944. }
  37945. return lightFallbackRank++;
  37946. };
  37947. /**
  37948. * Prepares the list of attributes required for morph targets according to the effect defines.
  37949. * @param attribs The current list of supported attribs
  37950. * @param mesh The mesh to prepare the morph targets attributes for
  37951. * @param defines The current Defines of the effect
  37952. */
  37953. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  37954. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  37955. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  37956. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  37957. var manager = mesh.morphTargetManager;
  37958. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  37959. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  37960. for (var index = 0; index < influencers; index++) {
  37961. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  37962. if (normal) {
  37963. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  37964. }
  37965. if (tangent) {
  37966. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  37967. }
  37968. if (attribs.length > maxAttributesCount) {
  37969. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  37970. }
  37971. }
  37972. }
  37973. };
  37974. /**
  37975. * Prepares the list of attributes required for bones according to the effect defines.
  37976. * @param attribs The current list of supported attribs
  37977. * @param mesh The mesh to prepare the bones attributes for
  37978. * @param defines The current Defines of the effect
  37979. * @param fallbacks The current efffect fallback strategy
  37980. */
  37981. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  37982. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  37983. fallbacks.addCPUSkinningFallback(0, mesh);
  37984. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37985. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37986. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  37987. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37988. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37989. }
  37990. }
  37991. };
  37992. /**
  37993. * Prepares the list of attributes required for instances according to the effect defines.
  37994. * @param attribs The current list of supported attribs
  37995. * @param defines The current Defines of the effect
  37996. */
  37997. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  37998. if (defines["INSTANCES"]) {
  37999. attribs.push("world0");
  38000. attribs.push("world1");
  38001. attribs.push("world2");
  38002. attribs.push("world3");
  38003. }
  38004. };
  38005. /**
  38006. * Binds the light shadow information to the effect for the given mesh.
  38007. * @param light The light containing the generator
  38008. * @param scene The scene the lights belongs to
  38009. * @param mesh The mesh we are binding the information to render
  38010. * @param lightIndex The light index in the effect used to render the mesh
  38011. * @param effect The effect we are binding the data to
  38012. */
  38013. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38014. if (light.shadowEnabled && mesh.receiveShadows) {
  38015. var shadowGenerator = light.getShadowGenerator();
  38016. if (shadowGenerator) {
  38017. shadowGenerator.bindShadowLight(lightIndex, effect);
  38018. }
  38019. }
  38020. };
  38021. /**
  38022. * Binds the light information to the effect.
  38023. * @param light The light containing the generator
  38024. * @param effect The effect we are binding the data to
  38025. * @param lightIndex The light index in the effect used to render
  38026. */
  38027. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38028. light.transferToEffect(effect, lightIndex + "");
  38029. };
  38030. /**
  38031. * Binds the lights information from the scene to the effect for the given mesh.
  38032. * @param scene The scene the lights belongs to
  38033. * @param mesh The mesh we are binding the information to render
  38034. * @param effect The effect we are binding the data to
  38035. * @param defines The generated defines for the effect
  38036. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38037. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38038. */
  38039. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38040. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38041. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38042. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38043. for (var i = 0; i < len; i++) {
  38044. var light = mesh._lightSources[i];
  38045. var iAsString = i.toString();
  38046. var scaledIntensity = light.getScaledIntensity();
  38047. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38048. MaterialHelper.BindLightProperties(light, effect, i);
  38049. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38050. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38051. if (defines["SPECULARTERM"]) {
  38052. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38053. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38054. }
  38055. // Shadows
  38056. if (scene.shadowsEnabled) {
  38057. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38058. }
  38059. light._uniformBuffer.update();
  38060. }
  38061. };
  38062. /**
  38063. * Binds the fog information from the scene to the effect for the given mesh.
  38064. * @param scene The scene the lights belongs to
  38065. * @param mesh The mesh we are binding the information to render
  38066. * @param effect The effect we are binding the data to
  38067. */
  38068. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38069. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38070. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38071. effect.setColor3("vFogColor", scene.fogColor);
  38072. }
  38073. };
  38074. /**
  38075. * Binds the bones information from the mesh to the effect.
  38076. * @param mesh The mesh we are binding the information to render
  38077. * @param effect The effect we are binding the data to
  38078. */
  38079. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38080. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38081. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38082. if (matrices && effect) {
  38083. effect.setMatrices("mBones", matrices);
  38084. }
  38085. }
  38086. };
  38087. /**
  38088. * Binds the morph targets information from the mesh to the effect.
  38089. * @param abstractMesh The mesh we are binding the information to render
  38090. * @param effect The effect we are binding the data to
  38091. */
  38092. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38093. var manager = abstractMesh.morphTargetManager;
  38094. if (!abstractMesh || !manager) {
  38095. return;
  38096. }
  38097. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38098. };
  38099. /**
  38100. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38101. * @param defines The generated defines used in the effect
  38102. * @param effect The effect we are binding the data to
  38103. * @param scene The scene we are willing to render with logarithmic scale for
  38104. */
  38105. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38106. if (defines["LOGARITHMICDEPTH"]) {
  38107. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38108. }
  38109. };
  38110. /**
  38111. * Binds the clip plane information from the scene to the effect.
  38112. * @param scene The scene the clip plane information are extracted from
  38113. * @param effect The effect we are binding the data to
  38114. */
  38115. MaterialHelper.BindClipPlane = function (effect, scene) {
  38116. if (scene.clipPlane) {
  38117. var clipPlane = scene.clipPlane;
  38118. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38119. }
  38120. };
  38121. return MaterialHelper;
  38122. }());
  38123. BABYLON.MaterialHelper = MaterialHelper;
  38124. })(BABYLON || (BABYLON = {}));
  38125. //# sourceMappingURL=babylon.materialHelper.js.map
  38126. var BABYLON;
  38127. (function (BABYLON) {
  38128. var PushMaterial = /** @class */ (function (_super) {
  38129. __extends(PushMaterial, _super);
  38130. function PushMaterial(name, scene) {
  38131. var _this = _super.call(this, name, scene) || this;
  38132. _this._normalMatrix = new BABYLON.Matrix();
  38133. _this.storeEffectOnSubMeshes = true;
  38134. return _this;
  38135. }
  38136. PushMaterial.prototype.getEffect = function () {
  38137. return this._activeEffect;
  38138. };
  38139. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38140. if (!mesh) {
  38141. return false;
  38142. }
  38143. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38144. return true;
  38145. }
  38146. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38147. };
  38148. /**
  38149. * Binds the given world matrix to the active effect
  38150. *
  38151. * @param world the matrix to bind
  38152. */
  38153. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38154. this._activeEffect.setMatrix("world", world);
  38155. };
  38156. /**
  38157. * Binds the given normal matrix to the active effect
  38158. *
  38159. * @param normalMatrix the matrix to bind
  38160. */
  38161. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38162. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38163. };
  38164. PushMaterial.prototype.bind = function (world, mesh) {
  38165. if (!mesh) {
  38166. return;
  38167. }
  38168. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38169. };
  38170. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38171. if (effect === void 0) { effect = null; }
  38172. _super.prototype._afterBind.call(this, mesh);
  38173. this.getScene()._cachedEffect = effect;
  38174. };
  38175. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38176. if (visibility === void 0) { visibility = 1; }
  38177. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38178. };
  38179. return PushMaterial;
  38180. }(BABYLON.Material));
  38181. BABYLON.PushMaterial = PushMaterial;
  38182. })(BABYLON || (BABYLON = {}));
  38183. //# sourceMappingURL=babylon.pushMaterial.js.map
  38184. var BABYLON;
  38185. (function (BABYLON) {
  38186. /** @ignore */
  38187. var StandardMaterialDefines = /** @class */ (function (_super) {
  38188. __extends(StandardMaterialDefines, _super);
  38189. function StandardMaterialDefines() {
  38190. var _this = _super.call(this) || this;
  38191. _this.MAINUV1 = false;
  38192. _this.MAINUV2 = false;
  38193. _this.DIFFUSE = false;
  38194. _this.DIFFUSEDIRECTUV = 0;
  38195. _this.AMBIENT = false;
  38196. _this.AMBIENTDIRECTUV = 0;
  38197. _this.OPACITY = false;
  38198. _this.OPACITYDIRECTUV = 0;
  38199. _this.OPACITYRGB = false;
  38200. _this.REFLECTION = false;
  38201. _this.EMISSIVE = false;
  38202. _this.EMISSIVEDIRECTUV = 0;
  38203. _this.SPECULAR = false;
  38204. _this.SPECULARDIRECTUV = 0;
  38205. _this.BUMP = false;
  38206. _this.BUMPDIRECTUV = 0;
  38207. _this.PARALLAX = false;
  38208. _this.PARALLAXOCCLUSION = false;
  38209. _this.SPECULAROVERALPHA = false;
  38210. _this.CLIPPLANE = false;
  38211. _this.ALPHATEST = false;
  38212. _this.DEPTHPREPASS = false;
  38213. _this.ALPHAFROMDIFFUSE = false;
  38214. _this.POINTSIZE = false;
  38215. _this.FOG = false;
  38216. _this.SPECULARTERM = false;
  38217. _this.DIFFUSEFRESNEL = false;
  38218. _this.OPACITYFRESNEL = false;
  38219. _this.REFLECTIONFRESNEL = false;
  38220. _this.REFRACTIONFRESNEL = false;
  38221. _this.EMISSIVEFRESNEL = false;
  38222. _this.FRESNEL = false;
  38223. _this.NORMAL = false;
  38224. _this.UV1 = false;
  38225. _this.UV2 = false;
  38226. _this.VERTEXCOLOR = false;
  38227. _this.VERTEXALPHA = false;
  38228. _this.NUM_BONE_INFLUENCERS = 0;
  38229. _this.BonesPerMesh = 0;
  38230. _this.INSTANCES = false;
  38231. _this.GLOSSINESS = false;
  38232. _this.ROUGHNESS = false;
  38233. _this.EMISSIVEASILLUMINATION = false;
  38234. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38235. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38236. _this.LIGHTMAP = false;
  38237. _this.LIGHTMAPDIRECTUV = 0;
  38238. _this.OBJECTSPACE_NORMALMAP = false;
  38239. _this.USELIGHTMAPASSHADOWMAP = false;
  38240. _this.REFLECTIONMAP_3D = false;
  38241. _this.REFLECTIONMAP_SPHERICAL = false;
  38242. _this.REFLECTIONMAP_PLANAR = false;
  38243. _this.REFLECTIONMAP_CUBIC = false;
  38244. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38245. _this.REFLECTIONMAP_PROJECTION = false;
  38246. _this.REFLECTIONMAP_SKYBOX = false;
  38247. _this.REFLECTIONMAP_EXPLICIT = false;
  38248. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38249. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38250. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38251. _this.INVERTCUBICMAP = false;
  38252. _this.LOGARITHMICDEPTH = false;
  38253. _this.REFRACTION = false;
  38254. _this.REFRACTIONMAP_3D = false;
  38255. _this.REFLECTIONOVERALPHA = false;
  38256. _this.TWOSIDEDLIGHTING = false;
  38257. _this.SHADOWFLOAT = false;
  38258. _this.MORPHTARGETS = false;
  38259. _this.MORPHTARGETS_NORMAL = false;
  38260. _this.MORPHTARGETS_TANGENT = false;
  38261. _this.NUM_MORPH_INFLUENCERS = 0;
  38262. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38263. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38264. _this.IMAGEPROCESSING = false;
  38265. _this.VIGNETTE = false;
  38266. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38267. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38268. _this.TONEMAPPING = false;
  38269. _this.CONTRAST = false;
  38270. _this.COLORCURVES = false;
  38271. _this.COLORGRADING = false;
  38272. _this.COLORGRADING3D = false;
  38273. _this.SAMPLER3DGREENDEPTH = false;
  38274. _this.SAMPLER3DBGRMAP = false;
  38275. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38276. _this.EXPOSURE = false;
  38277. _this.rebuild();
  38278. return _this;
  38279. }
  38280. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38281. var modes = [
  38282. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38283. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38284. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38285. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38286. ];
  38287. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38288. var mode = modes_1[_i];
  38289. this[mode] = (mode === modeToEnable);
  38290. }
  38291. };
  38292. return StandardMaterialDefines;
  38293. }(BABYLON.MaterialDefines));
  38294. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38295. var StandardMaterial = /** @class */ (function (_super) {
  38296. __extends(StandardMaterial, _super);
  38297. function StandardMaterial(name, scene) {
  38298. var _this = _super.call(this, name, scene) || this;
  38299. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38300. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38301. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38302. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38303. _this.specularPower = 64;
  38304. _this._useAlphaFromDiffuseTexture = false;
  38305. _this._useEmissiveAsIllumination = false;
  38306. _this._linkEmissiveWithDiffuse = false;
  38307. _this._useSpecularOverAlpha = false;
  38308. _this._useReflectionOverAlpha = false;
  38309. _this._disableLighting = false;
  38310. _this._useObjectSpaceNormalMap = false;
  38311. _this._useParallax = false;
  38312. _this._useParallaxOcclusion = false;
  38313. _this.parallaxScaleBias = 0.05;
  38314. _this._roughness = 0;
  38315. _this.indexOfRefraction = 0.98;
  38316. _this.invertRefractionY = true;
  38317. _this._useLightmapAsShadowmap = false;
  38318. _this._useReflectionFresnelFromSpecular = false;
  38319. _this._useGlossinessFromSpecularMapAlpha = false;
  38320. _this._maxSimultaneousLights = 4;
  38321. /**
  38322. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38323. */
  38324. _this._invertNormalMapX = false;
  38325. /**
  38326. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38327. */
  38328. _this._invertNormalMapY = false;
  38329. /**
  38330. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38331. */
  38332. _this._twoSidedLighting = false;
  38333. _this._renderTargets = new BABYLON.SmartArray(16);
  38334. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38335. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38336. // Setup the default processing configuration to the scene.
  38337. _this._attachImageProcessingConfiguration(null);
  38338. _this.getRenderTargetTextures = function () {
  38339. _this._renderTargets.reset();
  38340. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38341. _this._renderTargets.push(_this._reflectionTexture);
  38342. }
  38343. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38344. _this._renderTargets.push(_this._refractionTexture);
  38345. }
  38346. return _this._renderTargets;
  38347. };
  38348. return _this;
  38349. }
  38350. ;
  38351. ;
  38352. ;
  38353. ;
  38354. ;
  38355. ;
  38356. ;
  38357. ;
  38358. ;
  38359. ;
  38360. ;
  38361. ;
  38362. ;
  38363. ;
  38364. ;
  38365. ;
  38366. ;
  38367. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38368. /**
  38369. * Gets the image processing configuration used either in this material.
  38370. */
  38371. get: function () {
  38372. return this._imageProcessingConfiguration;
  38373. },
  38374. /**
  38375. * Sets the Default image processing configuration used either in the this material.
  38376. *
  38377. * If sets to null, the scene one is in use.
  38378. */
  38379. set: function (value) {
  38380. this._attachImageProcessingConfiguration(value);
  38381. // Ensure the effect will be rebuilt.
  38382. this._markAllSubMeshesAsTexturesDirty();
  38383. },
  38384. enumerable: true,
  38385. configurable: true
  38386. });
  38387. /**
  38388. * Attaches a new image processing configuration to the Standard Material.
  38389. * @param configuration
  38390. */
  38391. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38392. var _this = this;
  38393. if (configuration === this._imageProcessingConfiguration) {
  38394. return;
  38395. }
  38396. // Detaches observer.
  38397. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38398. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38399. }
  38400. // Pick the scene configuration if needed.
  38401. if (!configuration) {
  38402. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38403. }
  38404. else {
  38405. this._imageProcessingConfiguration = configuration;
  38406. }
  38407. // Attaches observer.
  38408. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38409. _this._markAllSubMeshesAsImageProcessingDirty();
  38410. });
  38411. };
  38412. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38413. /**
  38414. * Gets wether the color curves effect is enabled.
  38415. */
  38416. get: function () {
  38417. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38418. },
  38419. /**
  38420. * Sets wether the color curves effect is enabled.
  38421. */
  38422. set: function (value) {
  38423. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38424. },
  38425. enumerable: true,
  38426. configurable: true
  38427. });
  38428. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38429. /**
  38430. * Gets wether the color grading effect is enabled.
  38431. */
  38432. get: function () {
  38433. return this.imageProcessingConfiguration.colorGradingEnabled;
  38434. },
  38435. /**
  38436. * Gets wether the color grading effect is enabled.
  38437. */
  38438. set: function (value) {
  38439. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38440. },
  38441. enumerable: true,
  38442. configurable: true
  38443. });
  38444. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38445. /**
  38446. * Gets wether tonemapping is enabled or not.
  38447. */
  38448. get: function () {
  38449. return this._imageProcessingConfiguration.toneMappingEnabled;
  38450. },
  38451. /**
  38452. * Sets wether tonemapping is enabled or not
  38453. */
  38454. set: function (value) {
  38455. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38456. },
  38457. enumerable: true,
  38458. configurable: true
  38459. });
  38460. ;
  38461. ;
  38462. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38463. /**
  38464. * The camera exposure used on this material.
  38465. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38466. * This corresponds to a photographic exposure.
  38467. */
  38468. get: function () {
  38469. return this._imageProcessingConfiguration.exposure;
  38470. },
  38471. /**
  38472. * The camera exposure used on this material.
  38473. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38474. * This corresponds to a photographic exposure.
  38475. */
  38476. set: function (value) {
  38477. this._imageProcessingConfiguration.exposure = value;
  38478. },
  38479. enumerable: true,
  38480. configurable: true
  38481. });
  38482. ;
  38483. ;
  38484. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38485. /**
  38486. * Gets The camera contrast used on this material.
  38487. */
  38488. get: function () {
  38489. return this._imageProcessingConfiguration.contrast;
  38490. },
  38491. /**
  38492. * Sets The camera contrast used on this material.
  38493. */
  38494. set: function (value) {
  38495. this._imageProcessingConfiguration.contrast = value;
  38496. },
  38497. enumerable: true,
  38498. configurable: true
  38499. });
  38500. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38501. /**
  38502. * Gets the Color Grading 2D Lookup Texture.
  38503. */
  38504. get: function () {
  38505. return this._imageProcessingConfiguration.colorGradingTexture;
  38506. },
  38507. /**
  38508. * Sets the Color Grading 2D Lookup Texture.
  38509. */
  38510. set: function (value) {
  38511. this._imageProcessingConfiguration.colorGradingTexture = value;
  38512. },
  38513. enumerable: true,
  38514. configurable: true
  38515. });
  38516. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  38517. /**
  38518. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38519. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38520. * 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;
  38521. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38522. */
  38523. get: function () {
  38524. return this._imageProcessingConfiguration.colorCurves;
  38525. },
  38526. /**
  38527. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38528. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38529. * 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;
  38530. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38531. */
  38532. set: function (value) {
  38533. this._imageProcessingConfiguration.colorCurves = value;
  38534. },
  38535. enumerable: true,
  38536. configurable: true
  38537. });
  38538. StandardMaterial.prototype.getClassName = function () {
  38539. return "StandardMaterial";
  38540. };
  38541. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  38542. get: function () {
  38543. return this._useLogarithmicDepth;
  38544. },
  38545. set: function (value) {
  38546. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38547. this._markAllSubMeshesAsMiscDirty();
  38548. },
  38549. enumerable: true,
  38550. configurable: true
  38551. });
  38552. StandardMaterial.prototype.needAlphaBlending = function () {
  38553. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38554. };
  38555. StandardMaterial.prototype.needAlphaTesting = function () {
  38556. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  38557. };
  38558. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  38559. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  38560. };
  38561. StandardMaterial.prototype.getAlphaTestTexture = function () {
  38562. return this._diffuseTexture;
  38563. };
  38564. /**
  38565. * Child classes can use it to update shaders
  38566. */
  38567. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38568. if (useInstances === void 0) { useInstances = false; }
  38569. if (subMesh.effect && this.isFrozen) {
  38570. if (this._wasPreviouslyReady && subMesh.effect) {
  38571. return true;
  38572. }
  38573. }
  38574. if (!subMesh._materialDefines) {
  38575. subMesh._materialDefines = new StandardMaterialDefines();
  38576. }
  38577. var scene = this.getScene();
  38578. var defines = subMesh._materialDefines;
  38579. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38580. if (defines._renderId === scene.getRenderId()) {
  38581. return true;
  38582. }
  38583. }
  38584. var engine = scene.getEngine();
  38585. // Lights
  38586. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38587. // Textures
  38588. if (defines._areTexturesDirty) {
  38589. defines._needUVs = false;
  38590. defines.MAINUV1 = false;
  38591. defines.MAINUV2 = false;
  38592. if (scene.texturesEnabled) {
  38593. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38594. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  38595. return false;
  38596. }
  38597. else {
  38598. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  38599. }
  38600. }
  38601. else {
  38602. defines.DIFFUSE = false;
  38603. }
  38604. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38605. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38606. return false;
  38607. }
  38608. else {
  38609. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38610. }
  38611. }
  38612. else {
  38613. defines.AMBIENT = false;
  38614. }
  38615. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38616. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38617. return false;
  38618. }
  38619. else {
  38620. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38621. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38622. }
  38623. }
  38624. else {
  38625. defines.OPACITY = false;
  38626. }
  38627. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38628. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  38629. return false;
  38630. }
  38631. else {
  38632. defines._needNormals = true;
  38633. defines.REFLECTION = true;
  38634. defines.ROUGHNESS = (this._roughness > 0);
  38635. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  38636. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  38637. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  38638. switch (this._reflectionTexture.coordinatesMode) {
  38639. case BABYLON.Texture.CUBIC_MODE:
  38640. case BABYLON.Texture.INVCUBIC_MODE:
  38641. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  38642. break;
  38643. case BABYLON.Texture.EXPLICIT_MODE:
  38644. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  38645. break;
  38646. case BABYLON.Texture.PLANAR_MODE:
  38647. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  38648. break;
  38649. case BABYLON.Texture.PROJECTION_MODE:
  38650. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  38651. break;
  38652. case BABYLON.Texture.SKYBOX_MODE:
  38653. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  38654. break;
  38655. case BABYLON.Texture.SPHERICAL_MODE:
  38656. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  38657. break;
  38658. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38659. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  38660. break;
  38661. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38662. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  38663. break;
  38664. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38665. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  38666. break;
  38667. }
  38668. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  38669. }
  38670. }
  38671. else {
  38672. defines.REFLECTION = false;
  38673. }
  38674. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38675. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38676. return false;
  38677. }
  38678. else {
  38679. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38680. }
  38681. }
  38682. else {
  38683. defines.EMISSIVE = false;
  38684. }
  38685. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38686. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38687. return false;
  38688. }
  38689. else {
  38690. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38691. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38692. }
  38693. }
  38694. else {
  38695. defines.LIGHTMAP = false;
  38696. }
  38697. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38698. if (!this._specularTexture.isReadyOrNotBlocking()) {
  38699. return false;
  38700. }
  38701. else {
  38702. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  38703. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  38704. }
  38705. }
  38706. else {
  38707. defines.SPECULAR = false;
  38708. }
  38709. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  38710. // Bump texure can not be not blocking.
  38711. if (!this._bumpTexture.isReady()) {
  38712. return false;
  38713. }
  38714. else {
  38715. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38716. defines.PARALLAX = this._useParallax;
  38717. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  38718. }
  38719. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  38720. }
  38721. else {
  38722. defines.BUMP = false;
  38723. }
  38724. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38725. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38726. return false;
  38727. }
  38728. else {
  38729. defines._needUVs = true;
  38730. defines.REFRACTION = true;
  38731. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38732. }
  38733. }
  38734. else {
  38735. defines.REFRACTION = false;
  38736. }
  38737. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  38738. }
  38739. else {
  38740. defines.DIFFUSE = false;
  38741. defines.AMBIENT = false;
  38742. defines.OPACITY = false;
  38743. defines.REFLECTION = false;
  38744. defines.EMISSIVE = false;
  38745. defines.LIGHTMAP = false;
  38746. defines.BUMP = false;
  38747. defines.REFRACTION = false;
  38748. }
  38749. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  38750. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  38751. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  38752. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38753. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38754. }
  38755. if (defines._areImageProcessingDirty) {
  38756. if (!this._imageProcessingConfiguration.isReady()) {
  38757. return false;
  38758. }
  38759. this._imageProcessingConfiguration.prepareDefines(defines);
  38760. }
  38761. if (defines._areFresnelDirty) {
  38762. if (StandardMaterial.FresnelEnabled) {
  38763. // Fresnel
  38764. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  38765. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  38766. this._reflectionFresnelParameters) {
  38767. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  38768. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  38769. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  38770. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  38771. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  38772. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  38773. defines._needNormals = true;
  38774. defines.FRESNEL = true;
  38775. }
  38776. }
  38777. else {
  38778. defines.FRESNEL = false;
  38779. }
  38780. }
  38781. // Misc.
  38782. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  38783. // Attribs
  38784. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  38785. // Values that need to be evaluated on every frame
  38786. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  38787. // Get correct effect
  38788. if (defines.isDirty) {
  38789. defines.markAsProcessed();
  38790. scene.resetCachedMaterial();
  38791. // Fallbacks
  38792. var fallbacks = new BABYLON.EffectFallbacks();
  38793. if (defines.REFLECTION) {
  38794. fallbacks.addFallback(0, "REFLECTION");
  38795. }
  38796. if (defines.SPECULAR) {
  38797. fallbacks.addFallback(0, "SPECULAR");
  38798. }
  38799. if (defines.BUMP) {
  38800. fallbacks.addFallback(0, "BUMP");
  38801. }
  38802. if (defines.PARALLAX) {
  38803. fallbacks.addFallback(1, "PARALLAX");
  38804. }
  38805. if (defines.PARALLAXOCCLUSION) {
  38806. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38807. }
  38808. if (defines.SPECULAROVERALPHA) {
  38809. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38810. }
  38811. if (defines.FOG) {
  38812. fallbacks.addFallback(1, "FOG");
  38813. }
  38814. if (defines.POINTSIZE) {
  38815. fallbacks.addFallback(0, "POINTSIZE");
  38816. }
  38817. if (defines.LOGARITHMICDEPTH) {
  38818. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38819. }
  38820. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  38821. if (defines.SPECULARTERM) {
  38822. fallbacks.addFallback(0, "SPECULARTERM");
  38823. }
  38824. if (defines.DIFFUSEFRESNEL) {
  38825. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  38826. }
  38827. if (defines.OPACITYFRESNEL) {
  38828. fallbacks.addFallback(2, "OPACITYFRESNEL");
  38829. }
  38830. if (defines.REFLECTIONFRESNEL) {
  38831. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  38832. }
  38833. if (defines.EMISSIVEFRESNEL) {
  38834. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  38835. }
  38836. if (defines.FRESNEL) {
  38837. fallbacks.addFallback(4, "FRESNEL");
  38838. }
  38839. //Attributes
  38840. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38841. if (defines.NORMAL) {
  38842. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38843. }
  38844. if (defines.UV1) {
  38845. attribs.push(BABYLON.VertexBuffer.UVKind);
  38846. }
  38847. if (defines.UV2) {
  38848. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38849. }
  38850. if (defines.VERTEXCOLOR) {
  38851. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38852. }
  38853. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38854. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38855. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38856. var shaderName = "default";
  38857. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  38858. "vFogInfos", "vFogColor", "pointSize",
  38859. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38860. "mBones",
  38861. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  38862. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  38863. "vReflectionPosition", "vReflectionSize",
  38864. "logarithmicDepthConstant", "vTangentSpaceParams"
  38865. ];
  38866. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  38867. var uniformBuffers = ["Material", "Scene"];
  38868. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38869. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38870. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38871. uniformsNames: uniforms,
  38872. uniformBuffersNames: uniformBuffers,
  38873. samplers: samplers,
  38874. defines: defines,
  38875. maxSimultaneousLights: this._maxSimultaneousLights
  38876. });
  38877. if (this.customShaderNameResolve) {
  38878. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  38879. }
  38880. var join = defines.toString();
  38881. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  38882. attributes: attribs,
  38883. uniformsNames: uniforms,
  38884. uniformBuffersNames: uniformBuffers,
  38885. samplers: samplers,
  38886. defines: join,
  38887. fallbacks: fallbacks,
  38888. onCompiled: this.onCompiled,
  38889. onError: this.onError,
  38890. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38891. }, engine), defines);
  38892. this.buildUniformLayout();
  38893. }
  38894. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38895. return false;
  38896. }
  38897. defines._renderId = scene.getRenderId();
  38898. this._wasPreviouslyReady = true;
  38899. return true;
  38900. };
  38901. StandardMaterial.prototype.buildUniformLayout = function () {
  38902. // Order is important !
  38903. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  38904. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  38905. this._uniformBuffer.addUniform("opacityParts", 4);
  38906. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  38907. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  38908. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  38909. this._uniformBuffer.addUniform("refractionRightColor", 4);
  38910. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  38911. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  38912. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  38913. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  38914. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38915. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38916. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  38917. this._uniformBuffer.addUniform("vReflectionSize", 3);
  38918. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38919. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38920. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  38921. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38922. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  38923. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38924. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38925. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38926. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38927. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38928. this._uniformBuffer.addUniform("specularMatrix", 16);
  38929. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38930. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38931. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38932. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38933. this._uniformBuffer.addUniform("vSpecularColor", 4);
  38934. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38935. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  38936. this._uniformBuffer.addUniform("pointSize", 1);
  38937. this._uniformBuffer.create();
  38938. };
  38939. StandardMaterial.prototype.unbind = function () {
  38940. if (this._activeEffect) {
  38941. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38942. this._activeEffect.setTexture("reflection2DSampler", null);
  38943. }
  38944. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38945. this._activeEffect.setTexture("refraction2DSampler", null);
  38946. }
  38947. }
  38948. _super.prototype.unbind.call(this);
  38949. };
  38950. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38951. var scene = this.getScene();
  38952. var defines = subMesh._materialDefines;
  38953. if (!defines) {
  38954. return;
  38955. }
  38956. var effect = subMesh.effect;
  38957. if (!effect) {
  38958. return;
  38959. }
  38960. this._activeEffect = effect;
  38961. // Matrices
  38962. this.bindOnlyWorldMatrix(world);
  38963. // Normal Matrix
  38964. if (defines.OBJECTSPACE_NORMALMAP) {
  38965. world.toNormalMatrix(this._normalMatrix);
  38966. this.bindOnlyNormalMatrix(this._normalMatrix);
  38967. }
  38968. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38969. // Bones
  38970. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  38971. if (mustRebind) {
  38972. this._uniformBuffer.bindToEffect(effect, "Material");
  38973. this.bindViewProjection(effect);
  38974. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38975. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  38976. // Fresnel
  38977. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  38978. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  38979. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  38980. }
  38981. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  38982. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  38983. }
  38984. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  38985. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  38986. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  38987. }
  38988. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  38989. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  38990. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  38991. }
  38992. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  38993. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  38994. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  38995. }
  38996. }
  38997. // Textures
  38998. if (scene.texturesEnabled) {
  38999. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39000. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39001. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39002. }
  39003. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39004. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39005. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39006. }
  39007. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39008. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39009. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39010. }
  39011. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39012. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39013. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39014. if (this._reflectionTexture.boundingBoxSize) {
  39015. var cubeTexture = this._reflectionTexture;
  39016. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39017. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39018. }
  39019. }
  39020. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39021. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39022. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39023. }
  39024. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39025. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39026. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39027. }
  39028. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39029. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39030. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39031. }
  39032. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39033. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39034. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39035. if (scene._mirroredCameraPosition) {
  39036. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39037. }
  39038. else {
  39039. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39040. }
  39041. }
  39042. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39043. var depth = 1.0;
  39044. if (!this._refractionTexture.isCube) {
  39045. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39046. if (this._refractionTexture.depth) {
  39047. depth = this._refractionTexture.depth;
  39048. }
  39049. }
  39050. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39051. }
  39052. }
  39053. // Point size
  39054. if (this.pointsCloud) {
  39055. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39056. }
  39057. if (defines.SPECULARTERM) {
  39058. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39059. }
  39060. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39061. // Diffuse
  39062. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39063. }
  39064. // Textures
  39065. if (scene.texturesEnabled) {
  39066. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39067. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39068. }
  39069. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39070. effect.setTexture("ambientSampler", this._ambientTexture);
  39071. }
  39072. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39073. effect.setTexture("opacitySampler", this._opacityTexture);
  39074. }
  39075. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39076. if (this._reflectionTexture.isCube) {
  39077. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39078. }
  39079. else {
  39080. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39081. }
  39082. }
  39083. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39084. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39085. }
  39086. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39087. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39088. }
  39089. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39090. effect.setTexture("specularSampler", this._specularTexture);
  39091. }
  39092. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39093. effect.setTexture("bumpSampler", this._bumpTexture);
  39094. }
  39095. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39096. var depth = 1.0;
  39097. if (this._refractionTexture.isCube) {
  39098. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39099. }
  39100. else {
  39101. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39102. }
  39103. }
  39104. }
  39105. // Clip plane
  39106. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39107. // Colors
  39108. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39109. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39110. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39111. }
  39112. if (mustRebind || !this.isFrozen) {
  39113. // Lights
  39114. if (scene.lightsEnabled && !this._disableLighting) {
  39115. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39116. }
  39117. // View
  39118. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39119. this.bindView(effect);
  39120. }
  39121. // Fog
  39122. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39123. // Morph targets
  39124. if (defines.NUM_MORPH_INFLUENCERS) {
  39125. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39126. }
  39127. // Log. depth
  39128. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39129. // image processing
  39130. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39131. this._imageProcessingConfiguration.bind(this._activeEffect);
  39132. }
  39133. }
  39134. this._uniformBuffer.update();
  39135. this._afterBind(mesh, this._activeEffect);
  39136. };
  39137. StandardMaterial.prototype.getAnimatables = function () {
  39138. var results = [];
  39139. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39140. results.push(this._diffuseTexture);
  39141. }
  39142. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39143. results.push(this._ambientTexture);
  39144. }
  39145. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39146. results.push(this._opacityTexture);
  39147. }
  39148. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39149. results.push(this._reflectionTexture);
  39150. }
  39151. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39152. results.push(this._emissiveTexture);
  39153. }
  39154. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39155. results.push(this._specularTexture);
  39156. }
  39157. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39158. results.push(this._bumpTexture);
  39159. }
  39160. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39161. results.push(this._lightmapTexture);
  39162. }
  39163. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39164. results.push(this._refractionTexture);
  39165. }
  39166. return results;
  39167. };
  39168. StandardMaterial.prototype.getActiveTextures = function () {
  39169. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39170. if (this._diffuseTexture) {
  39171. activeTextures.push(this._diffuseTexture);
  39172. }
  39173. if (this._ambientTexture) {
  39174. activeTextures.push(this._ambientTexture);
  39175. }
  39176. if (this._opacityTexture) {
  39177. activeTextures.push(this._opacityTexture);
  39178. }
  39179. if (this._reflectionTexture) {
  39180. activeTextures.push(this._reflectionTexture);
  39181. }
  39182. if (this._emissiveTexture) {
  39183. activeTextures.push(this._emissiveTexture);
  39184. }
  39185. if (this._specularTexture) {
  39186. activeTextures.push(this._specularTexture);
  39187. }
  39188. if (this._bumpTexture) {
  39189. activeTextures.push(this._bumpTexture);
  39190. }
  39191. if (this._lightmapTexture) {
  39192. activeTextures.push(this._lightmapTexture);
  39193. }
  39194. if (this._refractionTexture) {
  39195. activeTextures.push(this._refractionTexture);
  39196. }
  39197. return activeTextures;
  39198. };
  39199. StandardMaterial.prototype.hasTexture = function (texture) {
  39200. if (_super.prototype.hasTexture.call(this, texture)) {
  39201. return true;
  39202. }
  39203. if (this._diffuseTexture === texture) {
  39204. return true;
  39205. }
  39206. if (this._ambientTexture === texture) {
  39207. return true;
  39208. }
  39209. if (this._opacityTexture === texture) {
  39210. return true;
  39211. }
  39212. if (this._reflectionTexture === texture) {
  39213. return true;
  39214. }
  39215. if (this._emissiveTexture === texture) {
  39216. return true;
  39217. }
  39218. if (this._specularTexture === texture) {
  39219. return true;
  39220. }
  39221. if (this._bumpTexture === texture) {
  39222. return true;
  39223. }
  39224. if (this._lightmapTexture === texture) {
  39225. return true;
  39226. }
  39227. if (this._refractionTexture === texture) {
  39228. return true;
  39229. }
  39230. return false;
  39231. };
  39232. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39233. if (forceDisposeTextures) {
  39234. if (this._diffuseTexture) {
  39235. this._diffuseTexture.dispose();
  39236. }
  39237. if (this._ambientTexture) {
  39238. this._ambientTexture.dispose();
  39239. }
  39240. if (this._opacityTexture) {
  39241. this._opacityTexture.dispose();
  39242. }
  39243. if (this._reflectionTexture) {
  39244. this._reflectionTexture.dispose();
  39245. }
  39246. if (this._emissiveTexture) {
  39247. this._emissiveTexture.dispose();
  39248. }
  39249. if (this._specularTexture) {
  39250. this._specularTexture.dispose();
  39251. }
  39252. if (this._bumpTexture) {
  39253. this._bumpTexture.dispose();
  39254. }
  39255. if (this._lightmapTexture) {
  39256. this._lightmapTexture.dispose();
  39257. }
  39258. if (this._refractionTexture) {
  39259. this._refractionTexture.dispose();
  39260. }
  39261. }
  39262. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39263. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39264. }
  39265. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39266. };
  39267. StandardMaterial.prototype.clone = function (name) {
  39268. var _this = this;
  39269. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39270. result.name = name;
  39271. result.id = name;
  39272. return result;
  39273. };
  39274. StandardMaterial.prototype.serialize = function () {
  39275. return BABYLON.SerializationHelper.Serialize(this);
  39276. };
  39277. // Statics
  39278. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39279. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39280. };
  39281. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39282. get: function () {
  39283. return StandardMaterial._DiffuseTextureEnabled;
  39284. },
  39285. set: function (value) {
  39286. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39287. return;
  39288. }
  39289. StandardMaterial._DiffuseTextureEnabled = value;
  39290. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39291. },
  39292. enumerable: true,
  39293. configurable: true
  39294. });
  39295. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39296. get: function () {
  39297. return StandardMaterial._AmbientTextureEnabled;
  39298. },
  39299. set: function (value) {
  39300. if (StandardMaterial._AmbientTextureEnabled === value) {
  39301. return;
  39302. }
  39303. StandardMaterial._AmbientTextureEnabled = value;
  39304. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39305. },
  39306. enumerable: true,
  39307. configurable: true
  39308. });
  39309. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39310. get: function () {
  39311. return StandardMaterial._OpacityTextureEnabled;
  39312. },
  39313. set: function (value) {
  39314. if (StandardMaterial._OpacityTextureEnabled === value) {
  39315. return;
  39316. }
  39317. StandardMaterial._OpacityTextureEnabled = value;
  39318. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39319. },
  39320. enumerable: true,
  39321. configurable: true
  39322. });
  39323. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39324. get: function () {
  39325. return StandardMaterial._ReflectionTextureEnabled;
  39326. },
  39327. set: function (value) {
  39328. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39329. return;
  39330. }
  39331. StandardMaterial._ReflectionTextureEnabled = value;
  39332. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39333. },
  39334. enumerable: true,
  39335. configurable: true
  39336. });
  39337. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39338. get: function () {
  39339. return StandardMaterial._EmissiveTextureEnabled;
  39340. },
  39341. set: function (value) {
  39342. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39343. return;
  39344. }
  39345. StandardMaterial._EmissiveTextureEnabled = value;
  39346. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39347. },
  39348. enumerable: true,
  39349. configurable: true
  39350. });
  39351. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39352. get: function () {
  39353. return StandardMaterial._SpecularTextureEnabled;
  39354. },
  39355. set: function (value) {
  39356. if (StandardMaterial._SpecularTextureEnabled === value) {
  39357. return;
  39358. }
  39359. StandardMaterial._SpecularTextureEnabled = value;
  39360. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39361. },
  39362. enumerable: true,
  39363. configurable: true
  39364. });
  39365. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39366. get: function () {
  39367. return StandardMaterial._BumpTextureEnabled;
  39368. },
  39369. set: function (value) {
  39370. if (StandardMaterial._BumpTextureEnabled === value) {
  39371. return;
  39372. }
  39373. StandardMaterial._BumpTextureEnabled = value;
  39374. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39375. },
  39376. enumerable: true,
  39377. configurable: true
  39378. });
  39379. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39380. get: function () {
  39381. return StandardMaterial._LightmapTextureEnabled;
  39382. },
  39383. set: function (value) {
  39384. if (StandardMaterial._LightmapTextureEnabled === value) {
  39385. return;
  39386. }
  39387. StandardMaterial._LightmapTextureEnabled = value;
  39388. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39389. },
  39390. enumerable: true,
  39391. configurable: true
  39392. });
  39393. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39394. get: function () {
  39395. return StandardMaterial._RefractionTextureEnabled;
  39396. },
  39397. set: function (value) {
  39398. if (StandardMaterial._RefractionTextureEnabled === value) {
  39399. return;
  39400. }
  39401. StandardMaterial._RefractionTextureEnabled = value;
  39402. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39403. },
  39404. enumerable: true,
  39405. configurable: true
  39406. });
  39407. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39408. get: function () {
  39409. return StandardMaterial._ColorGradingTextureEnabled;
  39410. },
  39411. set: function (value) {
  39412. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39413. return;
  39414. }
  39415. StandardMaterial._ColorGradingTextureEnabled = value;
  39416. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39417. },
  39418. enumerable: true,
  39419. configurable: true
  39420. });
  39421. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39422. get: function () {
  39423. return StandardMaterial._FresnelEnabled;
  39424. },
  39425. set: function (value) {
  39426. if (StandardMaterial._FresnelEnabled === value) {
  39427. return;
  39428. }
  39429. StandardMaterial._FresnelEnabled = value;
  39430. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39431. },
  39432. enumerable: true,
  39433. configurable: true
  39434. });
  39435. // Flags used to enable or disable a type of texture for all Standard Materials
  39436. StandardMaterial._DiffuseTextureEnabled = true;
  39437. StandardMaterial._AmbientTextureEnabled = true;
  39438. StandardMaterial._OpacityTextureEnabled = true;
  39439. StandardMaterial._ReflectionTextureEnabled = true;
  39440. StandardMaterial._EmissiveTextureEnabled = true;
  39441. StandardMaterial._SpecularTextureEnabled = true;
  39442. StandardMaterial._BumpTextureEnabled = true;
  39443. StandardMaterial._LightmapTextureEnabled = true;
  39444. StandardMaterial._RefractionTextureEnabled = true;
  39445. StandardMaterial._ColorGradingTextureEnabled = true;
  39446. StandardMaterial._FresnelEnabled = true;
  39447. __decorate([
  39448. BABYLON.serializeAsTexture("diffuseTexture")
  39449. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39450. __decorate([
  39451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39452. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39453. __decorate([
  39454. BABYLON.serializeAsTexture("ambientTexture")
  39455. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39456. __decorate([
  39457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39458. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39459. __decorate([
  39460. BABYLON.serializeAsTexture("opacityTexture")
  39461. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39462. __decorate([
  39463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39464. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39465. __decorate([
  39466. BABYLON.serializeAsTexture("reflectionTexture")
  39467. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39468. __decorate([
  39469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39470. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39471. __decorate([
  39472. BABYLON.serializeAsTexture("emissiveTexture")
  39473. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39474. __decorate([
  39475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39476. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39477. __decorate([
  39478. BABYLON.serializeAsTexture("specularTexture")
  39479. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39480. __decorate([
  39481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39482. ], StandardMaterial.prototype, "specularTexture", void 0);
  39483. __decorate([
  39484. BABYLON.serializeAsTexture("bumpTexture")
  39485. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39486. __decorate([
  39487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39488. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39489. __decorate([
  39490. BABYLON.serializeAsTexture("lightmapTexture")
  39491. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39492. __decorate([
  39493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39494. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39495. __decorate([
  39496. BABYLON.serializeAsTexture("refractionTexture")
  39497. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39498. __decorate([
  39499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39500. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39501. __decorate([
  39502. BABYLON.serializeAsColor3("ambient")
  39503. ], StandardMaterial.prototype, "ambientColor", void 0);
  39504. __decorate([
  39505. BABYLON.serializeAsColor3("diffuse")
  39506. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39507. __decorate([
  39508. BABYLON.serializeAsColor3("specular")
  39509. ], StandardMaterial.prototype, "specularColor", void 0);
  39510. __decorate([
  39511. BABYLON.serializeAsColor3("emissive")
  39512. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39513. __decorate([
  39514. BABYLON.serialize()
  39515. ], StandardMaterial.prototype, "specularPower", void 0);
  39516. __decorate([
  39517. BABYLON.serialize("useAlphaFromDiffuseTexture")
  39518. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  39519. __decorate([
  39520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39521. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  39522. __decorate([
  39523. BABYLON.serialize("useEmissiveAsIllumination")
  39524. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  39525. __decorate([
  39526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39527. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39528. __decorate([
  39529. BABYLON.serialize("linkEmissiveWithDiffuse")
  39530. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  39531. __decorate([
  39532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39533. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  39534. __decorate([
  39535. BABYLON.serialize("useSpecularOverAlpha")
  39536. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  39537. __decorate([
  39538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39539. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  39540. __decorate([
  39541. BABYLON.serialize("useReflectionOverAlpha")
  39542. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  39543. __decorate([
  39544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39545. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  39546. __decorate([
  39547. BABYLON.serialize("disableLighting")
  39548. ], StandardMaterial.prototype, "_disableLighting", void 0);
  39549. __decorate([
  39550. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39551. ], StandardMaterial.prototype, "disableLighting", void 0);
  39552. __decorate([
  39553. BABYLON.serialize("useObjectSpaceNormalMap")
  39554. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  39555. __decorate([
  39556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39557. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  39558. __decorate([
  39559. BABYLON.serialize("useParallax")
  39560. ], StandardMaterial.prototype, "_useParallax", void 0);
  39561. __decorate([
  39562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39563. ], StandardMaterial.prototype, "useParallax", void 0);
  39564. __decorate([
  39565. BABYLON.serialize("useParallaxOcclusion")
  39566. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  39567. __decorate([
  39568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39569. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  39570. __decorate([
  39571. BABYLON.serialize()
  39572. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  39573. __decorate([
  39574. BABYLON.serialize("roughness")
  39575. ], StandardMaterial.prototype, "_roughness", void 0);
  39576. __decorate([
  39577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39578. ], StandardMaterial.prototype, "roughness", void 0);
  39579. __decorate([
  39580. BABYLON.serialize()
  39581. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  39582. __decorate([
  39583. BABYLON.serialize()
  39584. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  39585. __decorate([
  39586. BABYLON.serialize("useLightmapAsShadowmap")
  39587. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  39588. __decorate([
  39589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39590. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39591. __decorate([
  39592. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  39593. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  39594. __decorate([
  39595. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39596. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  39597. __decorate([
  39598. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  39599. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  39600. __decorate([
  39601. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  39602. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  39603. __decorate([
  39604. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  39605. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  39606. __decorate([
  39607. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39608. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  39609. __decorate([
  39610. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  39611. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  39612. __decorate([
  39613. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39614. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  39615. __decorate([
  39616. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  39617. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  39618. __decorate([
  39619. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39620. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  39621. __decorate([
  39622. BABYLON.serialize("useReflectionFresnelFromSpecular")
  39623. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  39624. __decorate([
  39625. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39626. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  39627. __decorate([
  39628. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  39629. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  39630. __decorate([
  39631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39632. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  39633. __decorate([
  39634. BABYLON.serialize("maxSimultaneousLights")
  39635. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  39636. __decorate([
  39637. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39638. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  39639. __decorate([
  39640. BABYLON.serialize("invertNormalMapX")
  39641. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  39642. __decorate([
  39643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39644. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  39645. __decorate([
  39646. BABYLON.serialize("invertNormalMapY")
  39647. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  39648. __decorate([
  39649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39650. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  39651. __decorate([
  39652. BABYLON.serialize("twoSidedLighting")
  39653. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  39654. __decorate([
  39655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39656. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  39657. __decorate([
  39658. BABYLON.serialize()
  39659. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  39660. return StandardMaterial;
  39661. }(BABYLON.PushMaterial));
  39662. BABYLON.StandardMaterial = StandardMaterial;
  39663. })(BABYLON || (BABYLON = {}));
  39664. //# sourceMappingURL=babylon.standardMaterial.js.map
  39665. var BABYLON;
  39666. (function (BABYLON) {
  39667. /**
  39668. * Manages the defines for the PBR Material.
  39669. */
  39670. var PBRMaterialDefines = /** @class */ (function (_super) {
  39671. __extends(PBRMaterialDefines, _super);
  39672. /**
  39673. * Initializes the PBR Material defines.
  39674. */
  39675. function PBRMaterialDefines() {
  39676. var _this = _super.call(this) || this;
  39677. _this.PBR = true;
  39678. _this.MAINUV1 = false;
  39679. _this.MAINUV2 = false;
  39680. _this.UV1 = false;
  39681. _this.UV2 = false;
  39682. _this.ALBEDO = false;
  39683. _this.ALBEDODIRECTUV = 0;
  39684. _this.VERTEXCOLOR = false;
  39685. _this.AMBIENT = false;
  39686. _this.AMBIENTDIRECTUV = 0;
  39687. _this.AMBIENTINGRAYSCALE = false;
  39688. _this.OPACITY = false;
  39689. _this.VERTEXALPHA = false;
  39690. _this.OPACITYDIRECTUV = 0;
  39691. _this.OPACITYRGB = false;
  39692. _this.ALPHATEST = false;
  39693. _this.DEPTHPREPASS = false;
  39694. _this.ALPHABLEND = false;
  39695. _this.ALPHAFROMALBEDO = false;
  39696. _this.ALPHATESTVALUE = 0.5;
  39697. _this.SPECULAROVERALPHA = false;
  39698. _this.RADIANCEOVERALPHA = false;
  39699. _this.ALPHAFRESNEL = false;
  39700. _this.LINEARALPHAFRESNEL = false;
  39701. _this.PREMULTIPLYALPHA = false;
  39702. _this.EMISSIVE = false;
  39703. _this.EMISSIVEDIRECTUV = 0;
  39704. _this.REFLECTIVITY = false;
  39705. _this.REFLECTIVITYDIRECTUV = 0;
  39706. _this.SPECULARTERM = false;
  39707. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  39708. _this.MICROSURFACEAUTOMATIC = false;
  39709. _this.LODBASEDMICROSFURACE = false;
  39710. _this.MICROSURFACEMAP = false;
  39711. _this.MICROSURFACEMAPDIRECTUV = 0;
  39712. _this.METALLICWORKFLOW = false;
  39713. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  39714. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  39715. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  39716. _this.AOSTOREINMETALMAPRED = false;
  39717. _this.ENVIRONMENTBRDF = false;
  39718. _this.NORMAL = false;
  39719. _this.TANGENT = false;
  39720. _this.BUMP = false;
  39721. _this.BUMPDIRECTUV = 0;
  39722. _this.OBJECTSPACE_NORMALMAP = false;
  39723. _this.PARALLAX = false;
  39724. _this.PARALLAXOCCLUSION = false;
  39725. _this.NORMALXYSCALE = true;
  39726. _this.LIGHTMAP = false;
  39727. _this.LIGHTMAPDIRECTUV = 0;
  39728. _this.USELIGHTMAPASSHADOWMAP = false;
  39729. _this.REFLECTION = false;
  39730. _this.REFLECTIONMAP_3D = false;
  39731. _this.REFLECTIONMAP_SPHERICAL = false;
  39732. _this.REFLECTIONMAP_PLANAR = false;
  39733. _this.REFLECTIONMAP_CUBIC = false;
  39734. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39735. _this.REFLECTIONMAP_PROJECTION = false;
  39736. _this.REFLECTIONMAP_SKYBOX = false;
  39737. _this.REFLECTIONMAP_EXPLICIT = false;
  39738. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39739. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39740. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39741. _this.INVERTCUBICMAP = false;
  39742. _this.USESPHERICALFROMREFLECTIONMAP = false;
  39743. _this.USESPHERICALINVERTEX = false;
  39744. _this.REFLECTIONMAP_OPPOSITEZ = false;
  39745. _this.LODINREFLECTIONALPHA = false;
  39746. _this.GAMMAREFLECTION = false;
  39747. _this.RADIANCEOCCLUSION = false;
  39748. _this.HORIZONOCCLUSION = false;
  39749. _this.REFRACTION = false;
  39750. _this.REFRACTIONMAP_3D = false;
  39751. _this.REFRACTIONMAP_OPPOSITEZ = false;
  39752. _this.LODINREFRACTIONALPHA = false;
  39753. _this.GAMMAREFRACTION = false;
  39754. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  39755. _this.INSTANCES = false;
  39756. _this.NUM_BONE_INFLUENCERS = 0;
  39757. _this.BonesPerMesh = 0;
  39758. _this.NONUNIFORMSCALING = false;
  39759. _this.MORPHTARGETS = false;
  39760. _this.MORPHTARGETS_NORMAL = false;
  39761. _this.MORPHTARGETS_TANGENT = false;
  39762. _this.NUM_MORPH_INFLUENCERS = 0;
  39763. _this.IMAGEPROCESSING = false;
  39764. _this.VIGNETTE = false;
  39765. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39766. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39767. _this.TONEMAPPING = false;
  39768. _this.CONTRAST = false;
  39769. _this.COLORCURVES = false;
  39770. _this.COLORGRADING = false;
  39771. _this.COLORGRADING3D = false;
  39772. _this.SAMPLER3DGREENDEPTH = false;
  39773. _this.SAMPLER3DBGRMAP = false;
  39774. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39775. _this.EXPOSURE = false;
  39776. _this.USEPHYSICALLIGHTFALLOFF = false;
  39777. _this.TWOSIDEDLIGHTING = false;
  39778. _this.SHADOWFLOAT = false;
  39779. _this.CLIPPLANE = false;
  39780. _this.POINTSIZE = false;
  39781. _this.FOG = false;
  39782. _this.LOGARITHMICDEPTH = false;
  39783. _this.FORCENORMALFORWARD = false;
  39784. _this.rebuild();
  39785. return _this;
  39786. }
  39787. /**
  39788. * Resets the PBR Material defines.
  39789. */
  39790. PBRMaterialDefines.prototype.reset = function () {
  39791. _super.prototype.reset.call(this);
  39792. this.ALPHATESTVALUE = 0.5;
  39793. this.PBR = true;
  39794. };
  39795. return PBRMaterialDefines;
  39796. }(BABYLON.MaterialDefines));
  39797. /**
  39798. * The Physically based material base class of BJS.
  39799. *
  39800. * This offers the main features of a standard PBR material.
  39801. * For more information, please refer to the documentation :
  39802. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39803. */
  39804. var PBRBaseMaterial = /** @class */ (function (_super) {
  39805. __extends(PBRBaseMaterial, _super);
  39806. /**
  39807. * Instantiates a new PBRMaterial instance.
  39808. *
  39809. * @param name The material name
  39810. * @param scene The scene the material will be use in.
  39811. */
  39812. function PBRBaseMaterial(name, scene) {
  39813. var _this = _super.call(this, name, scene) || this;
  39814. /**
  39815. * Intensity of the direct lights e.g. the four lights available in your scene.
  39816. * This impacts both the direct diffuse and specular highlights.
  39817. */
  39818. _this._directIntensity = 1.0;
  39819. /**
  39820. * Intensity of the emissive part of the material.
  39821. * This helps controlling the emissive effect without modifying the emissive color.
  39822. */
  39823. _this._emissiveIntensity = 1.0;
  39824. /**
  39825. * Intensity of the environment e.g. how much the environment will light the object
  39826. * either through harmonics for rough material or through the refelction for shiny ones.
  39827. */
  39828. _this._environmentIntensity = 1.0;
  39829. /**
  39830. * This is a special control allowing the reduction of the specular highlights coming from the
  39831. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39832. */
  39833. _this._specularIntensity = 1.0;
  39834. /**
  39835. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  39836. */
  39837. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  39838. /**
  39839. * Debug Control allowing disabling the bump map on this material.
  39840. */
  39841. _this._disableBumpMap = false;
  39842. /**
  39843. * AKA Occlusion Texture Intensity in other nomenclature.
  39844. */
  39845. _this._ambientTextureStrength = 1.0;
  39846. /**
  39847. * The color of a material in ambient lighting.
  39848. */
  39849. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  39850. /**
  39851. * AKA Diffuse Color in other nomenclature.
  39852. */
  39853. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  39854. /**
  39855. * AKA Specular Color in other nomenclature.
  39856. */
  39857. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39858. /**
  39859. * The color applied when light is reflected from a material.
  39860. */
  39861. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  39862. /**
  39863. * The color applied when light is emitted from a material.
  39864. */
  39865. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  39866. /**
  39867. * AKA Glossiness in other nomenclature.
  39868. */
  39869. _this._microSurface = 0.9;
  39870. /**
  39871. * source material index of refraction (IOR)' / 'destination material IOR.
  39872. */
  39873. _this._indexOfRefraction = 0.66;
  39874. /**
  39875. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39876. */
  39877. _this._invertRefractionY = false;
  39878. /**
  39879. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39880. * Materials half opaque for instance using refraction could benefit from this control.
  39881. */
  39882. _this._linkRefractionWithTransparency = false;
  39883. /**
  39884. * Specifies that the material will use the light map as a show map.
  39885. */
  39886. _this._useLightmapAsShadowmap = false;
  39887. /**
  39888. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39889. * makes the reflect vector face the model (under horizon).
  39890. */
  39891. _this._useHorizonOcclusion = true;
  39892. /**
  39893. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39894. * too much the area relying on ambient texture to define their ambient occlusion.
  39895. */
  39896. _this._useRadianceOcclusion = true;
  39897. /**
  39898. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39899. */
  39900. _this._useAlphaFromAlbedoTexture = false;
  39901. /**
  39902. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39903. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39904. */
  39905. _this._useSpecularOverAlpha = true;
  39906. /**
  39907. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39908. */
  39909. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  39910. /**
  39911. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39912. */
  39913. _this._useRoughnessFromMetallicTextureAlpha = true;
  39914. /**
  39915. * Specifies if the metallic texture contains the roughness information in its green channel.
  39916. */
  39917. _this._useRoughnessFromMetallicTextureGreen = false;
  39918. /**
  39919. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39920. */
  39921. _this._useMetallnessFromMetallicTextureBlue = false;
  39922. /**
  39923. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39924. */
  39925. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  39926. /**
  39927. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39928. */
  39929. _this._useAmbientInGrayScale = false;
  39930. /**
  39931. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39932. * The material will try to infer what glossiness each pixel should be.
  39933. */
  39934. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  39935. /**
  39936. * BJS is using an harcoded light falloff based on a manually sets up range.
  39937. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39938. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39939. */
  39940. _this._usePhysicalLightFalloff = true;
  39941. /**
  39942. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39943. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39944. */
  39945. _this._useRadianceOverAlpha = true;
  39946. /**
  39947. * Allows using an object space normal map (instead of tangent space).
  39948. */
  39949. _this._useObjectSpaceNormalMap = false;
  39950. /**
  39951. * Allows using the bump map in parallax mode.
  39952. */
  39953. _this._useParallax = false;
  39954. /**
  39955. * Allows using the bump map in parallax occlusion mode.
  39956. */
  39957. _this._useParallaxOcclusion = false;
  39958. /**
  39959. * Controls the scale bias of the parallax mode.
  39960. */
  39961. _this._parallaxScaleBias = 0.05;
  39962. /**
  39963. * If sets to true, disables all the lights affecting the material.
  39964. */
  39965. _this._disableLighting = false;
  39966. /**
  39967. * Number of Simultaneous lights allowed on the material.
  39968. */
  39969. _this._maxSimultaneousLights = 4;
  39970. /**
  39971. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  39972. */
  39973. _this._invertNormalMapX = false;
  39974. /**
  39975. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  39976. */
  39977. _this._invertNormalMapY = false;
  39978. /**
  39979. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39980. */
  39981. _this._twoSidedLighting = false;
  39982. /**
  39983. * Defines the alpha limits in alpha test mode.
  39984. */
  39985. _this._alphaCutOff = 0.4;
  39986. /**
  39987. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39988. */
  39989. _this._forceAlphaTest = false;
  39990. /**
  39991. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39992. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39993. */
  39994. _this._useAlphaFresnel = false;
  39995. /**
  39996. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39997. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39998. */
  39999. _this._useLinearAlphaFresnel = false;
  40000. /**
  40001. * The transparency mode of the material.
  40002. */
  40003. _this._transparencyMode = null;
  40004. /**
  40005. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40006. * from cos thetav and roughness:
  40007. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40008. */
  40009. _this._environmentBRDFTexture = null;
  40010. /**
  40011. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40012. */
  40013. _this._forceIrradianceInFragment = false;
  40014. /**
  40015. * Force normal to face away from face.
  40016. */
  40017. _this._forceNormalForward = false;
  40018. /**
  40019. * Force metallic workflow.
  40020. */
  40021. _this._forceMetallicWorkflow = false;
  40022. /**
  40023. * Stores the available render targets.
  40024. */
  40025. _this._renderTargets = new BABYLON.SmartArray(16);
  40026. /**
  40027. * Sets the global ambient color for the material used in lighting calculations.
  40028. */
  40029. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40030. // Setup the default processing configuration to the scene.
  40031. _this._attachImageProcessingConfiguration(null);
  40032. _this.getRenderTargetTextures = function () {
  40033. _this._renderTargets.reset();
  40034. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40035. _this._renderTargets.push(_this._reflectionTexture);
  40036. }
  40037. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40038. _this._renderTargets.push(_this._refractionTexture);
  40039. }
  40040. return _this._renderTargets;
  40041. };
  40042. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40043. return _this;
  40044. }
  40045. /**
  40046. * Attaches a new image processing configuration to the PBR Material.
  40047. * @param configuration
  40048. */
  40049. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40050. var _this = this;
  40051. if (configuration === this._imageProcessingConfiguration) {
  40052. return;
  40053. }
  40054. // Detaches observer.
  40055. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40056. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40057. }
  40058. // Pick the scene configuration if needed.
  40059. if (!configuration) {
  40060. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40061. }
  40062. else {
  40063. this._imageProcessingConfiguration = configuration;
  40064. }
  40065. // Attaches observer.
  40066. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40067. _this._markAllSubMeshesAsImageProcessingDirty();
  40068. });
  40069. };
  40070. /**
  40071. * Gets the name of the material class.
  40072. */
  40073. PBRBaseMaterial.prototype.getClassName = function () {
  40074. return "PBRBaseMaterial";
  40075. };
  40076. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40077. /**
  40078. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40079. */
  40080. get: function () {
  40081. return this._useLogarithmicDepth;
  40082. },
  40083. /**
  40084. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40085. */
  40086. set: function (value) {
  40087. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40088. },
  40089. enumerable: true,
  40090. configurable: true
  40091. });
  40092. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40093. /**
  40094. * Gets the current transparency mode.
  40095. */
  40096. get: function () {
  40097. return this._transparencyMode;
  40098. },
  40099. /**
  40100. * Sets the transparency mode of the material.
  40101. */
  40102. set: function (value) {
  40103. if (this._transparencyMode === value) {
  40104. return;
  40105. }
  40106. this._transparencyMode = value;
  40107. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40108. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40109. },
  40110. enumerable: true,
  40111. configurable: true
  40112. });
  40113. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40114. /**
  40115. * Returns true if alpha blending should be disabled.
  40116. */
  40117. get: function () {
  40118. return (this._linkRefractionWithTransparency ||
  40119. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40120. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40121. },
  40122. enumerable: true,
  40123. configurable: true
  40124. });
  40125. /**
  40126. * Specifies whether or not this material should be rendered in alpha blend mode.
  40127. */
  40128. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40129. if (this._disableAlphaBlending) {
  40130. return false;
  40131. }
  40132. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40133. };
  40134. /**
  40135. * Specifies if the mesh will require alpha blending.
  40136. * @param mesh - BJS mesh.
  40137. */
  40138. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40139. if (this._disableAlphaBlending) {
  40140. return false;
  40141. }
  40142. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40143. };
  40144. /**
  40145. * Specifies whether or not this material should be rendered in alpha test mode.
  40146. */
  40147. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40148. if (this._forceAlphaTest) {
  40149. return true;
  40150. }
  40151. if (this._linkRefractionWithTransparency) {
  40152. return false;
  40153. }
  40154. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40155. };
  40156. /**
  40157. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40158. */
  40159. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40160. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40161. };
  40162. /**
  40163. * Gets the texture used for the alpha test.
  40164. */
  40165. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40166. return this._albedoTexture;
  40167. };
  40168. /**
  40169. * Specifies that the submesh is ready to be used.
  40170. * @param mesh - BJS mesh.
  40171. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40172. * @param useInstances - Specifies that instances should be used.
  40173. * @returns - boolean indicating that the submesh is ready or not.
  40174. */
  40175. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40176. if (subMesh.effect && this.isFrozen) {
  40177. if (this._wasPreviouslyReady) {
  40178. return true;
  40179. }
  40180. }
  40181. if (!subMesh._materialDefines) {
  40182. subMesh._materialDefines = new PBRMaterialDefines();
  40183. }
  40184. var defines = subMesh._materialDefines;
  40185. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40186. if (defines._renderId === this.getScene().getRenderId()) {
  40187. return true;
  40188. }
  40189. }
  40190. var scene = this.getScene();
  40191. var engine = scene.getEngine();
  40192. if (defines._areTexturesDirty) {
  40193. if (scene.texturesEnabled) {
  40194. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40195. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40196. return false;
  40197. }
  40198. }
  40199. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40200. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40201. return false;
  40202. }
  40203. }
  40204. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40205. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40206. return false;
  40207. }
  40208. }
  40209. var reflectionTexture = this._getReflectionTexture();
  40210. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40211. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40212. return false;
  40213. }
  40214. }
  40215. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40216. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40217. return false;
  40218. }
  40219. }
  40220. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40221. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40222. return false;
  40223. }
  40224. }
  40225. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40226. if (this._metallicTexture) {
  40227. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40228. return false;
  40229. }
  40230. }
  40231. else if (this._reflectivityTexture) {
  40232. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40233. return false;
  40234. }
  40235. }
  40236. if (this._microSurfaceTexture) {
  40237. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40238. return false;
  40239. }
  40240. }
  40241. }
  40242. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40243. // Bump texture cannot be not blocking.
  40244. if (!this._bumpTexture.isReady()) {
  40245. return false;
  40246. }
  40247. }
  40248. var refractionTexture = this._getRefractionTexture();
  40249. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40250. if (!refractionTexture.isReadyOrNotBlocking()) {
  40251. return false;
  40252. }
  40253. }
  40254. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40255. // This is blocking.
  40256. if (!this._environmentBRDFTexture.isReady()) {
  40257. return false;
  40258. }
  40259. }
  40260. }
  40261. }
  40262. if (defines._areImageProcessingDirty) {
  40263. if (!this._imageProcessingConfiguration.isReady()) {
  40264. return false;
  40265. }
  40266. }
  40267. if (!engine.getCaps().standardDerivatives) {
  40268. var bufferMesh = null;
  40269. if (mesh.getClassName() === "InstancedMesh") {
  40270. bufferMesh = mesh.sourceMesh;
  40271. }
  40272. else if (mesh.getClassName() === "Mesh") {
  40273. bufferMesh = mesh;
  40274. }
  40275. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40276. bufferMesh.createNormals(true);
  40277. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40278. }
  40279. }
  40280. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40281. if (effect) {
  40282. scene.resetCachedMaterial();
  40283. subMesh.setEffect(effect, defines);
  40284. this.buildUniformLayout();
  40285. }
  40286. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40287. return false;
  40288. }
  40289. defines._renderId = scene.getRenderId();
  40290. this._wasPreviouslyReady = true;
  40291. return true;
  40292. };
  40293. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40294. if (onCompiled === void 0) { onCompiled = null; }
  40295. if (onError === void 0) { onError = null; }
  40296. if (useInstances === void 0) { useInstances = null; }
  40297. if (useClipPlane === void 0) { useClipPlane = null; }
  40298. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40299. if (!defines.isDirty) {
  40300. return null;
  40301. }
  40302. defines.markAsProcessed();
  40303. var scene = this.getScene();
  40304. var engine = scene.getEngine();
  40305. // Fallbacks
  40306. var fallbacks = new BABYLON.EffectFallbacks();
  40307. var fallbackRank = 0;
  40308. if (defines.USESPHERICALINVERTEX) {
  40309. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40310. }
  40311. if (defines.FOG) {
  40312. fallbacks.addFallback(fallbackRank, "FOG");
  40313. }
  40314. if (defines.POINTSIZE) {
  40315. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40316. }
  40317. if (defines.LOGARITHMICDEPTH) {
  40318. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40319. }
  40320. if (defines.PARALLAX) {
  40321. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40322. }
  40323. if (defines.PARALLAXOCCLUSION) {
  40324. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40325. }
  40326. if (defines.ENVIRONMENTBRDF) {
  40327. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40328. }
  40329. if (defines.TANGENT) {
  40330. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40331. }
  40332. if (defines.BUMP) {
  40333. fallbacks.addFallback(fallbackRank++, "BUMP");
  40334. }
  40335. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40336. if (defines.SPECULARTERM) {
  40337. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40338. }
  40339. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40340. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40341. }
  40342. if (defines.LIGHTMAP) {
  40343. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40344. }
  40345. if (defines.NORMAL) {
  40346. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40347. }
  40348. if (defines.AMBIENT) {
  40349. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40350. }
  40351. if (defines.EMISSIVE) {
  40352. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40353. }
  40354. if (defines.VERTEXCOLOR) {
  40355. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40356. }
  40357. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40358. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40359. }
  40360. if (defines.MORPHTARGETS) {
  40361. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40362. }
  40363. //Attributes
  40364. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40365. if (defines.NORMAL) {
  40366. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40367. }
  40368. if (defines.TANGENT) {
  40369. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40370. }
  40371. if (defines.UV1) {
  40372. attribs.push(BABYLON.VertexBuffer.UVKind);
  40373. }
  40374. if (defines.UV2) {
  40375. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40376. }
  40377. if (defines.VERTEXCOLOR) {
  40378. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40379. }
  40380. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40381. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40382. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40383. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40384. "vFogInfos", "vFogColor", "pointSize",
  40385. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40386. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40387. "mBones",
  40388. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40389. "vLightingIntensity",
  40390. "logarithmicDepthConstant",
  40391. "vSphericalX", "vSphericalY", "vSphericalZ",
  40392. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40393. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40394. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40395. "vTangentSpaceParams"
  40396. ];
  40397. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40398. "bumpSampler", "lightmapSampler", "opacitySampler",
  40399. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40400. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40401. "microSurfaceSampler", "environmentBrdfSampler"];
  40402. var uniformBuffers = ["Material", "Scene"];
  40403. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40404. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40405. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40406. uniformsNames: uniforms,
  40407. uniformBuffersNames: uniformBuffers,
  40408. samplers: samplers,
  40409. defines: defines,
  40410. maxSimultaneousLights: this._maxSimultaneousLights
  40411. });
  40412. var join = defines.toString();
  40413. return engine.createEffect("pbr", {
  40414. attributes: attribs,
  40415. uniformsNames: uniforms,
  40416. uniformBuffersNames: uniformBuffers,
  40417. samplers: samplers,
  40418. defines: join,
  40419. fallbacks: fallbacks,
  40420. onCompiled: onCompiled,
  40421. onError: onError,
  40422. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40423. }, engine);
  40424. };
  40425. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40426. if (useInstances === void 0) { useInstances = null; }
  40427. if (useClipPlane === void 0) { useClipPlane = null; }
  40428. var scene = this.getScene();
  40429. var engine = scene.getEngine();
  40430. // Lights
  40431. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40432. defines._needNormals = true;
  40433. // Textures
  40434. if (defines._areTexturesDirty) {
  40435. defines._needUVs = false;
  40436. if (scene.texturesEnabled) {
  40437. if (scene.getEngine().getCaps().textureLOD) {
  40438. defines.LODBASEDMICROSFURACE = true;
  40439. }
  40440. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40441. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40442. }
  40443. else {
  40444. defines.ALBEDO = false;
  40445. }
  40446. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40447. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40448. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40449. }
  40450. else {
  40451. defines.AMBIENT = false;
  40452. }
  40453. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40454. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40455. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40456. }
  40457. else {
  40458. defines.OPACITY = false;
  40459. }
  40460. var reflectionTexture = this._getReflectionTexture();
  40461. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40462. defines.REFLECTION = true;
  40463. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40464. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40465. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40466. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40467. defines.INVERTCUBICMAP = true;
  40468. }
  40469. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40470. switch (reflectionTexture.coordinatesMode) {
  40471. case BABYLON.Texture.CUBIC_MODE:
  40472. case BABYLON.Texture.INVCUBIC_MODE:
  40473. defines.REFLECTIONMAP_CUBIC = true;
  40474. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40475. break;
  40476. case BABYLON.Texture.EXPLICIT_MODE:
  40477. defines.REFLECTIONMAP_EXPLICIT = true;
  40478. break;
  40479. case BABYLON.Texture.PLANAR_MODE:
  40480. defines.REFLECTIONMAP_PLANAR = true;
  40481. break;
  40482. case BABYLON.Texture.PROJECTION_MODE:
  40483. defines.REFLECTIONMAP_PROJECTION = true;
  40484. break;
  40485. case BABYLON.Texture.SKYBOX_MODE:
  40486. defines.REFLECTIONMAP_SKYBOX = true;
  40487. break;
  40488. case BABYLON.Texture.SPHERICAL_MODE:
  40489. defines.REFLECTIONMAP_SPHERICAL = true;
  40490. break;
  40491. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40492. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40493. break;
  40494. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40495. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40496. break;
  40497. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40498. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40499. break;
  40500. }
  40501. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40502. if (reflectionTexture.sphericalPolynomial) {
  40503. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40504. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40505. defines.USESPHERICALINVERTEX = false;
  40506. }
  40507. else {
  40508. defines.USESPHERICALINVERTEX = true;
  40509. }
  40510. }
  40511. }
  40512. }
  40513. else {
  40514. defines.REFLECTION = false;
  40515. defines.REFLECTIONMAP_3D = false;
  40516. defines.REFLECTIONMAP_SPHERICAL = false;
  40517. defines.REFLECTIONMAP_PLANAR = false;
  40518. defines.REFLECTIONMAP_CUBIC = false;
  40519. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40520. defines.REFLECTIONMAP_PROJECTION = false;
  40521. defines.REFLECTIONMAP_SKYBOX = false;
  40522. defines.REFLECTIONMAP_EXPLICIT = false;
  40523. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40524. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40525. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40526. defines.INVERTCUBICMAP = false;
  40527. defines.USESPHERICALFROMREFLECTIONMAP = false;
  40528. defines.USESPHERICALINVERTEX = false;
  40529. defines.REFLECTIONMAP_OPPOSITEZ = false;
  40530. defines.LODINREFLECTIONALPHA = false;
  40531. defines.GAMMAREFLECTION = false;
  40532. }
  40533. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40534. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  40535. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40536. }
  40537. else {
  40538. defines.LIGHTMAP = false;
  40539. }
  40540. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40541. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  40542. }
  40543. else {
  40544. defines.EMISSIVE = false;
  40545. }
  40546. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40547. if (this._metallicTexture) {
  40548. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  40549. defines.METALLICWORKFLOW = true;
  40550. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  40551. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  40552. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  40553. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  40554. }
  40555. else if (this._reflectivityTexture) {
  40556. defines.METALLICWORKFLOW = false;
  40557. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  40558. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  40559. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  40560. }
  40561. else {
  40562. defines.METALLICWORKFLOW = false;
  40563. defines.REFLECTIVITY = false;
  40564. }
  40565. if (this._microSurfaceTexture) {
  40566. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  40567. }
  40568. else {
  40569. defines.MICROSURFACEMAP = false;
  40570. }
  40571. }
  40572. else {
  40573. defines.REFLECTIVITY = false;
  40574. defines.MICROSURFACEMAP = false;
  40575. }
  40576. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40577. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40578. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40579. defines.PARALLAX = true;
  40580. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  40581. }
  40582. else {
  40583. defines.PARALLAX = false;
  40584. }
  40585. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  40586. }
  40587. else {
  40588. defines.BUMP = false;
  40589. }
  40590. var refractionTexture = this._getRefractionTexture();
  40591. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40592. defines.REFRACTION = true;
  40593. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  40594. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  40595. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  40596. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  40597. if (this._linkRefractionWithTransparency) {
  40598. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  40599. }
  40600. }
  40601. else {
  40602. defines.REFRACTION = false;
  40603. }
  40604. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40605. defines.ENVIRONMENTBRDF = true;
  40606. }
  40607. else {
  40608. defines.ENVIRONMENTBRDF = false;
  40609. }
  40610. if (this._shouldUseAlphaFromAlbedoTexture()) {
  40611. defines.ALPHAFROMALBEDO = true;
  40612. }
  40613. else {
  40614. defines.ALPHAFROMALBEDO = false;
  40615. }
  40616. }
  40617. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40618. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  40619. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  40620. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  40621. defines.METALLICWORKFLOW = true;
  40622. }
  40623. else {
  40624. defines.METALLICWORKFLOW = false;
  40625. }
  40626. if (!this.backFaceCulling && this._twoSidedLighting) {
  40627. defines.TWOSIDEDLIGHTING = true;
  40628. }
  40629. else {
  40630. defines.TWOSIDEDLIGHTING = false;
  40631. }
  40632. defines.ALPHATESTVALUE = this._alphaCutOff;
  40633. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40634. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  40635. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  40636. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  40637. }
  40638. if (defines._areImageProcessingDirty) {
  40639. this._imageProcessingConfiguration.prepareDefines(defines);
  40640. }
  40641. defines.FORCENORMALFORWARD = this._forceNormalForward;
  40642. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  40643. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  40644. // Misc.
  40645. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  40646. // Values that need to be evaluated on every frame
  40647. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  40648. // Attribs
  40649. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  40650. };
  40651. /**
  40652. * Force shader compilation
  40653. */
  40654. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  40655. var _this = this;
  40656. var localOptions = __assign({ clipPlane: false }, options);
  40657. var defines = new PBRMaterialDefines();
  40658. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  40659. if (effect.isReady()) {
  40660. if (onCompiled) {
  40661. onCompiled(this);
  40662. }
  40663. }
  40664. else {
  40665. effect.onCompileObservable.add(function () {
  40666. if (onCompiled) {
  40667. onCompiled(_this);
  40668. }
  40669. });
  40670. }
  40671. };
  40672. /**
  40673. * Initializes the uniform buffer layout for the shader.
  40674. */
  40675. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  40676. // Order is important !
  40677. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  40678. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  40679. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40680. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40681. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40682. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  40683. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  40684. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40685. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40686. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40687. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40688. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40689. this._uniformBuffer.addUniform("albedoMatrix", 16);
  40690. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40691. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40692. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40693. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40694. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  40695. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  40696. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40697. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40698. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40699. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40700. this._uniformBuffer.addUniform("vReflectionColor", 3);
  40701. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  40702. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  40703. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  40704. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  40705. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  40706. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40707. this._uniformBuffer.addUniform("pointSize", 1);
  40708. this._uniformBuffer.create();
  40709. };
  40710. /**
  40711. * Unbinds the textures.
  40712. */
  40713. PBRBaseMaterial.prototype.unbind = function () {
  40714. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40715. this._uniformBuffer.setTexture("reflectionSampler", null);
  40716. }
  40717. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40718. this._uniformBuffer.setTexture("refractionSampler", null);
  40719. }
  40720. _super.prototype.unbind.call(this);
  40721. };
  40722. /**
  40723. * Binds the submesh data.
  40724. * @param world - The world matrix.
  40725. * @param mesh - The BJS mesh.
  40726. * @param subMesh - A submesh of the BJS mesh.
  40727. */
  40728. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40729. var scene = this.getScene();
  40730. var defines = subMesh._materialDefines;
  40731. if (!defines) {
  40732. return;
  40733. }
  40734. var effect = subMesh.effect;
  40735. if (!effect) {
  40736. return;
  40737. }
  40738. this._activeEffect = effect;
  40739. // Matrices
  40740. this.bindOnlyWorldMatrix(world);
  40741. // Normal Matrix
  40742. if (defines.OBJECTSPACE_NORMALMAP) {
  40743. world.toNormalMatrix(this._normalMatrix);
  40744. this.bindOnlyNormalMatrix(this._normalMatrix);
  40745. }
  40746. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40747. // Bones
  40748. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  40749. var reflectionTexture = null;
  40750. if (mustRebind) {
  40751. this._uniformBuffer.bindToEffect(effect, "Material");
  40752. this.bindViewProjection(effect);
  40753. reflectionTexture = this._getReflectionTexture();
  40754. var refractionTexture = this._getRefractionTexture();
  40755. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40756. // Texture uniforms
  40757. if (scene.texturesEnabled) {
  40758. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40759. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  40760. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  40761. }
  40762. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40763. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  40764. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40765. }
  40766. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40767. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40768. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40769. }
  40770. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40771. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  40772. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  40773. if (reflectionTexture.boundingBoxSize) {
  40774. var cubeTexture = reflectionTexture;
  40775. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40776. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40777. }
  40778. var polynomials = reflectionTexture.sphericalPolynomial;
  40779. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  40780. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  40781. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  40782. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  40783. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  40784. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  40785. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  40786. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  40787. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  40788. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  40789. }
  40790. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  40791. }
  40792. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40793. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40794. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40795. }
  40796. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40797. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40798. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40799. }
  40800. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40801. if (this._metallicTexture) {
  40802. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  40803. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  40804. }
  40805. else if (this._reflectivityTexture) {
  40806. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  40807. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  40808. }
  40809. if (this._microSurfaceTexture) {
  40810. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  40811. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  40812. }
  40813. }
  40814. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40815. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  40816. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40817. if (scene._mirroredCameraPosition) {
  40818. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40819. }
  40820. else {
  40821. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40822. }
  40823. }
  40824. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40825. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  40826. var depth = 1.0;
  40827. if (!refractionTexture.isCube) {
  40828. if (refractionTexture.depth) {
  40829. depth = refractionTexture.depth;
  40830. }
  40831. }
  40832. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  40833. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  40834. }
  40835. }
  40836. // Point size
  40837. if (this.pointsCloud) {
  40838. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40839. }
  40840. // Colors
  40841. if (defines.METALLICWORKFLOW) {
  40842. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  40843. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  40844. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  40845. }
  40846. else {
  40847. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  40848. }
  40849. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  40850. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  40851. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  40852. // Misc
  40853. this._lightingInfos.x = this._directIntensity;
  40854. this._lightingInfos.y = this._emissiveIntensity;
  40855. this._lightingInfos.z = this._environmentIntensity;
  40856. this._lightingInfos.w = this._specularIntensity;
  40857. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  40858. }
  40859. // Textures
  40860. if (scene.texturesEnabled) {
  40861. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40862. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  40863. }
  40864. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40865. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  40866. }
  40867. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40868. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  40869. }
  40870. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40871. if (defines.LODBASEDMICROSFURACE) {
  40872. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  40873. }
  40874. else {
  40875. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  40876. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  40877. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  40878. }
  40879. }
  40880. if (defines.ENVIRONMENTBRDF) {
  40881. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  40882. }
  40883. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40884. if (defines.LODBASEDMICROSFURACE) {
  40885. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  40886. }
  40887. else {
  40888. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  40889. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  40890. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  40891. }
  40892. }
  40893. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40894. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  40895. }
  40896. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40897. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  40898. }
  40899. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40900. if (this._metallicTexture) {
  40901. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  40902. }
  40903. else if (this._reflectivityTexture) {
  40904. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  40905. }
  40906. if (this._microSurfaceTexture) {
  40907. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  40908. }
  40909. }
  40910. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40911. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  40912. }
  40913. }
  40914. // Clip plane
  40915. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  40916. // Colors
  40917. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  40918. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40919. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  40920. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  40921. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40922. }
  40923. if (mustRebind || !this.isFrozen) {
  40924. // Lights
  40925. if (scene.lightsEnabled && !this._disableLighting) {
  40926. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  40927. }
  40928. // View
  40929. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  40930. this.bindView(effect);
  40931. }
  40932. // Fog
  40933. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  40934. // Morph targets
  40935. if (defines.NUM_MORPH_INFLUENCERS) {
  40936. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  40937. }
  40938. // image processing
  40939. this._imageProcessingConfiguration.bind(this._activeEffect);
  40940. // Log. depth
  40941. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  40942. }
  40943. this._uniformBuffer.update();
  40944. this._afterBind(mesh);
  40945. };
  40946. /**
  40947. * Returns the animatable textures.
  40948. * @returns - Array of animatable textures.
  40949. */
  40950. PBRBaseMaterial.prototype.getAnimatables = function () {
  40951. var results = [];
  40952. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  40953. results.push(this._albedoTexture);
  40954. }
  40955. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40956. results.push(this._ambientTexture);
  40957. }
  40958. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40959. results.push(this._opacityTexture);
  40960. }
  40961. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40962. results.push(this._reflectionTexture);
  40963. }
  40964. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40965. results.push(this._emissiveTexture);
  40966. }
  40967. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  40968. results.push(this._metallicTexture);
  40969. }
  40970. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  40971. results.push(this._reflectivityTexture);
  40972. }
  40973. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40974. results.push(this._bumpTexture);
  40975. }
  40976. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40977. results.push(this._lightmapTexture);
  40978. }
  40979. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40980. results.push(this._refractionTexture);
  40981. }
  40982. return results;
  40983. };
  40984. /**
  40985. * Returns the texture used for reflections.
  40986. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  40987. */
  40988. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  40989. if (this._reflectionTexture) {
  40990. return this._reflectionTexture;
  40991. }
  40992. return this.getScene().environmentTexture;
  40993. };
  40994. /**
  40995. * Returns the texture used for refraction or null if none is used.
  40996. * @returns - Refection texture if present. If no refraction texture and refraction
  40997. * is linked with transparency, returns environment texture. Otherwise, returns null.
  40998. */
  40999. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41000. if (this._refractionTexture) {
  41001. return this._refractionTexture;
  41002. }
  41003. if (this._linkRefractionWithTransparency) {
  41004. return this.getScene().environmentTexture;
  41005. }
  41006. return null;
  41007. };
  41008. /**
  41009. * Disposes the resources of the material.
  41010. * @param forceDisposeEffect - Forces the disposal of effects.
  41011. * @param forceDisposeTextures - Forces the disposal of all textures.
  41012. */
  41013. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41014. if (forceDisposeTextures) {
  41015. if (this._albedoTexture) {
  41016. this._albedoTexture.dispose();
  41017. }
  41018. if (this._ambientTexture) {
  41019. this._ambientTexture.dispose();
  41020. }
  41021. if (this._opacityTexture) {
  41022. this._opacityTexture.dispose();
  41023. }
  41024. if (this._reflectionTexture) {
  41025. this._reflectionTexture.dispose();
  41026. }
  41027. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41028. this._environmentBRDFTexture.dispose();
  41029. }
  41030. if (this._emissiveTexture) {
  41031. this._emissiveTexture.dispose();
  41032. }
  41033. if (this._metallicTexture) {
  41034. this._metallicTexture.dispose();
  41035. }
  41036. if (this._reflectivityTexture) {
  41037. this._reflectivityTexture.dispose();
  41038. }
  41039. if (this._bumpTexture) {
  41040. this._bumpTexture.dispose();
  41041. }
  41042. if (this._lightmapTexture) {
  41043. this._lightmapTexture.dispose();
  41044. }
  41045. if (this._refractionTexture) {
  41046. this._refractionTexture.dispose();
  41047. }
  41048. }
  41049. this._renderTargets.dispose();
  41050. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41051. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41052. }
  41053. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41054. };
  41055. /**
  41056. * Stores the reflectivity values based on metallic roughness workflow.
  41057. */
  41058. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41059. __decorate([
  41060. BABYLON.serializeAsImageProcessingConfiguration()
  41061. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41062. __decorate([
  41063. BABYLON.serialize()
  41064. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41065. __decorate([
  41066. BABYLON.serialize()
  41067. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41068. return PBRBaseMaterial;
  41069. }(BABYLON.PushMaterial));
  41070. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41071. })(BABYLON || (BABYLON = {}));
  41072. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41073. var BABYLON;
  41074. (function (BABYLON) {
  41075. /**
  41076. * The Physically based simple base material of BJS.
  41077. *
  41078. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41079. * It is used as the base class for both the specGloss and metalRough conventions.
  41080. */
  41081. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41082. __extends(PBRBaseSimpleMaterial, _super);
  41083. /**
  41084. * Instantiates a new PBRMaterial instance.
  41085. *
  41086. * @param name The material name
  41087. * @param scene The scene the material will be use in.
  41088. */
  41089. function PBRBaseSimpleMaterial(name, scene) {
  41090. var _this = _super.call(this, name, scene) || this;
  41091. /**
  41092. * Number of Simultaneous lights allowed on the material.
  41093. */
  41094. _this.maxSimultaneousLights = 4;
  41095. /**
  41096. * If sets to true, disables all the lights affecting the material.
  41097. */
  41098. _this.disableLighting = false;
  41099. /**
  41100. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41101. */
  41102. _this.invertNormalMapX = false;
  41103. /**
  41104. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41105. */
  41106. _this.invertNormalMapY = false;
  41107. /**
  41108. * Emissivie color used to self-illuminate the model.
  41109. */
  41110. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41111. /**
  41112. * Occlusion Channel Strenght.
  41113. */
  41114. _this.occlusionStrength = 1.0;
  41115. _this.useLightmapAsShadowmap = false;
  41116. _this._useAlphaFromAlbedoTexture = true;
  41117. _this._useAmbientInGrayScale = true;
  41118. return _this;
  41119. }
  41120. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41121. /**
  41122. * Gets the current double sided mode.
  41123. */
  41124. get: function () {
  41125. return this._twoSidedLighting;
  41126. },
  41127. /**
  41128. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41129. */
  41130. set: function (value) {
  41131. if (this._twoSidedLighting === value) {
  41132. return;
  41133. }
  41134. this._twoSidedLighting = value;
  41135. this.backFaceCulling = !value;
  41136. this._markAllSubMeshesAsTexturesDirty();
  41137. },
  41138. enumerable: true,
  41139. configurable: true
  41140. });
  41141. /**
  41142. * Return the active textures of the material.
  41143. */
  41144. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41145. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41146. if (this.environmentTexture) {
  41147. activeTextures.push(this.environmentTexture);
  41148. }
  41149. if (this.normalTexture) {
  41150. activeTextures.push(this.normalTexture);
  41151. }
  41152. if (this.emissiveTexture) {
  41153. activeTextures.push(this.emissiveTexture);
  41154. }
  41155. if (this.occlusionTexture) {
  41156. activeTextures.push(this.occlusionTexture);
  41157. }
  41158. if (this.lightmapTexture) {
  41159. activeTextures.push(this.lightmapTexture);
  41160. }
  41161. return activeTextures;
  41162. };
  41163. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41164. if (_super.prototype.hasTexture.call(this, texture)) {
  41165. return true;
  41166. }
  41167. if (this.lightmapTexture === texture) {
  41168. return true;
  41169. }
  41170. return false;
  41171. };
  41172. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41173. return "PBRBaseSimpleMaterial";
  41174. };
  41175. __decorate([
  41176. BABYLON.serialize(),
  41177. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41178. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41179. __decorate([
  41180. BABYLON.serialize(),
  41181. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41182. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41183. __decorate([
  41184. BABYLON.serializeAsTexture(),
  41185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41186. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41187. __decorate([
  41188. BABYLON.serialize(),
  41189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41190. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41191. __decorate([
  41192. BABYLON.serialize(),
  41193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41194. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41195. __decorate([
  41196. BABYLON.serializeAsTexture(),
  41197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41198. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41199. __decorate([
  41200. BABYLON.serializeAsColor3("emissive"),
  41201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41202. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41203. __decorate([
  41204. BABYLON.serializeAsTexture(),
  41205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41206. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41207. __decorate([
  41208. BABYLON.serialize(),
  41209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41210. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41211. __decorate([
  41212. BABYLON.serializeAsTexture(),
  41213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41214. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41215. __decorate([
  41216. BABYLON.serialize(),
  41217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41218. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41219. __decorate([
  41220. BABYLON.serialize()
  41221. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41222. __decorate([
  41223. BABYLON.serializeAsTexture(),
  41224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41225. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41226. __decorate([
  41227. BABYLON.serialize(),
  41228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41229. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41230. return PBRBaseSimpleMaterial;
  41231. }(BABYLON.PBRBaseMaterial));
  41232. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41233. })(BABYLON || (BABYLON = {}));
  41234. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41235. var BABYLON;
  41236. (function (BABYLON) {
  41237. /**
  41238. * The Physically based material of BJS.
  41239. *
  41240. * This offers the main features of a standard PBR material.
  41241. * For more information, please refer to the documentation :
  41242. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41243. */
  41244. var PBRMaterial = /** @class */ (function (_super) {
  41245. __extends(PBRMaterial, _super);
  41246. /**
  41247. * Instantiates a new PBRMaterial instance.
  41248. *
  41249. * @param name The material name
  41250. * @param scene The scene the material will be use in.
  41251. */
  41252. function PBRMaterial(name, scene) {
  41253. var _this = _super.call(this, name, scene) || this;
  41254. /**
  41255. * Intensity of the direct lights e.g. the four lights available in your scene.
  41256. * This impacts both the direct diffuse and specular highlights.
  41257. */
  41258. _this.directIntensity = 1.0;
  41259. /**
  41260. * Intensity of the emissive part of the material.
  41261. * This helps controlling the emissive effect without modifying the emissive color.
  41262. */
  41263. _this.emissiveIntensity = 1.0;
  41264. /**
  41265. * Intensity of the environment e.g. how much the environment will light the object
  41266. * either through harmonics for rough material or through the refelction for shiny ones.
  41267. */
  41268. _this.environmentIntensity = 1.0;
  41269. /**
  41270. * This is a special control allowing the reduction of the specular highlights coming from the
  41271. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41272. */
  41273. _this.specularIntensity = 1.0;
  41274. /**
  41275. * Debug Control allowing disabling the bump map on this material.
  41276. */
  41277. _this.disableBumpMap = false;
  41278. /**
  41279. * AKA Occlusion Texture Intensity in other nomenclature.
  41280. */
  41281. _this.ambientTextureStrength = 1.0;
  41282. /**
  41283. * The color of a material in ambient lighting.
  41284. */
  41285. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41286. /**
  41287. * AKA Diffuse Color in other nomenclature.
  41288. */
  41289. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41290. /**
  41291. * AKA Specular Color in other nomenclature.
  41292. */
  41293. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41294. /**
  41295. * The color reflected from the material.
  41296. */
  41297. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41298. /**
  41299. * The color emitted from the material.
  41300. */
  41301. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41302. /**
  41303. * AKA Glossiness in other nomenclature.
  41304. */
  41305. _this.microSurface = 1.0;
  41306. /**
  41307. * source material index of refraction (IOR)' / 'destination material IOR.
  41308. */
  41309. _this.indexOfRefraction = 0.66;
  41310. /**
  41311. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41312. */
  41313. _this.invertRefractionY = false;
  41314. /**
  41315. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41316. * Materials half opaque for instance using refraction could benefit from this control.
  41317. */
  41318. _this.linkRefractionWithTransparency = false;
  41319. _this.useLightmapAsShadowmap = false;
  41320. /**
  41321. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41322. */
  41323. _this.useAlphaFromAlbedoTexture = false;
  41324. /**
  41325. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41326. */
  41327. _this.forceAlphaTest = false;
  41328. /**
  41329. * Defines the alpha limits in alpha test mode.
  41330. */
  41331. _this.alphaCutOff = 0.4;
  41332. /**
  41333. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41334. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41335. */
  41336. _this.useSpecularOverAlpha = true;
  41337. /**
  41338. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41339. */
  41340. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41341. /**
  41342. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41343. */
  41344. _this.useRoughnessFromMetallicTextureAlpha = true;
  41345. /**
  41346. * Specifies if the metallic texture contains the roughness information in its green channel.
  41347. */
  41348. _this.useRoughnessFromMetallicTextureGreen = false;
  41349. /**
  41350. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41351. */
  41352. _this.useMetallnessFromMetallicTextureBlue = false;
  41353. /**
  41354. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41355. */
  41356. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41357. /**
  41358. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41359. */
  41360. _this.useAmbientInGrayScale = false;
  41361. /**
  41362. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41363. * The material will try to infer what glossiness each pixel should be.
  41364. */
  41365. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41366. /**
  41367. * BJS is using an harcoded light falloff based on a manually sets up range.
  41368. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41369. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41370. */
  41371. _this.usePhysicalLightFalloff = true;
  41372. /**
  41373. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41374. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41375. */
  41376. _this.useRadianceOverAlpha = true;
  41377. /**
  41378. * Allows using an object space normal map (instead of tangent space).
  41379. */
  41380. _this.useObjectSpaceNormalMap = false;
  41381. /**
  41382. * Allows using the bump map in parallax mode.
  41383. */
  41384. _this.useParallax = false;
  41385. /**
  41386. * Allows using the bump map in parallax occlusion mode.
  41387. */
  41388. _this.useParallaxOcclusion = false;
  41389. /**
  41390. * Controls the scale bias of the parallax mode.
  41391. */
  41392. _this.parallaxScaleBias = 0.05;
  41393. /**
  41394. * If sets to true, disables all the lights affecting the material.
  41395. */
  41396. _this.disableLighting = false;
  41397. /**
  41398. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41399. */
  41400. _this.forceIrradianceInFragment = false;
  41401. /**
  41402. * Number of Simultaneous lights allowed on the material.
  41403. */
  41404. _this.maxSimultaneousLights = 4;
  41405. /**
  41406. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41407. */
  41408. _this.invertNormalMapX = false;
  41409. /**
  41410. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41411. */
  41412. _this.invertNormalMapY = false;
  41413. /**
  41414. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41415. */
  41416. _this.twoSidedLighting = false;
  41417. /**
  41418. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41419. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41420. */
  41421. _this.useAlphaFresnel = false;
  41422. /**
  41423. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41424. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41425. */
  41426. _this.useLinearAlphaFresnel = false;
  41427. /**
  41428. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41429. * And/Or occlude the blended part.
  41430. */
  41431. _this.environmentBRDFTexture = null;
  41432. /**
  41433. * Force normal to face away from face.
  41434. */
  41435. _this.forceNormalForward = false;
  41436. /**
  41437. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41438. * makes the reflect vector face the model (under horizon).
  41439. */
  41440. _this.useHorizonOcclusion = true;
  41441. /**
  41442. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41443. * too much the area relying on ambient texture to define their ambient occlusion.
  41444. */
  41445. _this.useRadianceOcclusion = true;
  41446. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41447. return _this;
  41448. }
  41449. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41450. /**
  41451. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41452. */
  41453. get: function () {
  41454. return this._PBRMATERIAL_OPAQUE;
  41455. },
  41456. enumerable: true,
  41457. configurable: true
  41458. });
  41459. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41460. /**
  41461. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41462. */
  41463. get: function () {
  41464. return this._PBRMATERIAL_ALPHATEST;
  41465. },
  41466. enumerable: true,
  41467. configurable: true
  41468. });
  41469. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41470. /**
  41471. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41472. */
  41473. get: function () {
  41474. return this._PBRMATERIAL_ALPHABLEND;
  41475. },
  41476. enumerable: true,
  41477. configurable: true
  41478. });
  41479. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41480. /**
  41481. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41482. * They are also discarded below the alpha cutoff threshold to improve performances.
  41483. */
  41484. get: function () {
  41485. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41486. },
  41487. enumerable: true,
  41488. configurable: true
  41489. });
  41490. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41491. /**
  41492. * Gets the image processing configuration used either in this material.
  41493. */
  41494. get: function () {
  41495. return this._imageProcessingConfiguration;
  41496. },
  41497. /**
  41498. * Sets the Default image processing configuration used either in the this material.
  41499. *
  41500. * If sets to null, the scene one is in use.
  41501. */
  41502. set: function (value) {
  41503. this._attachImageProcessingConfiguration(value);
  41504. // Ensure the effect will be rebuilt.
  41505. this._markAllSubMeshesAsTexturesDirty();
  41506. },
  41507. enumerable: true,
  41508. configurable: true
  41509. });
  41510. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41511. /**
  41512. * Gets wether the color curves effect is enabled.
  41513. */
  41514. get: function () {
  41515. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41516. },
  41517. /**
  41518. * Sets wether the color curves effect is enabled.
  41519. */
  41520. set: function (value) {
  41521. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41522. },
  41523. enumerable: true,
  41524. configurable: true
  41525. });
  41526. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  41527. /**
  41528. * Gets wether the color grading effect is enabled.
  41529. */
  41530. get: function () {
  41531. return this.imageProcessingConfiguration.colorGradingEnabled;
  41532. },
  41533. /**
  41534. * Gets wether the color grading effect is enabled.
  41535. */
  41536. set: function (value) {
  41537. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41538. },
  41539. enumerable: true,
  41540. configurable: true
  41541. });
  41542. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  41543. /**
  41544. * Gets wether tonemapping is enabled or not.
  41545. */
  41546. get: function () {
  41547. return this._imageProcessingConfiguration.toneMappingEnabled;
  41548. },
  41549. /**
  41550. * Sets wether tonemapping is enabled or not
  41551. */
  41552. set: function (value) {
  41553. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41554. },
  41555. enumerable: true,
  41556. configurable: true
  41557. });
  41558. ;
  41559. ;
  41560. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  41561. /**
  41562. * The camera exposure used on this material.
  41563. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41564. * This corresponds to a photographic exposure.
  41565. */
  41566. get: function () {
  41567. return this._imageProcessingConfiguration.exposure;
  41568. },
  41569. /**
  41570. * The camera exposure used on this material.
  41571. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41572. * This corresponds to a photographic exposure.
  41573. */
  41574. set: function (value) {
  41575. this._imageProcessingConfiguration.exposure = value;
  41576. },
  41577. enumerable: true,
  41578. configurable: true
  41579. });
  41580. ;
  41581. ;
  41582. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  41583. /**
  41584. * Gets The camera contrast used on this material.
  41585. */
  41586. get: function () {
  41587. return this._imageProcessingConfiguration.contrast;
  41588. },
  41589. /**
  41590. * Sets The camera contrast used on this material.
  41591. */
  41592. set: function (value) {
  41593. this._imageProcessingConfiguration.contrast = value;
  41594. },
  41595. enumerable: true,
  41596. configurable: true
  41597. });
  41598. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  41599. /**
  41600. * Gets the Color Grading 2D Lookup Texture.
  41601. */
  41602. get: function () {
  41603. return this._imageProcessingConfiguration.colorGradingTexture;
  41604. },
  41605. /**
  41606. * Sets the Color Grading 2D Lookup Texture.
  41607. */
  41608. set: function (value) {
  41609. this._imageProcessingConfiguration.colorGradingTexture = value;
  41610. },
  41611. enumerable: true,
  41612. configurable: true
  41613. });
  41614. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  41615. /**
  41616. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41617. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41618. * 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;
  41619. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41620. */
  41621. get: function () {
  41622. return this._imageProcessingConfiguration.colorCurves;
  41623. },
  41624. /**
  41625. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41626. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41627. * 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;
  41628. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41629. */
  41630. set: function (value) {
  41631. this._imageProcessingConfiguration.colorCurves = value;
  41632. },
  41633. enumerable: true,
  41634. configurable: true
  41635. });
  41636. /**
  41637. * Returns the name of this material class.
  41638. */
  41639. PBRMaterial.prototype.getClassName = function () {
  41640. return "PBRMaterial";
  41641. };
  41642. /**
  41643. * Returns an array of the actively used textures.
  41644. * @returns - Array of BaseTextures
  41645. */
  41646. PBRMaterial.prototype.getActiveTextures = function () {
  41647. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41648. if (this._albedoTexture) {
  41649. activeTextures.push(this._albedoTexture);
  41650. }
  41651. if (this._ambientTexture) {
  41652. activeTextures.push(this._ambientTexture);
  41653. }
  41654. if (this._opacityTexture) {
  41655. activeTextures.push(this._opacityTexture);
  41656. }
  41657. if (this._reflectionTexture) {
  41658. activeTextures.push(this._reflectionTexture);
  41659. }
  41660. if (this._emissiveTexture) {
  41661. activeTextures.push(this._emissiveTexture);
  41662. }
  41663. if (this._reflectivityTexture) {
  41664. activeTextures.push(this._reflectivityTexture);
  41665. }
  41666. if (this._metallicTexture) {
  41667. activeTextures.push(this._metallicTexture);
  41668. }
  41669. if (this._microSurfaceTexture) {
  41670. activeTextures.push(this._microSurfaceTexture);
  41671. }
  41672. if (this._bumpTexture) {
  41673. activeTextures.push(this._bumpTexture);
  41674. }
  41675. if (this._lightmapTexture) {
  41676. activeTextures.push(this._lightmapTexture);
  41677. }
  41678. if (this._refractionTexture) {
  41679. activeTextures.push(this._refractionTexture);
  41680. }
  41681. return activeTextures;
  41682. };
  41683. /**
  41684. * Checks to see if a texture is used in the material.
  41685. * @param texture - Base texture to use.
  41686. * @returns - Boolean specifying if a texture is used in the material.
  41687. */
  41688. PBRMaterial.prototype.hasTexture = function (texture) {
  41689. if (_super.prototype.hasTexture.call(this, texture)) {
  41690. return true;
  41691. }
  41692. if (this._albedoTexture === texture) {
  41693. return true;
  41694. }
  41695. if (this._ambientTexture === texture) {
  41696. return true;
  41697. }
  41698. if (this._opacityTexture === texture) {
  41699. return true;
  41700. }
  41701. if (this._reflectionTexture === texture) {
  41702. return true;
  41703. }
  41704. if (this._reflectivityTexture === texture) {
  41705. return true;
  41706. }
  41707. if (this._metallicTexture === texture) {
  41708. return true;
  41709. }
  41710. if (this._microSurfaceTexture === texture) {
  41711. return true;
  41712. }
  41713. if (this._bumpTexture === texture) {
  41714. return true;
  41715. }
  41716. if (this._lightmapTexture === texture) {
  41717. return true;
  41718. }
  41719. if (this._refractionTexture === texture) {
  41720. return true;
  41721. }
  41722. return false;
  41723. };
  41724. /**
  41725. * Makes a duplicate of the current material.
  41726. * @param name - name to use for the new material.
  41727. */
  41728. PBRMaterial.prototype.clone = function (name) {
  41729. var _this = this;
  41730. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  41731. clone.id = name;
  41732. clone.name = name;
  41733. return clone;
  41734. };
  41735. /**
  41736. * Serializes this PBR Material.
  41737. * @returns - An object with the serialized material.
  41738. */
  41739. PBRMaterial.prototype.serialize = function () {
  41740. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41741. serializationObject.customType = "BABYLON.PBRMaterial";
  41742. return serializationObject;
  41743. };
  41744. // Statics
  41745. /**
  41746. * Parses a PBR Material from a serialized object.
  41747. * @param source - Serialized object.
  41748. * @param scene - BJS scene instance.
  41749. * @param rootUrl - url for the scene object
  41750. * @returns - PBRMaterial
  41751. */
  41752. PBRMaterial.Parse = function (source, scene, rootUrl) {
  41753. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  41754. };
  41755. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  41756. /**
  41757. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41758. */
  41759. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  41760. /**
  41761. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41762. */
  41763. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  41764. /**
  41765. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41766. * They are also discarded below the alpha cutoff threshold to improve performances.
  41767. */
  41768. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  41769. __decorate([
  41770. BABYLON.serialize(),
  41771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41772. ], PBRMaterial.prototype, "directIntensity", void 0);
  41773. __decorate([
  41774. BABYLON.serialize(),
  41775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41776. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  41777. __decorate([
  41778. BABYLON.serialize(),
  41779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41780. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  41781. __decorate([
  41782. BABYLON.serialize(),
  41783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41784. ], PBRMaterial.prototype, "specularIntensity", void 0);
  41785. __decorate([
  41786. BABYLON.serialize(),
  41787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41788. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  41789. __decorate([
  41790. BABYLON.serializeAsTexture(),
  41791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41792. ], PBRMaterial.prototype, "albedoTexture", void 0);
  41793. __decorate([
  41794. BABYLON.serializeAsTexture(),
  41795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41796. ], PBRMaterial.prototype, "ambientTexture", void 0);
  41797. __decorate([
  41798. BABYLON.serialize(),
  41799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41800. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  41801. __decorate([
  41802. BABYLON.serializeAsTexture(),
  41803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41804. ], PBRMaterial.prototype, "opacityTexture", void 0);
  41805. __decorate([
  41806. BABYLON.serializeAsTexture(),
  41807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41808. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  41809. __decorate([
  41810. BABYLON.serializeAsTexture(),
  41811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41812. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  41813. __decorate([
  41814. BABYLON.serializeAsTexture(),
  41815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41816. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  41817. __decorate([
  41818. BABYLON.serializeAsTexture(),
  41819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41820. ], PBRMaterial.prototype, "metallicTexture", void 0);
  41821. __decorate([
  41822. BABYLON.serialize(),
  41823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41824. ], PBRMaterial.prototype, "metallic", void 0);
  41825. __decorate([
  41826. BABYLON.serialize(),
  41827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41828. ], PBRMaterial.prototype, "roughness", void 0);
  41829. __decorate([
  41830. BABYLON.serializeAsTexture(),
  41831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41832. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  41833. __decorate([
  41834. BABYLON.serializeAsTexture(),
  41835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41836. ], PBRMaterial.prototype, "bumpTexture", void 0);
  41837. __decorate([
  41838. BABYLON.serializeAsTexture(),
  41839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41840. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  41841. __decorate([
  41842. BABYLON.serializeAsTexture(),
  41843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41844. ], PBRMaterial.prototype, "refractionTexture", void 0);
  41845. __decorate([
  41846. BABYLON.serializeAsColor3("ambient"),
  41847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41848. ], PBRMaterial.prototype, "ambientColor", void 0);
  41849. __decorate([
  41850. BABYLON.serializeAsColor3("albedo"),
  41851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41852. ], PBRMaterial.prototype, "albedoColor", void 0);
  41853. __decorate([
  41854. BABYLON.serializeAsColor3("reflectivity"),
  41855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41856. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  41857. __decorate([
  41858. BABYLON.serializeAsColor3("reflection"),
  41859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41860. ], PBRMaterial.prototype, "reflectionColor", void 0);
  41861. __decorate([
  41862. BABYLON.serializeAsColor3("emissive"),
  41863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41864. ], PBRMaterial.prototype, "emissiveColor", void 0);
  41865. __decorate([
  41866. BABYLON.serialize(),
  41867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41868. ], PBRMaterial.prototype, "microSurface", void 0);
  41869. __decorate([
  41870. BABYLON.serialize(),
  41871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41872. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  41873. __decorate([
  41874. BABYLON.serialize(),
  41875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41876. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  41877. __decorate([
  41878. BABYLON.serialize(),
  41879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41880. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  41881. __decorate([
  41882. BABYLON.serialize(),
  41883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41884. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41885. __decorate([
  41886. BABYLON.serialize(),
  41887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41888. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  41889. __decorate([
  41890. BABYLON.serialize(),
  41891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41892. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  41893. __decorate([
  41894. BABYLON.serialize(),
  41895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41896. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  41897. __decorate([
  41898. BABYLON.serialize(),
  41899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41900. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  41901. __decorate([
  41902. BABYLON.serialize(),
  41903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41904. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  41905. __decorate([
  41906. BABYLON.serialize(),
  41907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41908. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  41909. __decorate([
  41910. BABYLON.serialize(),
  41911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41912. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  41913. __decorate([
  41914. BABYLON.serialize(),
  41915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41916. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  41917. __decorate([
  41918. BABYLON.serialize(),
  41919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41920. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  41921. __decorate([
  41922. BABYLON.serialize(),
  41923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41924. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  41925. __decorate([
  41926. BABYLON.serialize(),
  41927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41928. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  41929. __decorate([
  41930. BABYLON.serialize(),
  41931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41932. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  41933. __decorate([
  41934. BABYLON.serialize(),
  41935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41936. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  41937. __decorate([
  41938. BABYLON.serialize(),
  41939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41940. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  41941. __decorate([
  41942. BABYLON.serialize(),
  41943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41944. ], PBRMaterial.prototype, "useParallax", void 0);
  41945. __decorate([
  41946. BABYLON.serialize(),
  41947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41948. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  41949. __decorate([
  41950. BABYLON.serialize(),
  41951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41952. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  41953. __decorate([
  41954. BABYLON.serialize(),
  41955. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41956. ], PBRMaterial.prototype, "disableLighting", void 0);
  41957. __decorate([
  41958. BABYLON.serialize(),
  41959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41960. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  41961. __decorate([
  41962. BABYLON.serialize(),
  41963. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41964. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  41965. __decorate([
  41966. BABYLON.serialize(),
  41967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41968. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  41969. __decorate([
  41970. BABYLON.serialize(),
  41971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41972. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  41973. __decorate([
  41974. BABYLON.serialize(),
  41975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41976. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  41977. __decorate([
  41978. BABYLON.serialize(),
  41979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41980. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  41981. __decorate([
  41982. BABYLON.serialize(),
  41983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41984. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  41985. __decorate([
  41986. BABYLON.serializeAsTexture(),
  41987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41988. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  41989. __decorate([
  41990. BABYLON.serialize(),
  41991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41992. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  41993. __decorate([
  41994. BABYLON.serialize(),
  41995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41996. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  41997. __decorate([
  41998. BABYLON.serialize(),
  41999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42000. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42001. return PBRMaterial;
  42002. }(BABYLON.PBRBaseMaterial));
  42003. BABYLON.PBRMaterial = PBRMaterial;
  42004. })(BABYLON || (BABYLON = {}));
  42005. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42006. var BABYLON;
  42007. (function (BABYLON) {
  42008. /**
  42009. * The PBR material of BJS following the metal roughness convention.
  42010. *
  42011. * This fits to the PBR convention in the GLTF definition:
  42012. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42013. */
  42014. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42015. __extends(PBRMetallicRoughnessMaterial, _super);
  42016. /**
  42017. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42018. *
  42019. * @param name The material name
  42020. * @param scene The scene the material will be use in.
  42021. */
  42022. function PBRMetallicRoughnessMaterial(name, scene) {
  42023. var _this = _super.call(this, name, scene) || this;
  42024. _this._useRoughnessFromMetallicTextureAlpha = false;
  42025. _this._useRoughnessFromMetallicTextureGreen = true;
  42026. _this._useMetallnessFromMetallicTextureBlue = true;
  42027. _this._forceMetallicWorkflow = true;
  42028. return _this;
  42029. }
  42030. /**
  42031. * Return the currrent class name of the material.
  42032. */
  42033. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42034. return "PBRMetallicRoughnessMaterial";
  42035. };
  42036. /**
  42037. * Return the active textures of the material.
  42038. */
  42039. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42040. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42041. if (this.baseTexture) {
  42042. activeTextures.push(this.baseTexture);
  42043. }
  42044. if (this.metallicRoughnessTexture) {
  42045. activeTextures.push(this.metallicRoughnessTexture);
  42046. }
  42047. return activeTextures;
  42048. };
  42049. /**
  42050. * Checks to see if a texture is used in the material.
  42051. * @param texture - Base texture to use.
  42052. * @returns - Boolean specifying if a texture is used in the material.
  42053. */
  42054. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42055. if (_super.prototype.hasTexture.call(this, texture)) {
  42056. return true;
  42057. }
  42058. if (this.baseTexture === texture) {
  42059. return true;
  42060. }
  42061. if (this.metallicRoughnessTexture === texture) {
  42062. return true;
  42063. }
  42064. return false;
  42065. };
  42066. /**
  42067. * Makes a duplicate of the current material.
  42068. * @param name - name to use for the new material.
  42069. */
  42070. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42071. var _this = this;
  42072. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42073. clone.id = name;
  42074. clone.name = name;
  42075. return clone;
  42076. };
  42077. /**
  42078. * Serialize the material to a parsable JSON object.
  42079. */
  42080. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42081. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42082. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42083. return serializationObject;
  42084. };
  42085. /**
  42086. * Parses a JSON object correponding to the serialize function.
  42087. */
  42088. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42089. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42090. };
  42091. __decorate([
  42092. BABYLON.serializeAsColor3(),
  42093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42094. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42095. __decorate([
  42096. BABYLON.serializeAsTexture(),
  42097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42098. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42099. __decorate([
  42100. BABYLON.serialize(),
  42101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42102. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42103. __decorate([
  42104. BABYLON.serialize(),
  42105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42106. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42107. __decorate([
  42108. BABYLON.serializeAsTexture(),
  42109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42110. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42111. return PBRMetallicRoughnessMaterial;
  42112. }(BABYLON.PBRBaseSimpleMaterial));
  42113. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42114. })(BABYLON || (BABYLON = {}));
  42115. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42116. var BABYLON;
  42117. (function (BABYLON) {
  42118. /**
  42119. * The PBR material of BJS following the specular glossiness convention.
  42120. *
  42121. * This fits to the PBR convention in the GLTF definition:
  42122. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42123. */
  42124. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42125. __extends(PBRSpecularGlossinessMaterial, _super);
  42126. /**
  42127. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42128. *
  42129. * @param name The material name
  42130. * @param scene The scene the material will be use in.
  42131. */
  42132. function PBRSpecularGlossinessMaterial(name, scene) {
  42133. var _this = _super.call(this, name, scene) || this;
  42134. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42135. return _this;
  42136. }
  42137. /**
  42138. * Return the currrent class name of the material.
  42139. */
  42140. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42141. return "PBRSpecularGlossinessMaterial";
  42142. };
  42143. /**
  42144. * Return the active textures of the material.
  42145. */
  42146. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42147. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42148. if (this.diffuseTexture) {
  42149. activeTextures.push(this.diffuseTexture);
  42150. }
  42151. if (this.specularGlossinessTexture) {
  42152. activeTextures.push(this.specularGlossinessTexture);
  42153. }
  42154. return activeTextures;
  42155. };
  42156. /**
  42157. * Checks to see if a texture is used in the material.
  42158. * @param texture - Base texture to use.
  42159. * @returns - Boolean specifying if a texture is used in the material.
  42160. */
  42161. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42162. if (_super.prototype.hasTexture.call(this, texture)) {
  42163. return true;
  42164. }
  42165. if (this.diffuseTexture === texture) {
  42166. return true;
  42167. }
  42168. if (this.specularGlossinessTexture === texture) {
  42169. return true;
  42170. }
  42171. return false;
  42172. };
  42173. /**
  42174. * Makes a duplicate of the current material.
  42175. * @param name - name to use for the new material.
  42176. */
  42177. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42178. var _this = this;
  42179. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42180. clone.id = name;
  42181. clone.name = name;
  42182. return clone;
  42183. };
  42184. /**
  42185. * Serialize the material to a parsable JSON object.
  42186. */
  42187. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42188. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42189. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42190. return serializationObject;
  42191. };
  42192. /**
  42193. * Parses a JSON object correponding to the serialize function.
  42194. */
  42195. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42196. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42197. };
  42198. __decorate([
  42199. BABYLON.serializeAsColor3("diffuse"),
  42200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42201. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42202. __decorate([
  42203. BABYLON.serializeAsTexture(),
  42204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42205. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42206. __decorate([
  42207. BABYLON.serializeAsColor3("specular"),
  42208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42209. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42210. __decorate([
  42211. BABYLON.serialize(),
  42212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42213. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42214. __decorate([
  42215. BABYLON.serializeAsTexture(),
  42216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42217. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42218. return PBRSpecularGlossinessMaterial;
  42219. }(BABYLON.PBRBaseSimpleMaterial));
  42220. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42221. })(BABYLON || (BABYLON = {}));
  42222. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42223. var BABYLON;
  42224. (function (BABYLON) {
  42225. BABYLON.CameraInputTypes = {};
  42226. var CameraInputsManager = /** @class */ (function () {
  42227. function CameraInputsManager(camera) {
  42228. this.attached = {};
  42229. this.camera = camera;
  42230. this.checkInputs = function () { };
  42231. }
  42232. /**
  42233. * Add an input method to a camera.
  42234. * builtin inputs example: camera.inputs.addGamepad();
  42235. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42236. * @param input camera input method
  42237. */
  42238. CameraInputsManager.prototype.add = function (input) {
  42239. var type = input.getSimpleName();
  42240. if (this.attached[type]) {
  42241. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42242. return;
  42243. }
  42244. this.attached[type] = input;
  42245. input.camera = this.camera;
  42246. //for checkInputs, we are dynamically creating a function
  42247. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42248. if (input.checkInputs) {
  42249. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42250. }
  42251. if (this.attachedElement) {
  42252. input.attachControl(this.attachedElement);
  42253. }
  42254. };
  42255. /**
  42256. * Remove a specific input method from a camera
  42257. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42258. * @param inputToRemove camera input method
  42259. */
  42260. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42261. for (var cam in this.attached) {
  42262. var input = this.attached[cam];
  42263. if (input === inputToRemove) {
  42264. input.detachControl(this.attachedElement);
  42265. input.camera = null;
  42266. delete this.attached[cam];
  42267. this.rebuildInputCheck();
  42268. }
  42269. }
  42270. };
  42271. CameraInputsManager.prototype.removeByType = function (inputType) {
  42272. for (var cam in this.attached) {
  42273. var input = this.attached[cam];
  42274. if (input.getClassName() === inputType) {
  42275. input.detachControl(this.attachedElement);
  42276. input.camera = null;
  42277. delete this.attached[cam];
  42278. this.rebuildInputCheck();
  42279. }
  42280. }
  42281. };
  42282. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42283. var current = this.checkInputs;
  42284. return function () {
  42285. current();
  42286. fn();
  42287. };
  42288. };
  42289. CameraInputsManager.prototype.attachInput = function (input) {
  42290. if (this.attachedElement) {
  42291. input.attachControl(this.attachedElement, this.noPreventDefault);
  42292. }
  42293. };
  42294. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42295. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42296. if (this.attachedElement) {
  42297. return;
  42298. }
  42299. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42300. this.attachedElement = element;
  42301. this.noPreventDefault = noPreventDefault;
  42302. for (var cam in this.attached) {
  42303. this.attached[cam].attachControl(element, noPreventDefault);
  42304. }
  42305. };
  42306. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42307. if (disconnect === void 0) { disconnect = false; }
  42308. if (this.attachedElement !== element) {
  42309. return;
  42310. }
  42311. for (var cam in this.attached) {
  42312. this.attached[cam].detachControl(element);
  42313. if (disconnect) {
  42314. this.attached[cam].camera = null;
  42315. }
  42316. }
  42317. this.attachedElement = null;
  42318. };
  42319. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42320. this.checkInputs = function () { };
  42321. for (var cam in this.attached) {
  42322. var input = this.attached[cam];
  42323. if (input.checkInputs) {
  42324. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42325. }
  42326. }
  42327. };
  42328. /**
  42329. * Remove all attached input methods from a camera
  42330. */
  42331. CameraInputsManager.prototype.clear = function () {
  42332. if (this.attachedElement) {
  42333. this.detachElement(this.attachedElement, true);
  42334. }
  42335. this.attached = {};
  42336. this.attachedElement = null;
  42337. this.checkInputs = function () { };
  42338. };
  42339. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42340. var inputs = {};
  42341. for (var cam in this.attached) {
  42342. var input = this.attached[cam];
  42343. var res = BABYLON.SerializationHelper.Serialize(input);
  42344. inputs[input.getClassName()] = res;
  42345. }
  42346. serializedCamera.inputsmgr = inputs;
  42347. };
  42348. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42349. var parsedInputs = parsedCamera.inputsmgr;
  42350. if (parsedInputs) {
  42351. this.clear();
  42352. for (var n in parsedInputs) {
  42353. var construct = BABYLON.CameraInputTypes[n];
  42354. if (construct) {
  42355. var parsedinput = parsedInputs[n];
  42356. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42357. this.add(input);
  42358. }
  42359. }
  42360. }
  42361. else {
  42362. //2016-03-08 this part is for managing backward compatibility
  42363. for (var n in this.attached) {
  42364. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42365. if (construct) {
  42366. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42367. this.remove(this.attached[n]);
  42368. this.add(input);
  42369. }
  42370. }
  42371. }
  42372. };
  42373. return CameraInputsManager;
  42374. }());
  42375. BABYLON.CameraInputsManager = CameraInputsManager;
  42376. })(BABYLON || (BABYLON = {}));
  42377. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42378. var BABYLON;
  42379. (function (BABYLON) {
  42380. var TargetCamera = /** @class */ (function (_super) {
  42381. __extends(TargetCamera, _super);
  42382. function TargetCamera(name, position, scene) {
  42383. var _this = _super.call(this, name, position, scene) || this;
  42384. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42385. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42386. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42387. _this.speed = 2.0;
  42388. _this.noRotationConstraint = false;
  42389. _this.lockedTarget = null;
  42390. _this._currentTarget = BABYLON.Vector3.Zero();
  42391. _this._viewMatrix = BABYLON.Matrix.Zero();
  42392. _this._camMatrix = BABYLON.Matrix.Zero();
  42393. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42394. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42395. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42396. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42397. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42398. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42399. _this._tempMatrix = BABYLON.Matrix.Zero();
  42400. return _this;
  42401. }
  42402. TargetCamera.prototype.getFrontPosition = function (distance) {
  42403. this.getWorldMatrix();
  42404. var direction = this.getTarget().subtract(this.position);
  42405. direction.normalize();
  42406. direction.scaleInPlace(distance);
  42407. return this.globalPosition.add(direction);
  42408. };
  42409. TargetCamera.prototype._getLockedTargetPosition = function () {
  42410. if (!this.lockedTarget) {
  42411. return null;
  42412. }
  42413. if (this.lockedTarget.absolutePosition) {
  42414. this.lockedTarget.computeWorldMatrix();
  42415. }
  42416. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42417. };
  42418. TargetCamera.prototype.storeState = function () {
  42419. this._storedPosition = this.position.clone();
  42420. this._storedRotation = this.rotation.clone();
  42421. if (this.rotationQuaternion) {
  42422. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42423. }
  42424. return _super.prototype.storeState.call(this);
  42425. };
  42426. /**
  42427. * Restored camera state. You must call storeState() first
  42428. */
  42429. TargetCamera.prototype._restoreStateValues = function () {
  42430. if (!_super.prototype._restoreStateValues.call(this)) {
  42431. return false;
  42432. }
  42433. this.position = this._storedPosition.clone();
  42434. this.rotation = this._storedRotation.clone();
  42435. if (this.rotationQuaternion) {
  42436. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42437. }
  42438. this.cameraDirection.copyFromFloats(0, 0, 0);
  42439. this.cameraRotation.copyFromFloats(0, 0);
  42440. return true;
  42441. };
  42442. // Cache
  42443. TargetCamera.prototype._initCache = function () {
  42444. _super.prototype._initCache.call(this);
  42445. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42446. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42447. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42448. };
  42449. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42450. if (!ignoreParentClass) {
  42451. _super.prototype._updateCache.call(this);
  42452. }
  42453. var lockedTargetPosition = this._getLockedTargetPosition();
  42454. if (!lockedTargetPosition) {
  42455. this._cache.lockedTarget = null;
  42456. }
  42457. else {
  42458. if (!this._cache.lockedTarget) {
  42459. this._cache.lockedTarget = lockedTargetPosition.clone();
  42460. }
  42461. else {
  42462. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42463. }
  42464. }
  42465. this._cache.rotation.copyFrom(this.rotation);
  42466. if (this.rotationQuaternion)
  42467. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42468. };
  42469. // Synchronized
  42470. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42471. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42472. return false;
  42473. }
  42474. var lockedTargetPosition = this._getLockedTargetPosition();
  42475. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42476. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42477. };
  42478. // Methods
  42479. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42480. var engine = this.getEngine();
  42481. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42482. };
  42483. // Target
  42484. TargetCamera.prototype.setTarget = function (target) {
  42485. this.upVector.normalize();
  42486. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42487. this._camMatrix.invert();
  42488. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42489. var vDir = target.subtract(this.position);
  42490. if (vDir.x >= 0.0) {
  42491. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42492. }
  42493. else {
  42494. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42495. }
  42496. this.rotation.z = 0;
  42497. if (isNaN(this.rotation.x)) {
  42498. this.rotation.x = 0;
  42499. }
  42500. if (isNaN(this.rotation.y)) {
  42501. this.rotation.y = 0;
  42502. }
  42503. if (isNaN(this.rotation.z)) {
  42504. this.rotation.z = 0;
  42505. }
  42506. if (this.rotationQuaternion) {
  42507. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42508. }
  42509. };
  42510. /**
  42511. * Return the current target position of the camera. This value is expressed in local space.
  42512. */
  42513. TargetCamera.prototype.getTarget = function () {
  42514. return this._currentTarget;
  42515. };
  42516. TargetCamera.prototype._decideIfNeedsToMove = function () {
  42517. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42518. };
  42519. TargetCamera.prototype._updatePosition = function () {
  42520. if (this.parent) {
  42521. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  42522. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  42523. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  42524. return;
  42525. }
  42526. this.position.addInPlace(this.cameraDirection);
  42527. };
  42528. TargetCamera.prototype._checkInputs = function () {
  42529. var needToMove = this._decideIfNeedsToMove();
  42530. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  42531. // Move
  42532. if (needToMove) {
  42533. this._updatePosition();
  42534. }
  42535. // Rotate
  42536. if (needToRotate) {
  42537. this.rotation.x += this.cameraRotation.x;
  42538. this.rotation.y += this.cameraRotation.y;
  42539. //rotate, if quaternion is set and rotation was used
  42540. if (this.rotationQuaternion) {
  42541. var len = this.rotation.lengthSquared();
  42542. if (len) {
  42543. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42544. }
  42545. }
  42546. if (!this.noRotationConstraint) {
  42547. var limit = (Math.PI / 2) * 0.95;
  42548. if (this.rotation.x > limit)
  42549. this.rotation.x = limit;
  42550. if (this.rotation.x < -limit)
  42551. this.rotation.x = -limit;
  42552. }
  42553. }
  42554. // Inertia
  42555. if (needToMove) {
  42556. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  42557. this.cameraDirection.x = 0;
  42558. }
  42559. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  42560. this.cameraDirection.y = 0;
  42561. }
  42562. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  42563. this.cameraDirection.z = 0;
  42564. }
  42565. this.cameraDirection.scaleInPlace(this.inertia);
  42566. }
  42567. if (needToRotate) {
  42568. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  42569. this.cameraRotation.x = 0;
  42570. }
  42571. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  42572. this.cameraRotation.y = 0;
  42573. }
  42574. this.cameraRotation.scaleInPlace(this.inertia);
  42575. }
  42576. _super.prototype._checkInputs.call(this);
  42577. };
  42578. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  42579. if (this.rotationQuaternion) {
  42580. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  42581. }
  42582. else {
  42583. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  42584. }
  42585. //update the up vector!
  42586. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  42587. };
  42588. TargetCamera.prototype._getViewMatrix = function () {
  42589. if (this.lockedTarget) {
  42590. this.setTarget(this._getLockedTargetPosition());
  42591. }
  42592. // Compute
  42593. this._updateCameraRotationMatrix();
  42594. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  42595. // Computing target and final matrix
  42596. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  42597. if (this.getScene().useRightHandedSystem) {
  42598. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42599. }
  42600. else {
  42601. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42602. }
  42603. return this._viewMatrix;
  42604. };
  42605. /**
  42606. * @override
  42607. * Override Camera.createRigCamera
  42608. */
  42609. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42610. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  42611. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  42612. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  42613. if (!this.rotationQuaternion) {
  42614. this.rotationQuaternion = new BABYLON.Quaternion();
  42615. }
  42616. rigCamera._cameraRigParams = {};
  42617. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  42618. }
  42619. return rigCamera;
  42620. }
  42621. return null;
  42622. };
  42623. /**
  42624. * @override
  42625. * Override Camera._updateRigCameras
  42626. */
  42627. TargetCamera.prototype._updateRigCameras = function () {
  42628. var camLeft = this._rigCameras[0];
  42629. var camRight = this._rigCameras[1];
  42630. switch (this.cameraRigMode) {
  42631. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42632. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42633. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42634. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42635. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  42636. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  42637. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  42638. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  42639. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  42640. camLeft.setTarget(this.getTarget());
  42641. camRight.setTarget(this.getTarget());
  42642. break;
  42643. case BABYLON.Camera.RIG_MODE_VR:
  42644. if (camLeft.rotationQuaternion) {
  42645. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42646. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42647. }
  42648. else {
  42649. camLeft.rotation.copyFrom(this.rotation);
  42650. camRight.rotation.copyFrom(this.rotation);
  42651. }
  42652. camLeft.position.copyFrom(this.position);
  42653. camRight.position.copyFrom(this.position);
  42654. break;
  42655. }
  42656. _super.prototype._updateRigCameras.call(this);
  42657. };
  42658. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  42659. if (!this._rigCamTransformMatrix) {
  42660. this._rigCamTransformMatrix = new BABYLON.Matrix();
  42661. }
  42662. var target = this.getTarget();
  42663. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  42664. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  42665. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  42666. };
  42667. TargetCamera.prototype.getClassName = function () {
  42668. return "TargetCamera";
  42669. };
  42670. __decorate([
  42671. BABYLON.serializeAsVector3()
  42672. ], TargetCamera.prototype, "rotation", void 0);
  42673. __decorate([
  42674. BABYLON.serialize()
  42675. ], TargetCamera.prototype, "speed", void 0);
  42676. __decorate([
  42677. BABYLON.serializeAsMeshReference("lockedTargetId")
  42678. ], TargetCamera.prototype, "lockedTarget", void 0);
  42679. return TargetCamera;
  42680. }(BABYLON.Camera));
  42681. BABYLON.TargetCamera = TargetCamera;
  42682. })(BABYLON || (BABYLON = {}));
  42683. //# sourceMappingURL=babylon.targetCamera.js.map
  42684. var BABYLON;
  42685. (function (BABYLON) {
  42686. var FreeCameraMouseInput = /** @class */ (function () {
  42687. function FreeCameraMouseInput(touchEnabled) {
  42688. if (touchEnabled === void 0) { touchEnabled = true; }
  42689. this.touchEnabled = touchEnabled;
  42690. this.buttons = [0, 1, 2];
  42691. this.angularSensibility = 2000.0;
  42692. this.previousPosition = null;
  42693. }
  42694. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  42695. var _this = this;
  42696. var engine = this.camera.getEngine();
  42697. if (!this._pointerInput) {
  42698. this._pointerInput = function (p, s) {
  42699. var evt = p.event;
  42700. if (engine.isInVRExclusivePointerMode) {
  42701. return;
  42702. }
  42703. if (!_this.touchEnabled && evt.pointerType === "touch") {
  42704. return;
  42705. }
  42706. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  42707. return;
  42708. }
  42709. var srcElement = (evt.srcElement || evt.target);
  42710. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  42711. try {
  42712. srcElement.setPointerCapture(evt.pointerId);
  42713. }
  42714. catch (e) {
  42715. //Nothing to do with the error. Execution will continue.
  42716. }
  42717. _this.previousPosition = {
  42718. x: evt.clientX,
  42719. y: evt.clientY
  42720. };
  42721. if (!noPreventDefault) {
  42722. evt.preventDefault();
  42723. element.focus();
  42724. }
  42725. }
  42726. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  42727. try {
  42728. srcElement.releasePointerCapture(evt.pointerId);
  42729. }
  42730. catch (e) {
  42731. //Nothing to do with the error.
  42732. }
  42733. _this.previousPosition = null;
  42734. if (!noPreventDefault) {
  42735. evt.preventDefault();
  42736. }
  42737. }
  42738. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  42739. if (!_this.previousPosition || engine.isPointerLock) {
  42740. return;
  42741. }
  42742. var offsetX = evt.clientX - _this.previousPosition.x;
  42743. var offsetY = evt.clientY - _this.previousPosition.y;
  42744. if (_this.camera.getScene().useRightHandedSystem) {
  42745. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42746. }
  42747. else {
  42748. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42749. }
  42750. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42751. _this.previousPosition = {
  42752. x: evt.clientX,
  42753. y: evt.clientY
  42754. };
  42755. if (!noPreventDefault) {
  42756. evt.preventDefault();
  42757. }
  42758. }
  42759. };
  42760. }
  42761. this._onMouseMove = function (evt) {
  42762. if (!engine.isPointerLock) {
  42763. return;
  42764. }
  42765. if (engine.isInVRExclusivePointerMode) {
  42766. return;
  42767. }
  42768. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42769. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42770. if (_this.camera.getScene().useRightHandedSystem) {
  42771. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42772. }
  42773. else {
  42774. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42775. }
  42776. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42777. _this.previousPosition = null;
  42778. if (!noPreventDefault) {
  42779. evt.preventDefault();
  42780. }
  42781. };
  42782. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  42783. element.addEventListener("mousemove", this._onMouseMove, false);
  42784. };
  42785. FreeCameraMouseInput.prototype.detachControl = function (element) {
  42786. if (this._observer && element) {
  42787. this.camera.getScene().onPointerObservable.remove(this._observer);
  42788. if (this._onMouseMove) {
  42789. element.removeEventListener("mousemove", this._onMouseMove);
  42790. }
  42791. this._observer = null;
  42792. this._onMouseMove = null;
  42793. this.previousPosition = null;
  42794. }
  42795. };
  42796. FreeCameraMouseInput.prototype.getClassName = function () {
  42797. return "FreeCameraMouseInput";
  42798. };
  42799. FreeCameraMouseInput.prototype.getSimpleName = function () {
  42800. return "mouse";
  42801. };
  42802. __decorate([
  42803. BABYLON.serialize()
  42804. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  42805. __decorate([
  42806. BABYLON.serialize()
  42807. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  42808. return FreeCameraMouseInput;
  42809. }());
  42810. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  42811. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  42812. })(BABYLON || (BABYLON = {}));
  42813. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  42814. var BABYLON;
  42815. (function (BABYLON) {
  42816. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  42817. function FreeCameraKeyboardMoveInput() {
  42818. this._keys = new Array();
  42819. this.keysUp = [38];
  42820. this.keysDown = [40];
  42821. this.keysLeft = [37];
  42822. this.keysRight = [39];
  42823. }
  42824. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  42825. var _this = this;
  42826. if (this._onCanvasBlurObserver) {
  42827. return;
  42828. }
  42829. this._scene = this.camera.getScene();
  42830. this._engine = this._scene.getEngine();
  42831. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  42832. _this._keys = [];
  42833. });
  42834. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  42835. var evt = info.event;
  42836. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  42837. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42838. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42839. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42840. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42841. var index = _this._keys.indexOf(evt.keyCode);
  42842. if (index === -1) {
  42843. _this._keys.push(evt.keyCode);
  42844. }
  42845. if (!noPreventDefault) {
  42846. evt.preventDefault();
  42847. }
  42848. }
  42849. }
  42850. else {
  42851. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42852. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42853. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42854. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42855. var index = _this._keys.indexOf(evt.keyCode);
  42856. if (index >= 0) {
  42857. _this._keys.splice(index, 1);
  42858. }
  42859. if (!noPreventDefault) {
  42860. evt.preventDefault();
  42861. }
  42862. }
  42863. }
  42864. });
  42865. };
  42866. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  42867. if (this._scene) {
  42868. if (this._onKeyboardObserver) {
  42869. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  42870. }
  42871. if (this._onCanvasBlurObserver) {
  42872. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  42873. }
  42874. this._onKeyboardObserver = null;
  42875. this._onCanvasBlurObserver = null;
  42876. }
  42877. this._keys = [];
  42878. };
  42879. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  42880. if (this._onKeyboardObserver) {
  42881. var camera = this.camera;
  42882. // Keyboard
  42883. for (var index = 0; index < this._keys.length; index++) {
  42884. var keyCode = this._keys[index];
  42885. var speed = camera._computeLocalCameraSpeed();
  42886. if (this.keysLeft.indexOf(keyCode) !== -1) {
  42887. camera._localDirection.copyFromFloats(-speed, 0, 0);
  42888. }
  42889. else if (this.keysUp.indexOf(keyCode) !== -1) {
  42890. camera._localDirection.copyFromFloats(0, 0, speed);
  42891. }
  42892. else if (this.keysRight.indexOf(keyCode) !== -1) {
  42893. camera._localDirection.copyFromFloats(speed, 0, 0);
  42894. }
  42895. else if (this.keysDown.indexOf(keyCode) !== -1) {
  42896. camera._localDirection.copyFromFloats(0, 0, -speed);
  42897. }
  42898. if (camera.getScene().useRightHandedSystem) {
  42899. camera._localDirection.z *= -1;
  42900. }
  42901. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  42902. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  42903. camera.cameraDirection.addInPlace(camera._transformedDirection);
  42904. }
  42905. }
  42906. };
  42907. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  42908. return "FreeCameraKeyboardMoveInput";
  42909. };
  42910. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  42911. this._keys = [];
  42912. };
  42913. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  42914. return "keyboard";
  42915. };
  42916. __decorate([
  42917. BABYLON.serialize()
  42918. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  42919. __decorate([
  42920. BABYLON.serialize()
  42921. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  42922. __decorate([
  42923. BABYLON.serialize()
  42924. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  42925. __decorate([
  42926. BABYLON.serialize()
  42927. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  42928. return FreeCameraKeyboardMoveInput;
  42929. }());
  42930. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  42931. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  42932. })(BABYLON || (BABYLON = {}));
  42933. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  42934. var BABYLON;
  42935. (function (BABYLON) {
  42936. var FreeCameraInputsManager = /** @class */ (function (_super) {
  42937. __extends(FreeCameraInputsManager, _super);
  42938. function FreeCameraInputsManager(camera) {
  42939. return _super.call(this, camera) || this;
  42940. }
  42941. FreeCameraInputsManager.prototype.addKeyboard = function () {
  42942. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  42943. return this;
  42944. };
  42945. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  42946. if (touchEnabled === void 0) { touchEnabled = true; }
  42947. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  42948. return this;
  42949. };
  42950. FreeCameraInputsManager.prototype.addGamepad = function () {
  42951. this.add(new BABYLON.FreeCameraGamepadInput());
  42952. return this;
  42953. };
  42954. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  42955. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  42956. return this;
  42957. };
  42958. FreeCameraInputsManager.prototype.addTouch = function () {
  42959. this.add(new BABYLON.FreeCameraTouchInput());
  42960. return this;
  42961. };
  42962. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  42963. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  42964. return this;
  42965. };
  42966. return FreeCameraInputsManager;
  42967. }(BABYLON.CameraInputsManager));
  42968. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  42969. })(BABYLON || (BABYLON = {}));
  42970. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  42971. var BABYLON;
  42972. (function (BABYLON) {
  42973. var FreeCamera = /** @class */ (function (_super) {
  42974. __extends(FreeCamera, _super);
  42975. function FreeCamera(name, position, scene) {
  42976. var _this = _super.call(this, name, position, scene) || this;
  42977. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  42978. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  42979. _this.checkCollisions = false;
  42980. _this.applyGravity = false;
  42981. _this._needMoveForGravity = false;
  42982. _this._oldPosition = BABYLON.Vector3.Zero();
  42983. _this._diffPosition = BABYLON.Vector3.Zero();
  42984. _this._newPosition = BABYLON.Vector3.Zero();
  42985. // Collisions
  42986. _this._collisionMask = -1;
  42987. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  42988. if (collidedMesh === void 0) { collidedMesh = null; }
  42989. //TODO move this to the collision coordinator!
  42990. if (_this.getScene().workerCollisions)
  42991. newPosition.multiplyInPlace(_this._collider._radius);
  42992. var updatePosition = function (newPos) {
  42993. _this._newPosition.copyFrom(newPos);
  42994. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  42995. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  42996. _this.position.addInPlace(_this._diffPosition);
  42997. if (_this.onCollide && collidedMesh) {
  42998. _this.onCollide(collidedMesh);
  42999. }
  43000. }
  43001. };
  43002. updatePosition(newPosition);
  43003. };
  43004. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43005. _this.inputs.addKeyboard().addMouse();
  43006. return _this;
  43007. }
  43008. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43009. //-- begin properties for backward compatibility for inputs
  43010. /**
  43011. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43012. * Higher values reduce sensitivity.
  43013. */
  43014. get: function () {
  43015. var mouse = this.inputs.attached["mouse"];
  43016. if (mouse)
  43017. return mouse.angularSensibility;
  43018. return 0;
  43019. },
  43020. /**
  43021. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43022. * Higher values reduce sensitivity.
  43023. */
  43024. set: function (value) {
  43025. var mouse = this.inputs.attached["mouse"];
  43026. if (mouse)
  43027. mouse.angularSensibility = value;
  43028. },
  43029. enumerable: true,
  43030. configurable: true
  43031. });
  43032. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43033. get: function () {
  43034. var keyboard = this.inputs.attached["keyboard"];
  43035. if (keyboard)
  43036. return keyboard.keysUp;
  43037. return [];
  43038. },
  43039. set: function (value) {
  43040. var keyboard = this.inputs.attached["keyboard"];
  43041. if (keyboard)
  43042. keyboard.keysUp = value;
  43043. },
  43044. enumerable: true,
  43045. configurable: true
  43046. });
  43047. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43048. get: function () {
  43049. var keyboard = this.inputs.attached["keyboard"];
  43050. if (keyboard)
  43051. return keyboard.keysDown;
  43052. return [];
  43053. },
  43054. set: function (value) {
  43055. var keyboard = this.inputs.attached["keyboard"];
  43056. if (keyboard)
  43057. keyboard.keysDown = value;
  43058. },
  43059. enumerable: true,
  43060. configurable: true
  43061. });
  43062. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43063. get: function () {
  43064. var keyboard = this.inputs.attached["keyboard"];
  43065. if (keyboard)
  43066. return keyboard.keysLeft;
  43067. return [];
  43068. },
  43069. set: function (value) {
  43070. var keyboard = this.inputs.attached["keyboard"];
  43071. if (keyboard)
  43072. keyboard.keysLeft = value;
  43073. },
  43074. enumerable: true,
  43075. configurable: true
  43076. });
  43077. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43078. get: function () {
  43079. var keyboard = this.inputs.attached["keyboard"];
  43080. if (keyboard)
  43081. return keyboard.keysRight;
  43082. return [];
  43083. },
  43084. set: function (value) {
  43085. var keyboard = this.inputs.attached["keyboard"];
  43086. if (keyboard)
  43087. keyboard.keysRight = value;
  43088. },
  43089. enumerable: true,
  43090. configurable: true
  43091. });
  43092. // Controls
  43093. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43094. this.inputs.attachElement(element, noPreventDefault);
  43095. };
  43096. FreeCamera.prototype.detachControl = function (element) {
  43097. this.inputs.detachElement(element);
  43098. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43099. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43100. };
  43101. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43102. get: function () {
  43103. return this._collisionMask;
  43104. },
  43105. set: function (mask) {
  43106. this._collisionMask = !isNaN(mask) ? mask : -1;
  43107. },
  43108. enumerable: true,
  43109. configurable: true
  43110. });
  43111. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43112. var globalPosition;
  43113. if (this.parent) {
  43114. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43115. }
  43116. else {
  43117. globalPosition = this.position;
  43118. }
  43119. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43120. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43121. if (!this._collider) {
  43122. this._collider = new BABYLON.Collider();
  43123. }
  43124. this._collider._radius = this.ellipsoid;
  43125. this._collider.collisionMask = this._collisionMask;
  43126. //no need for clone, as long as gravity is not on.
  43127. var actualDisplacement = displacement;
  43128. //add gravity to the direction to prevent the dual-collision checking
  43129. if (this.applyGravity) {
  43130. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43131. actualDisplacement = displacement.add(this.getScene().gravity);
  43132. }
  43133. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43134. };
  43135. FreeCamera.prototype._checkInputs = function () {
  43136. if (!this._localDirection) {
  43137. this._localDirection = BABYLON.Vector3.Zero();
  43138. this._transformedDirection = BABYLON.Vector3.Zero();
  43139. }
  43140. this.inputs.checkInputs();
  43141. _super.prototype._checkInputs.call(this);
  43142. };
  43143. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43144. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43145. };
  43146. FreeCamera.prototype._updatePosition = function () {
  43147. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43148. this._collideWithWorld(this.cameraDirection);
  43149. }
  43150. else {
  43151. _super.prototype._updatePosition.call(this);
  43152. }
  43153. };
  43154. FreeCamera.prototype.dispose = function () {
  43155. this.inputs.clear();
  43156. _super.prototype.dispose.call(this);
  43157. };
  43158. FreeCamera.prototype.getClassName = function () {
  43159. return "FreeCamera";
  43160. };
  43161. __decorate([
  43162. BABYLON.serializeAsVector3()
  43163. ], FreeCamera.prototype, "ellipsoid", void 0);
  43164. __decorate([
  43165. BABYLON.serializeAsVector3()
  43166. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43167. __decorate([
  43168. BABYLON.serialize()
  43169. ], FreeCamera.prototype, "checkCollisions", void 0);
  43170. __decorate([
  43171. BABYLON.serialize()
  43172. ], FreeCamera.prototype, "applyGravity", void 0);
  43173. return FreeCamera;
  43174. }(BABYLON.TargetCamera));
  43175. BABYLON.FreeCamera = FreeCamera;
  43176. })(BABYLON || (BABYLON = {}));
  43177. //# sourceMappingURL=babylon.freeCamera.js.map
  43178. var BABYLON;
  43179. (function (BABYLON) {
  43180. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43181. function ArcRotateCameraKeyboardMoveInput() {
  43182. this._keys = new Array();
  43183. this.keysUp = [38];
  43184. this.keysDown = [40];
  43185. this.keysLeft = [37];
  43186. this.keysRight = [39];
  43187. this.keysReset = [220];
  43188. this.panningSensibility = 50.0;
  43189. this.zoomingSensibility = 25.0;
  43190. this.useAltToZoom = true;
  43191. }
  43192. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43193. var _this = this;
  43194. if (this._onCanvasBlurObserver) {
  43195. return;
  43196. }
  43197. this._scene = this.camera.getScene();
  43198. this._engine = this._scene.getEngine();
  43199. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43200. _this._keys = [];
  43201. });
  43202. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43203. var evt = info.event;
  43204. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43205. _this._ctrlPressed = evt.ctrlKey;
  43206. _this._altPressed = evt.altKey;
  43207. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43208. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43209. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43210. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43211. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43212. var index = _this._keys.indexOf(evt.keyCode);
  43213. if (index === -1) {
  43214. _this._keys.push(evt.keyCode);
  43215. }
  43216. if (evt.preventDefault) {
  43217. if (!noPreventDefault) {
  43218. evt.preventDefault();
  43219. }
  43220. }
  43221. }
  43222. }
  43223. else {
  43224. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43225. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43226. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43227. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43228. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43229. var index = _this._keys.indexOf(evt.keyCode);
  43230. if (index >= 0) {
  43231. _this._keys.splice(index, 1);
  43232. }
  43233. if (evt.preventDefault) {
  43234. if (!noPreventDefault) {
  43235. evt.preventDefault();
  43236. }
  43237. }
  43238. }
  43239. }
  43240. });
  43241. };
  43242. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43243. if (this._scene) {
  43244. if (this._onKeyboardObserver) {
  43245. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43246. }
  43247. if (this._onCanvasBlurObserver) {
  43248. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43249. }
  43250. this._onKeyboardObserver = null;
  43251. this._onCanvasBlurObserver = null;
  43252. }
  43253. this._keys = [];
  43254. };
  43255. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43256. if (this._onKeyboardObserver) {
  43257. var camera = this.camera;
  43258. for (var index = 0; index < this._keys.length; index++) {
  43259. var keyCode = this._keys[index];
  43260. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43261. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43262. camera.inertialPanningX -= 1 / this.panningSensibility;
  43263. }
  43264. else {
  43265. camera.inertialAlphaOffset -= 0.01;
  43266. }
  43267. }
  43268. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43269. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43270. camera.inertialPanningY += 1 / this.panningSensibility;
  43271. }
  43272. else if (this._altPressed && this.useAltToZoom) {
  43273. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43274. }
  43275. else {
  43276. camera.inertialBetaOffset -= 0.01;
  43277. }
  43278. }
  43279. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43280. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43281. camera.inertialPanningX += 1 / this.panningSensibility;
  43282. }
  43283. else {
  43284. camera.inertialAlphaOffset += 0.01;
  43285. }
  43286. }
  43287. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43288. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43289. camera.inertialPanningY -= 1 / this.panningSensibility;
  43290. }
  43291. else if (this._altPressed && this.useAltToZoom) {
  43292. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43293. }
  43294. else {
  43295. camera.inertialBetaOffset += 0.01;
  43296. }
  43297. }
  43298. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43299. camera.restoreState();
  43300. }
  43301. }
  43302. }
  43303. };
  43304. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43305. return "ArcRotateCameraKeyboardMoveInput";
  43306. };
  43307. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43308. return "keyboard";
  43309. };
  43310. __decorate([
  43311. BABYLON.serialize()
  43312. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43313. __decorate([
  43314. BABYLON.serialize()
  43315. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43316. __decorate([
  43317. BABYLON.serialize()
  43318. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43319. __decorate([
  43320. BABYLON.serialize()
  43321. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43322. __decorate([
  43323. BABYLON.serialize()
  43324. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43325. __decorate([
  43326. BABYLON.serialize()
  43327. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43328. __decorate([
  43329. BABYLON.serialize()
  43330. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43331. __decorate([
  43332. BABYLON.serialize()
  43333. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43334. return ArcRotateCameraKeyboardMoveInput;
  43335. }());
  43336. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43337. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43338. })(BABYLON || (BABYLON = {}));
  43339. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43340. var BABYLON;
  43341. (function (BABYLON) {
  43342. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43343. function ArcRotateCameraMouseWheelInput() {
  43344. this.wheelPrecision = 3.0;
  43345. /**
  43346. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43347. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43348. */
  43349. this.wheelDeltaPercentage = 0;
  43350. }
  43351. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43352. var _this = this;
  43353. this._wheel = function (p, s) {
  43354. //sanity check - this should be a PointerWheel event.
  43355. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43356. return;
  43357. var event = p.event;
  43358. var delta = 0;
  43359. if (event.wheelDelta) {
  43360. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43361. }
  43362. else if (event.detail) {
  43363. delta = -event.detail / _this.wheelPrecision;
  43364. }
  43365. if (delta)
  43366. _this.camera.inertialRadiusOffset += delta;
  43367. if (event.preventDefault) {
  43368. if (!noPreventDefault) {
  43369. event.preventDefault();
  43370. }
  43371. }
  43372. };
  43373. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43374. };
  43375. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43376. if (this._observer && element) {
  43377. this.camera.getScene().onPointerObservable.remove(this._observer);
  43378. this._observer = null;
  43379. this._wheel = null;
  43380. }
  43381. };
  43382. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43383. return "ArcRotateCameraMouseWheelInput";
  43384. };
  43385. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43386. return "mousewheel";
  43387. };
  43388. __decorate([
  43389. BABYLON.serialize()
  43390. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43391. __decorate([
  43392. BABYLON.serialize()
  43393. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43394. return ArcRotateCameraMouseWheelInput;
  43395. }());
  43396. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43397. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43398. })(BABYLON || (BABYLON = {}));
  43399. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43400. var BABYLON;
  43401. (function (BABYLON) {
  43402. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43403. function ArcRotateCameraPointersInput() {
  43404. this.buttons = [0, 1, 2];
  43405. this.angularSensibilityX = 1000.0;
  43406. this.angularSensibilityY = 1000.0;
  43407. this.pinchPrecision = 12.0;
  43408. /**
  43409. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43410. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43411. */
  43412. this.pinchDeltaPercentage = 0;
  43413. this.panningSensibility = 1000.0;
  43414. this.multiTouchPanning = true;
  43415. this.multiTouchPanAndZoom = true;
  43416. this._isPanClick = false;
  43417. this.pinchInwards = true;
  43418. }
  43419. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43420. var _this = this;
  43421. var engine = this.camera.getEngine();
  43422. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43423. var pointA = null;
  43424. var pointB = null;
  43425. var previousPinchSquaredDistance = 0;
  43426. var initialDistance = 0;
  43427. var twoFingerActivityCount = 0;
  43428. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43429. this._pointerInput = function (p, s) {
  43430. var evt = p.event;
  43431. var isTouch = p.event.pointerType === "touch";
  43432. if (engine.isInVRExclusivePointerMode) {
  43433. return;
  43434. }
  43435. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43436. return;
  43437. }
  43438. var srcElement = (evt.srcElement || evt.target);
  43439. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43440. try {
  43441. srcElement.setPointerCapture(evt.pointerId);
  43442. }
  43443. catch (e) {
  43444. //Nothing to do with the error. Execution will continue.
  43445. }
  43446. // Manage panning with pan button click
  43447. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43448. // manage pointers
  43449. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43450. if (pointA === null) {
  43451. pointA = cacheSoloPointer;
  43452. }
  43453. else if (pointB === null) {
  43454. pointB = cacheSoloPointer;
  43455. }
  43456. if (!noPreventDefault) {
  43457. evt.preventDefault();
  43458. element.focus();
  43459. }
  43460. }
  43461. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43462. _this.camera.restoreState();
  43463. }
  43464. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43465. try {
  43466. srcElement.releasePointerCapture(evt.pointerId);
  43467. }
  43468. catch (e) {
  43469. //Nothing to do with the error.
  43470. }
  43471. cacheSoloPointer = null;
  43472. previousPinchSquaredDistance = 0;
  43473. previousMultiTouchPanPosition.isPaning = false;
  43474. previousMultiTouchPanPosition.isPinching = false;
  43475. twoFingerActivityCount = 0;
  43476. initialDistance = 0;
  43477. if (!isTouch) {
  43478. pointB = null; // Mouse and pen are mono pointer
  43479. }
  43480. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43481. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43482. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43483. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43484. if (engine.badOS) {
  43485. pointA = pointB = null;
  43486. }
  43487. else {
  43488. //only remove the impacted pointer in case of multitouch allowing on most
  43489. //platforms switching from rotate to zoom and pan seamlessly.
  43490. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43491. pointA = pointB;
  43492. pointB = null;
  43493. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43494. }
  43495. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43496. pointB = null;
  43497. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43498. }
  43499. else {
  43500. pointA = pointB = null;
  43501. }
  43502. }
  43503. if (!noPreventDefault) {
  43504. evt.preventDefault();
  43505. }
  43506. }
  43507. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43508. if (!noPreventDefault) {
  43509. evt.preventDefault();
  43510. }
  43511. // One button down
  43512. if (pointA && pointB === null && cacheSoloPointer) {
  43513. if (_this.panningSensibility !== 0 &&
  43514. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43515. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43516. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  43517. }
  43518. else {
  43519. var offsetX = evt.clientX - cacheSoloPointer.x;
  43520. var offsetY = evt.clientY - cacheSoloPointer.y;
  43521. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43522. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43523. }
  43524. cacheSoloPointer.x = evt.clientX;
  43525. cacheSoloPointer.y = evt.clientY;
  43526. }
  43527. else if (pointA && pointB) {
  43528. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  43529. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  43530. ed.x = evt.clientX;
  43531. ed.y = evt.clientY;
  43532. var direction = _this.pinchInwards ? 1 : -1;
  43533. var distX = pointA.x - pointB.x;
  43534. var distY = pointA.y - pointB.y;
  43535. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  43536. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  43537. if (previousPinchSquaredDistance === 0) {
  43538. initialDistance = pinchDistance;
  43539. previousPinchSquaredDistance = pinchSquaredDistance;
  43540. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  43541. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  43542. return;
  43543. }
  43544. if (_this.multiTouchPanAndZoom) {
  43545. if (_this.pinchDeltaPercentage) {
  43546. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43547. }
  43548. else {
  43549. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43550. (_this.pinchPrecision *
  43551. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43552. direction);
  43553. }
  43554. if (_this.panningSensibility !== 0) {
  43555. var pointersCenterX = (pointA.x + pointB.x) / 2;
  43556. var pointersCenterY = (pointA.y + pointB.y) / 2;
  43557. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  43558. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  43559. previousMultiTouchPanPosition.x = pointersCenterX;
  43560. previousMultiTouchPanPosition.y = pointersCenterY;
  43561. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  43562. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  43563. }
  43564. }
  43565. else {
  43566. twoFingerActivityCount++;
  43567. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  43568. if (_this.pinchDeltaPercentage) {
  43569. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43570. }
  43571. else {
  43572. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43573. (_this.pinchPrecision *
  43574. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43575. direction);
  43576. }
  43577. previousMultiTouchPanPosition.isPaning = false;
  43578. previousMultiTouchPanPosition.isPinching = true;
  43579. }
  43580. else {
  43581. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  43582. if (!previousMultiTouchPanPosition.isPaning) {
  43583. previousMultiTouchPanPosition.isPaning = true;
  43584. previousMultiTouchPanPosition.isPinching = false;
  43585. previousMultiTouchPanPosition.x = ed.x;
  43586. previousMultiTouchPanPosition.y = ed.y;
  43587. return;
  43588. }
  43589. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  43590. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  43591. }
  43592. }
  43593. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  43594. previousMultiTouchPanPosition.x = ed.x;
  43595. previousMultiTouchPanPosition.y = ed.y;
  43596. }
  43597. }
  43598. previousPinchSquaredDistance = pinchSquaredDistance;
  43599. }
  43600. }
  43601. };
  43602. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  43603. this._onContextMenu = function (evt) {
  43604. evt.preventDefault();
  43605. };
  43606. if (!this.camera._useCtrlForPanning) {
  43607. element.addEventListener("contextmenu", this._onContextMenu, false);
  43608. }
  43609. this._onLostFocus = function () {
  43610. //this._keys = [];
  43611. pointA = pointB = null;
  43612. previousPinchSquaredDistance = 0;
  43613. previousMultiTouchPanPosition.isPaning = false;
  43614. previousMultiTouchPanPosition.isPinching = false;
  43615. twoFingerActivityCount = 0;
  43616. cacheSoloPointer = null;
  43617. initialDistance = 0;
  43618. };
  43619. this._onMouseMove = function (evt) {
  43620. if (!engine.isPointerLock) {
  43621. return;
  43622. }
  43623. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43624. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43625. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43626. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43627. if (!noPreventDefault) {
  43628. evt.preventDefault();
  43629. }
  43630. };
  43631. this._onGestureStart = function (e) {
  43632. if (window.MSGesture === undefined) {
  43633. return;
  43634. }
  43635. if (!_this._MSGestureHandler) {
  43636. _this._MSGestureHandler = new MSGesture();
  43637. _this._MSGestureHandler.target = element;
  43638. }
  43639. _this._MSGestureHandler.addPointer(e.pointerId);
  43640. };
  43641. this._onGesture = function (e) {
  43642. _this.camera.radius *= e.scale;
  43643. if (e.preventDefault) {
  43644. if (!noPreventDefault) {
  43645. e.stopPropagation();
  43646. e.preventDefault();
  43647. }
  43648. }
  43649. };
  43650. element.addEventListener("mousemove", this._onMouseMove, false);
  43651. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  43652. element.addEventListener("MSGestureChange", this._onGesture, false);
  43653. BABYLON.Tools.RegisterTopRootEvents([
  43654. { name: "blur", handler: this._onLostFocus }
  43655. ]);
  43656. };
  43657. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  43658. if (this._onLostFocus) {
  43659. BABYLON.Tools.UnregisterTopRootEvents([
  43660. { name: "blur", handler: this._onLostFocus }
  43661. ]);
  43662. }
  43663. if (element && this._observer) {
  43664. this.camera.getScene().onPointerObservable.remove(this._observer);
  43665. this._observer = null;
  43666. if (this._onContextMenu) {
  43667. element.removeEventListener("contextmenu", this._onContextMenu);
  43668. }
  43669. if (this._onMouseMove) {
  43670. element.removeEventListener("mousemove", this._onMouseMove);
  43671. }
  43672. if (this._onGestureStart) {
  43673. element.removeEventListener("MSPointerDown", this._onGestureStart);
  43674. }
  43675. if (this._onGesture) {
  43676. element.removeEventListener("MSGestureChange", this._onGesture);
  43677. }
  43678. this._isPanClick = false;
  43679. this.pinchInwards = true;
  43680. this._onMouseMove = null;
  43681. this._onGestureStart = null;
  43682. this._onGesture = null;
  43683. this._MSGestureHandler = null;
  43684. this._onLostFocus = null;
  43685. this._onContextMenu = null;
  43686. }
  43687. };
  43688. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  43689. return "ArcRotateCameraPointersInput";
  43690. };
  43691. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  43692. return "pointers";
  43693. };
  43694. __decorate([
  43695. BABYLON.serialize()
  43696. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  43697. __decorate([
  43698. BABYLON.serialize()
  43699. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  43700. __decorate([
  43701. BABYLON.serialize()
  43702. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  43703. __decorate([
  43704. BABYLON.serialize()
  43705. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  43706. __decorate([
  43707. BABYLON.serialize()
  43708. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  43709. __decorate([
  43710. BABYLON.serialize()
  43711. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  43712. __decorate([
  43713. BABYLON.serialize()
  43714. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  43715. __decorate([
  43716. BABYLON.serialize()
  43717. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  43718. return ArcRotateCameraPointersInput;
  43719. }());
  43720. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  43721. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  43722. })(BABYLON || (BABYLON = {}));
  43723. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  43724. var BABYLON;
  43725. (function (BABYLON) {
  43726. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  43727. __extends(ArcRotateCameraInputsManager, _super);
  43728. function ArcRotateCameraInputsManager(camera) {
  43729. return _super.call(this, camera) || this;
  43730. }
  43731. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  43732. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  43733. return this;
  43734. };
  43735. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  43736. this.add(new BABYLON.ArcRotateCameraPointersInput());
  43737. return this;
  43738. };
  43739. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  43740. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  43741. return this;
  43742. };
  43743. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  43744. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  43745. return this;
  43746. };
  43747. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  43748. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  43749. return this;
  43750. };
  43751. return ArcRotateCameraInputsManager;
  43752. }(BABYLON.CameraInputsManager));
  43753. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  43754. })(BABYLON || (BABYLON = {}));
  43755. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  43756. var BABYLON;
  43757. (function (BABYLON) {
  43758. var ArcRotateCamera = /** @class */ (function (_super) {
  43759. __extends(ArcRotateCamera, _super);
  43760. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  43761. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  43762. _this.inertialAlphaOffset = 0;
  43763. _this.inertialBetaOffset = 0;
  43764. _this.inertialRadiusOffset = 0;
  43765. _this.lowerAlphaLimit = null;
  43766. _this.upperAlphaLimit = null;
  43767. _this.lowerBetaLimit = 0.01;
  43768. _this.upperBetaLimit = Math.PI;
  43769. _this.lowerRadiusLimit = null;
  43770. _this.upperRadiusLimit = null;
  43771. _this.inertialPanningX = 0;
  43772. _this.inertialPanningY = 0;
  43773. _this.pinchToPanMaxDistance = 20;
  43774. _this.panningDistanceLimit = null;
  43775. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  43776. _this.panningInertia = 0.9;
  43777. //-- end properties for backward compatibility for inputs
  43778. _this.zoomOnFactor = 1;
  43779. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  43780. _this.allowUpsideDown = true;
  43781. _this._viewMatrix = new BABYLON.Matrix();
  43782. // Panning
  43783. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  43784. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  43785. _this.checkCollisions = false;
  43786. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43787. _this._previousPosition = BABYLON.Vector3.Zero();
  43788. _this._collisionVelocity = BABYLON.Vector3.Zero();
  43789. _this._newPosition = BABYLON.Vector3.Zero();
  43790. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43791. if (collidedMesh === void 0) { collidedMesh = null; }
  43792. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  43793. newPosition.multiplyInPlace(_this._collider._radius);
  43794. }
  43795. if (!collidedMesh) {
  43796. _this._previousPosition.copyFrom(_this.position);
  43797. }
  43798. else {
  43799. _this.setPosition(newPosition);
  43800. if (_this.onCollide) {
  43801. _this.onCollide(collidedMesh);
  43802. }
  43803. }
  43804. // Recompute because of constraints
  43805. var cosa = Math.cos(_this.alpha);
  43806. var sina = Math.sin(_this.alpha);
  43807. var cosb = Math.cos(_this.beta);
  43808. var sinb = Math.sin(_this.beta);
  43809. if (sinb === 0) {
  43810. sinb = 0.0001;
  43811. }
  43812. var target = _this._getTargetPosition();
  43813. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  43814. _this.position.copyFrom(_this._newPosition);
  43815. var up = _this.upVector;
  43816. if (_this.allowUpsideDown && _this.beta < 0) {
  43817. up = up.clone();
  43818. up = up.negate();
  43819. }
  43820. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  43821. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  43822. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  43823. _this._collisionTriggered = false;
  43824. };
  43825. _this._target = BABYLON.Vector3.Zero();
  43826. if (target) {
  43827. _this.setTarget(target);
  43828. }
  43829. _this.alpha = alpha;
  43830. _this.beta = beta;
  43831. _this.radius = radius;
  43832. _this.getViewMatrix();
  43833. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  43834. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  43835. return _this;
  43836. }
  43837. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  43838. get: function () {
  43839. return this._target;
  43840. },
  43841. set: function (value) {
  43842. this.setTarget(value);
  43843. },
  43844. enumerable: true,
  43845. configurable: true
  43846. });
  43847. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  43848. //-- begin properties for backward compatibility for inputs
  43849. get: function () {
  43850. var pointers = this.inputs.attached["pointers"];
  43851. if (pointers)
  43852. return pointers.angularSensibilityX;
  43853. return 0;
  43854. },
  43855. set: function (value) {
  43856. var pointers = this.inputs.attached["pointers"];
  43857. if (pointers) {
  43858. pointers.angularSensibilityX = value;
  43859. }
  43860. },
  43861. enumerable: true,
  43862. configurable: true
  43863. });
  43864. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  43865. get: function () {
  43866. var pointers = this.inputs.attached["pointers"];
  43867. if (pointers)
  43868. return pointers.angularSensibilityY;
  43869. return 0;
  43870. },
  43871. set: function (value) {
  43872. var pointers = this.inputs.attached["pointers"];
  43873. if (pointers) {
  43874. pointers.angularSensibilityY = value;
  43875. }
  43876. },
  43877. enumerable: true,
  43878. configurable: true
  43879. });
  43880. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  43881. get: function () {
  43882. var pointers = this.inputs.attached["pointers"];
  43883. if (pointers)
  43884. return pointers.pinchPrecision;
  43885. return 0;
  43886. },
  43887. set: function (value) {
  43888. var pointers = this.inputs.attached["pointers"];
  43889. if (pointers) {
  43890. pointers.pinchPrecision = value;
  43891. }
  43892. },
  43893. enumerable: true,
  43894. configurable: true
  43895. });
  43896. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  43897. get: function () {
  43898. var pointers = this.inputs.attached["pointers"];
  43899. if (pointers)
  43900. return pointers.pinchDeltaPercentage;
  43901. return 0;
  43902. },
  43903. set: function (value) {
  43904. var pointers = this.inputs.attached["pointers"];
  43905. if (pointers) {
  43906. pointers.pinchDeltaPercentage = value;
  43907. }
  43908. },
  43909. enumerable: true,
  43910. configurable: true
  43911. });
  43912. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  43913. get: function () {
  43914. var pointers = this.inputs.attached["pointers"];
  43915. if (pointers)
  43916. return pointers.panningSensibility;
  43917. return 0;
  43918. },
  43919. set: function (value) {
  43920. var pointers = this.inputs.attached["pointers"];
  43921. if (pointers) {
  43922. pointers.panningSensibility = value;
  43923. }
  43924. },
  43925. enumerable: true,
  43926. configurable: true
  43927. });
  43928. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  43929. get: function () {
  43930. var keyboard = this.inputs.attached["keyboard"];
  43931. if (keyboard)
  43932. return keyboard.keysUp;
  43933. return [];
  43934. },
  43935. set: function (value) {
  43936. var keyboard = this.inputs.attached["keyboard"];
  43937. if (keyboard)
  43938. keyboard.keysUp = value;
  43939. },
  43940. enumerable: true,
  43941. configurable: true
  43942. });
  43943. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  43944. get: function () {
  43945. var keyboard = this.inputs.attached["keyboard"];
  43946. if (keyboard)
  43947. return keyboard.keysDown;
  43948. return [];
  43949. },
  43950. set: function (value) {
  43951. var keyboard = this.inputs.attached["keyboard"];
  43952. if (keyboard)
  43953. keyboard.keysDown = value;
  43954. },
  43955. enumerable: true,
  43956. configurable: true
  43957. });
  43958. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  43959. get: function () {
  43960. var keyboard = this.inputs.attached["keyboard"];
  43961. if (keyboard)
  43962. return keyboard.keysLeft;
  43963. return [];
  43964. },
  43965. set: function (value) {
  43966. var keyboard = this.inputs.attached["keyboard"];
  43967. if (keyboard)
  43968. keyboard.keysLeft = value;
  43969. },
  43970. enumerable: true,
  43971. configurable: true
  43972. });
  43973. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  43974. get: function () {
  43975. var keyboard = this.inputs.attached["keyboard"];
  43976. if (keyboard)
  43977. return keyboard.keysRight;
  43978. return [];
  43979. },
  43980. set: function (value) {
  43981. var keyboard = this.inputs.attached["keyboard"];
  43982. if (keyboard)
  43983. keyboard.keysRight = value;
  43984. },
  43985. enumerable: true,
  43986. configurable: true
  43987. });
  43988. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  43989. get: function () {
  43990. var mousewheel = this.inputs.attached["mousewheel"];
  43991. if (mousewheel)
  43992. return mousewheel.wheelPrecision;
  43993. return 0;
  43994. },
  43995. set: function (value) {
  43996. var mousewheel = this.inputs.attached["mousewheel"];
  43997. if (mousewheel)
  43998. mousewheel.wheelPrecision = value;
  43999. },
  44000. enumerable: true,
  44001. configurable: true
  44002. });
  44003. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44004. get: function () {
  44005. var mousewheel = this.inputs.attached["mousewheel"];
  44006. if (mousewheel)
  44007. return mousewheel.wheelDeltaPercentage;
  44008. return 0;
  44009. },
  44010. set: function (value) {
  44011. var mousewheel = this.inputs.attached["mousewheel"];
  44012. if (mousewheel)
  44013. mousewheel.wheelDeltaPercentage = value;
  44014. },
  44015. enumerable: true,
  44016. configurable: true
  44017. });
  44018. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44019. get: function () {
  44020. return this._bouncingBehavior;
  44021. },
  44022. enumerable: true,
  44023. configurable: true
  44024. });
  44025. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44026. get: function () {
  44027. return this._bouncingBehavior != null;
  44028. },
  44029. set: function (value) {
  44030. if (value === this.useBouncingBehavior) {
  44031. return;
  44032. }
  44033. if (value) {
  44034. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44035. this.addBehavior(this._bouncingBehavior);
  44036. }
  44037. else if (this._bouncingBehavior) {
  44038. this.removeBehavior(this._bouncingBehavior);
  44039. this._bouncingBehavior = null;
  44040. }
  44041. },
  44042. enumerable: true,
  44043. configurable: true
  44044. });
  44045. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44046. get: function () {
  44047. return this._framingBehavior;
  44048. },
  44049. enumerable: true,
  44050. configurable: true
  44051. });
  44052. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44053. get: function () {
  44054. return this._framingBehavior != null;
  44055. },
  44056. set: function (value) {
  44057. if (value === this.useFramingBehavior) {
  44058. return;
  44059. }
  44060. if (value) {
  44061. this._framingBehavior = new BABYLON.FramingBehavior();
  44062. this.addBehavior(this._framingBehavior);
  44063. }
  44064. else if (this._framingBehavior) {
  44065. this.removeBehavior(this._framingBehavior);
  44066. this._framingBehavior = null;
  44067. }
  44068. },
  44069. enumerable: true,
  44070. configurable: true
  44071. });
  44072. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44073. get: function () {
  44074. return this._autoRotationBehavior;
  44075. },
  44076. enumerable: true,
  44077. configurable: true
  44078. });
  44079. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44080. get: function () {
  44081. return this._autoRotationBehavior != null;
  44082. },
  44083. set: function (value) {
  44084. if (value === this.useAutoRotationBehavior) {
  44085. return;
  44086. }
  44087. if (value) {
  44088. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44089. this.addBehavior(this._autoRotationBehavior);
  44090. }
  44091. else if (this._autoRotationBehavior) {
  44092. this.removeBehavior(this._autoRotationBehavior);
  44093. this._autoRotationBehavior = null;
  44094. }
  44095. },
  44096. enumerable: true,
  44097. configurable: true
  44098. });
  44099. // Cache
  44100. ArcRotateCamera.prototype._initCache = function () {
  44101. _super.prototype._initCache.call(this);
  44102. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44103. this._cache.alpha = undefined;
  44104. this._cache.beta = undefined;
  44105. this._cache.radius = undefined;
  44106. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44107. };
  44108. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44109. if (!ignoreParentClass) {
  44110. _super.prototype._updateCache.call(this);
  44111. }
  44112. this._cache._target.copyFrom(this._getTargetPosition());
  44113. this._cache.alpha = this.alpha;
  44114. this._cache.beta = this.beta;
  44115. this._cache.radius = this.radius;
  44116. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44117. };
  44118. ArcRotateCamera.prototype._getTargetPosition = function () {
  44119. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44120. var pos = this._targetHost.getAbsolutePosition();
  44121. if (this._targetBoundingCenter) {
  44122. pos.addToRef(this._targetBoundingCenter, this._target);
  44123. }
  44124. else {
  44125. this._target.copyFrom(pos);
  44126. }
  44127. }
  44128. var lockedTargetPosition = this._getLockedTargetPosition();
  44129. if (lockedTargetPosition) {
  44130. return lockedTargetPosition;
  44131. }
  44132. return this._target;
  44133. };
  44134. ArcRotateCamera.prototype.storeState = function () {
  44135. this._storedAlpha = this.alpha;
  44136. this._storedBeta = this.beta;
  44137. this._storedRadius = this.radius;
  44138. this._storedTarget = this._getTargetPosition().clone();
  44139. return _super.prototype.storeState.call(this);
  44140. };
  44141. /**
  44142. * Restored camera state. You must call storeState() first
  44143. */
  44144. ArcRotateCamera.prototype._restoreStateValues = function () {
  44145. if (!_super.prototype._restoreStateValues.call(this)) {
  44146. return false;
  44147. }
  44148. this.alpha = this._storedAlpha;
  44149. this.beta = this._storedBeta;
  44150. this.radius = this._storedRadius;
  44151. this.setTarget(this._storedTarget.clone());
  44152. this.inertialAlphaOffset = 0;
  44153. this.inertialBetaOffset = 0;
  44154. this.inertialRadiusOffset = 0;
  44155. this.inertialPanningX = 0;
  44156. this.inertialPanningY = 0;
  44157. return true;
  44158. };
  44159. // Synchronized
  44160. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44161. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44162. return false;
  44163. return this._cache._target.equals(this._getTargetPosition())
  44164. && this._cache.alpha === this.alpha
  44165. && this._cache.beta === this.beta
  44166. && this._cache.radius === this.radius
  44167. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44168. };
  44169. // Methods
  44170. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44171. var _this = this;
  44172. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44173. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44174. this._useCtrlForPanning = useCtrlForPanning;
  44175. this._panningMouseButton = panningMouseButton;
  44176. this.inputs.attachElement(element, noPreventDefault);
  44177. this._reset = function () {
  44178. _this.inertialAlphaOffset = 0;
  44179. _this.inertialBetaOffset = 0;
  44180. _this.inertialRadiusOffset = 0;
  44181. _this.inertialPanningX = 0;
  44182. _this.inertialPanningY = 0;
  44183. };
  44184. };
  44185. ArcRotateCamera.prototype.detachControl = function (element) {
  44186. this.inputs.detachElement(element);
  44187. if (this._reset) {
  44188. this._reset();
  44189. }
  44190. };
  44191. ArcRotateCamera.prototype._checkInputs = function () {
  44192. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44193. if (this._collisionTriggered) {
  44194. return;
  44195. }
  44196. this.inputs.checkInputs();
  44197. // Inertia
  44198. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44199. if (this.getScene().useRightHandedSystem) {
  44200. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44201. }
  44202. else {
  44203. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44204. }
  44205. this.beta += this.inertialBetaOffset;
  44206. this.radius -= this.inertialRadiusOffset;
  44207. this.inertialAlphaOffset *= this.inertia;
  44208. this.inertialBetaOffset *= this.inertia;
  44209. this.inertialRadiusOffset *= this.inertia;
  44210. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44211. this.inertialAlphaOffset = 0;
  44212. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44213. this.inertialBetaOffset = 0;
  44214. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44215. this.inertialRadiusOffset = 0;
  44216. }
  44217. // Panning inertia
  44218. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44219. if (!this._localDirection) {
  44220. this._localDirection = BABYLON.Vector3.Zero();
  44221. this._transformedDirection = BABYLON.Vector3.Zero();
  44222. }
  44223. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44224. this._localDirection.multiplyInPlace(this.panningAxis);
  44225. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44226. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44227. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44228. if (!this.panningAxis.y) {
  44229. this._transformedDirection.y = 0;
  44230. }
  44231. if (!this._targetHost) {
  44232. if (this.panningDistanceLimit) {
  44233. this._transformedDirection.addInPlace(this._target);
  44234. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44235. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44236. this._target.copyFrom(this._transformedDirection);
  44237. }
  44238. }
  44239. else {
  44240. this._target.addInPlace(this._transformedDirection);
  44241. }
  44242. }
  44243. this.inertialPanningX *= this.panningInertia;
  44244. this.inertialPanningY *= this.panningInertia;
  44245. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44246. this.inertialPanningX = 0;
  44247. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44248. this.inertialPanningY = 0;
  44249. }
  44250. // Limits
  44251. this._checkLimits();
  44252. _super.prototype._checkInputs.call(this);
  44253. };
  44254. ArcRotateCamera.prototype._checkLimits = function () {
  44255. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44256. if (this.allowUpsideDown && this.beta > Math.PI) {
  44257. this.beta = this.beta - (2 * Math.PI);
  44258. }
  44259. }
  44260. else {
  44261. if (this.beta < this.lowerBetaLimit) {
  44262. this.beta = this.lowerBetaLimit;
  44263. }
  44264. }
  44265. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44266. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44267. this.beta = this.beta + (2 * Math.PI);
  44268. }
  44269. }
  44270. else {
  44271. if (this.beta > this.upperBetaLimit) {
  44272. this.beta = this.upperBetaLimit;
  44273. }
  44274. }
  44275. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44276. this.alpha = this.lowerAlphaLimit;
  44277. }
  44278. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44279. this.alpha = this.upperAlphaLimit;
  44280. }
  44281. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44282. this.radius = this.lowerRadiusLimit;
  44283. }
  44284. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44285. this.radius = this.upperRadiusLimit;
  44286. }
  44287. };
  44288. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44289. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44290. this.radius = radiusv3.length();
  44291. if (this.radius === 0) {
  44292. this.radius = 0.0001; // Just to avoid division by zero
  44293. }
  44294. // Alpha
  44295. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44296. if (radiusv3.z < 0) {
  44297. this.alpha = 2 * Math.PI - this.alpha;
  44298. }
  44299. // Beta
  44300. this.beta = Math.acos(radiusv3.y / this.radius);
  44301. this._checkLimits();
  44302. };
  44303. ArcRotateCamera.prototype.setPosition = function (position) {
  44304. if (this.position.equals(position)) {
  44305. return;
  44306. }
  44307. this.position.copyFrom(position);
  44308. this.rebuildAnglesAndRadius();
  44309. };
  44310. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44311. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44312. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44313. if (target.getBoundingInfo) {
  44314. if (toBoundingCenter) {
  44315. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44316. }
  44317. else {
  44318. this._targetBoundingCenter = null;
  44319. }
  44320. this._targetHost = target;
  44321. this._target = this._getTargetPosition();
  44322. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44323. }
  44324. else {
  44325. var newTarget = target;
  44326. var currentTarget = this._getTargetPosition();
  44327. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44328. return;
  44329. }
  44330. this._targetHost = null;
  44331. this._target = newTarget;
  44332. this._targetBoundingCenter = null;
  44333. this.onMeshTargetChangedObservable.notifyObservers(null);
  44334. }
  44335. this.rebuildAnglesAndRadius();
  44336. };
  44337. ArcRotateCamera.prototype._getViewMatrix = function () {
  44338. // Compute
  44339. var cosa = Math.cos(this.alpha);
  44340. var sina = Math.sin(this.alpha);
  44341. var cosb = Math.cos(this.beta);
  44342. var sinb = Math.sin(this.beta);
  44343. if (sinb === 0) {
  44344. sinb = 0.0001;
  44345. }
  44346. var target = this._getTargetPosition();
  44347. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44348. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44349. if (!this._collider) {
  44350. this._collider = new BABYLON.Collider();
  44351. }
  44352. this._collider._radius = this.collisionRadius;
  44353. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44354. this._collisionTriggered = true;
  44355. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44356. }
  44357. else {
  44358. this.position.copyFrom(this._newPosition);
  44359. var up = this.upVector;
  44360. if (this.allowUpsideDown && sinb < 0) {
  44361. up = up.clone();
  44362. up = up.negate();
  44363. }
  44364. if (this.getScene().useRightHandedSystem) {
  44365. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44366. }
  44367. else {
  44368. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44369. }
  44370. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44371. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44372. }
  44373. this._currentTarget = target;
  44374. return this._viewMatrix;
  44375. };
  44376. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44377. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44378. meshes = meshes || this.getScene().meshes;
  44379. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44380. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44381. this.radius = distance * this.zoomOnFactor;
  44382. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44383. };
  44384. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44385. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44386. var meshesOrMinMaxVector;
  44387. var distance;
  44388. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44389. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44390. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44391. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44392. }
  44393. else {
  44394. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44395. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44396. distance = minMaxVectorAndDistance.distance;
  44397. }
  44398. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44399. if (!doNotUpdateMaxZ) {
  44400. this.maxZ = distance * 2;
  44401. }
  44402. };
  44403. /**
  44404. * @override
  44405. * Override Camera.createRigCamera
  44406. */
  44407. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44408. var alphaShift = 0;
  44409. switch (this.cameraRigMode) {
  44410. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44411. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44412. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44413. case BABYLON.Camera.RIG_MODE_VR:
  44414. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44415. break;
  44416. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44417. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44418. break;
  44419. }
  44420. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44421. rigCam._cameraRigParams = {};
  44422. return rigCam;
  44423. };
  44424. /**
  44425. * @override
  44426. * Override Camera._updateRigCameras
  44427. */
  44428. ArcRotateCamera.prototype._updateRigCameras = function () {
  44429. var camLeft = this._rigCameras[0];
  44430. var camRight = this._rigCameras[1];
  44431. camLeft.beta = camRight.beta = this.beta;
  44432. camLeft.radius = camRight.radius = this.radius;
  44433. switch (this.cameraRigMode) {
  44434. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44435. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44436. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44437. case BABYLON.Camera.RIG_MODE_VR:
  44438. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44439. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44440. break;
  44441. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44442. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44443. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44444. break;
  44445. }
  44446. _super.prototype._updateRigCameras.call(this);
  44447. };
  44448. ArcRotateCamera.prototype.dispose = function () {
  44449. this.inputs.clear();
  44450. _super.prototype.dispose.call(this);
  44451. };
  44452. ArcRotateCamera.prototype.getClassName = function () {
  44453. return "ArcRotateCamera";
  44454. };
  44455. __decorate([
  44456. BABYLON.serialize()
  44457. ], ArcRotateCamera.prototype, "alpha", void 0);
  44458. __decorate([
  44459. BABYLON.serialize()
  44460. ], ArcRotateCamera.prototype, "beta", void 0);
  44461. __decorate([
  44462. BABYLON.serialize()
  44463. ], ArcRotateCamera.prototype, "radius", void 0);
  44464. __decorate([
  44465. BABYLON.serializeAsVector3("target")
  44466. ], ArcRotateCamera.prototype, "_target", void 0);
  44467. __decorate([
  44468. BABYLON.serialize()
  44469. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44470. __decorate([
  44471. BABYLON.serialize()
  44472. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44473. __decorate([
  44474. BABYLON.serialize()
  44475. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44476. __decorate([
  44477. BABYLON.serialize()
  44478. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44479. __decorate([
  44480. BABYLON.serialize()
  44481. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44482. __decorate([
  44483. BABYLON.serialize()
  44484. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44485. __decorate([
  44486. BABYLON.serialize()
  44487. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44488. __decorate([
  44489. BABYLON.serialize()
  44490. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44491. __decorate([
  44492. BABYLON.serialize()
  44493. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44494. __decorate([
  44495. BABYLON.serialize()
  44496. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44497. __decorate([
  44498. BABYLON.serialize()
  44499. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44500. __decorate([
  44501. BABYLON.serialize()
  44502. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44503. __decorate([
  44504. BABYLON.serialize()
  44505. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44506. __decorate([
  44507. BABYLON.serializeAsVector3()
  44508. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44509. __decorate([
  44510. BABYLON.serialize()
  44511. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44512. __decorate([
  44513. BABYLON.serialize()
  44514. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44515. __decorate([
  44516. BABYLON.serialize()
  44517. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  44518. return ArcRotateCamera;
  44519. }(BABYLON.TargetCamera));
  44520. BABYLON.ArcRotateCamera = ArcRotateCamera;
  44521. })(BABYLON || (BABYLON = {}));
  44522. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  44523. var BABYLON;
  44524. (function (BABYLON) {
  44525. /**
  44526. * The HemisphericLight simulates the ambient environment light,
  44527. * so the passed direction is the light reflection direction, not the incoming direction.
  44528. */
  44529. var HemisphericLight = /** @class */ (function (_super) {
  44530. __extends(HemisphericLight, _super);
  44531. /**
  44532. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  44533. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  44534. * The HemisphericLight can't cast shadows.
  44535. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44536. * @param name The friendly name of the light
  44537. * @param direction The direction of the light reflection
  44538. * @param scene The scene the light belongs to
  44539. */
  44540. function HemisphericLight(name, direction, scene) {
  44541. var _this = _super.call(this, name, scene) || this;
  44542. /**
  44543. * The groundColor is the light in the opposite direction to the one specified during creation.
  44544. * 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.
  44545. */
  44546. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  44547. _this.direction = direction || BABYLON.Vector3.Up();
  44548. return _this;
  44549. }
  44550. HemisphericLight.prototype._buildUniformLayout = function () {
  44551. this._uniformBuffer.addUniform("vLightData", 4);
  44552. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44553. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44554. this._uniformBuffer.addUniform("vLightGround", 3);
  44555. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44556. this._uniformBuffer.addUniform("depthValues", 2);
  44557. this._uniformBuffer.create();
  44558. };
  44559. /**
  44560. * Returns the string "HemisphericLight".
  44561. * @return The class name
  44562. */
  44563. HemisphericLight.prototype.getClassName = function () {
  44564. return "HemisphericLight";
  44565. };
  44566. /**
  44567. * Sets the HemisphericLight direction towards the passed target (Vector3).
  44568. * Returns the updated direction.
  44569. * @param target The target the direction should point to
  44570. * @return The computed direction
  44571. */
  44572. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  44573. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  44574. return this.direction;
  44575. };
  44576. /**
  44577. * Returns the shadow generator associated to the light.
  44578. * @returns Always null for hemispheric lights because it does not support shadows.
  44579. */
  44580. HemisphericLight.prototype.getShadowGenerator = function () {
  44581. return null;
  44582. };
  44583. /**
  44584. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  44585. * @param effect The effect to update
  44586. * @param lightIndex The index of the light in the effect to update
  44587. * @returns The hemispheric light
  44588. */
  44589. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  44590. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  44591. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  44592. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  44593. return this;
  44594. };
  44595. /**
  44596. * @ignore internal use only.
  44597. */
  44598. HemisphericLight.prototype._getWorldMatrix = function () {
  44599. if (!this._worldMatrix) {
  44600. this._worldMatrix = BABYLON.Matrix.Identity();
  44601. }
  44602. return this._worldMatrix;
  44603. };
  44604. /**
  44605. * Returns the integer 3.
  44606. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44607. */
  44608. HemisphericLight.prototype.getTypeID = function () {
  44609. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  44610. };
  44611. __decorate([
  44612. BABYLON.serializeAsColor3()
  44613. ], HemisphericLight.prototype, "groundColor", void 0);
  44614. __decorate([
  44615. BABYLON.serializeAsVector3()
  44616. ], HemisphericLight.prototype, "direction", void 0);
  44617. return HemisphericLight;
  44618. }(BABYLON.Light));
  44619. BABYLON.HemisphericLight = HemisphericLight;
  44620. })(BABYLON || (BABYLON = {}));
  44621. //# sourceMappingURL=babylon.hemisphericLight.js.map
  44622. var BABYLON;
  44623. (function (BABYLON) {
  44624. /**
  44625. * Base implementation of @see IShadowLight
  44626. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  44627. */
  44628. var ShadowLight = /** @class */ (function (_super) {
  44629. __extends(ShadowLight, _super);
  44630. function ShadowLight() {
  44631. var _this = _super !== null && _super.apply(this, arguments) || this;
  44632. _this._needProjectionMatrixCompute = true;
  44633. return _this;
  44634. }
  44635. ShadowLight.prototype._setPosition = function (value) {
  44636. this._position = value;
  44637. };
  44638. Object.defineProperty(ShadowLight.prototype, "position", {
  44639. /**
  44640. * Sets the position the shadow will be casted from. Also use as the light position for both
  44641. * point and spot lights.
  44642. */
  44643. get: function () {
  44644. return this._position;
  44645. },
  44646. /**
  44647. * Sets the position the shadow will be casted from. Also use as the light position for both
  44648. * point and spot lights.
  44649. */
  44650. set: function (value) {
  44651. this._setPosition(value);
  44652. },
  44653. enumerable: true,
  44654. configurable: true
  44655. });
  44656. ShadowLight.prototype._setDirection = function (value) {
  44657. this._direction = value;
  44658. };
  44659. Object.defineProperty(ShadowLight.prototype, "direction", {
  44660. /**
  44661. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  44662. * Also use as the light direction on spot and directional lights.
  44663. */
  44664. get: function () {
  44665. return this._direction;
  44666. },
  44667. /**
  44668. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  44669. * Also use as the light direction on spot and directional lights.
  44670. */
  44671. set: function (value) {
  44672. this._setDirection(value);
  44673. },
  44674. enumerable: true,
  44675. configurable: true
  44676. });
  44677. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  44678. /**
  44679. * Gets the shadow projection clipping minimum z value.
  44680. */
  44681. get: function () {
  44682. return this._shadowMinZ;
  44683. },
  44684. /**
  44685. * Sets the shadow projection clipping minimum z value.
  44686. */
  44687. set: function (value) {
  44688. this._shadowMinZ = value;
  44689. this.forceProjectionMatrixCompute();
  44690. },
  44691. enumerable: true,
  44692. configurable: true
  44693. });
  44694. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  44695. /**
  44696. * Sets the shadow projection clipping maximum z value.
  44697. */
  44698. get: function () {
  44699. return this._shadowMaxZ;
  44700. },
  44701. /**
  44702. * Gets the shadow projection clipping maximum z value.
  44703. */
  44704. set: function (value) {
  44705. this._shadowMaxZ = value;
  44706. this.forceProjectionMatrixCompute();
  44707. },
  44708. enumerable: true,
  44709. configurable: true
  44710. });
  44711. /**
  44712. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  44713. * @returns true if the information has been computed, false if it does not need to (no parenting)
  44714. */
  44715. ShadowLight.prototype.computeTransformedInformation = function () {
  44716. if (this.parent && this.parent.getWorldMatrix) {
  44717. if (!this.transformedPosition) {
  44718. this.transformedPosition = BABYLON.Vector3.Zero();
  44719. }
  44720. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  44721. // In case the direction is present.
  44722. if (this.direction) {
  44723. if (!this.transformedDirection) {
  44724. this.transformedDirection = BABYLON.Vector3.Zero();
  44725. }
  44726. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  44727. }
  44728. return true;
  44729. }
  44730. return false;
  44731. };
  44732. /**
  44733. * Return the depth scale used for the shadow map.
  44734. * @returns the depth scale.
  44735. */
  44736. ShadowLight.prototype.getDepthScale = function () {
  44737. return 50.0;
  44738. };
  44739. /**
  44740. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  44741. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44742. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44743. */
  44744. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  44745. return this.transformedDirection ? this.transformedDirection : this.direction;
  44746. };
  44747. /**
  44748. * Returns the ShadowLight absolute position in the World.
  44749. * @returns the position vector in world space
  44750. */
  44751. ShadowLight.prototype.getAbsolutePosition = function () {
  44752. return this.transformedPosition ? this.transformedPosition : this.position;
  44753. };
  44754. /**
  44755. * Sets the ShadowLight direction toward the passed target.
  44756. * @param target The point tot target in local space
  44757. * @returns the updated ShadowLight direction
  44758. */
  44759. ShadowLight.prototype.setDirectionToTarget = function (target) {
  44760. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  44761. return this.direction;
  44762. };
  44763. /**
  44764. * Returns the light rotation in euler definition.
  44765. * @returns the x y z rotation in local space.
  44766. */
  44767. ShadowLight.prototype.getRotation = function () {
  44768. this.direction.normalize();
  44769. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  44770. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  44771. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  44772. };
  44773. /**
  44774. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  44775. * @returns true if a cube texture needs to be use
  44776. */
  44777. ShadowLight.prototype.needCube = function () {
  44778. return false;
  44779. };
  44780. /**
  44781. * Detects if the projection matrix requires to be recomputed this frame.
  44782. * @returns true if it requires to be recomputed otherwise, false.
  44783. */
  44784. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  44785. return this._needProjectionMatrixCompute;
  44786. };
  44787. /**
  44788. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  44789. */
  44790. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  44791. this._needProjectionMatrixCompute = true;
  44792. };
  44793. /**
  44794. * Get the world matrix of the sahdow lights.
  44795. * @ignore Internal Use Only
  44796. */
  44797. ShadowLight.prototype._getWorldMatrix = function () {
  44798. if (!this._worldMatrix) {
  44799. this._worldMatrix = BABYLON.Matrix.Identity();
  44800. }
  44801. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  44802. return this._worldMatrix;
  44803. };
  44804. /**
  44805. * Gets the minZ used for shadow according to both the scene and the light.
  44806. * @param activeCamera The camera we are returning the min for
  44807. * @returns the depth min z
  44808. */
  44809. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  44810. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  44811. };
  44812. /**
  44813. * Gets the maxZ used for shadow according to both the scene and the light.
  44814. * @param activeCamera The camera we are returning the max for
  44815. * @returns the depth max z
  44816. */
  44817. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  44818. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  44819. };
  44820. /**
  44821. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  44822. * @param matrix The materix to updated with the projection information
  44823. * @param viewMatrix The transform matrix of the light
  44824. * @param renderList The list of mesh to render in the map
  44825. * @returns The current light
  44826. */
  44827. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44828. if (this.customProjectionMatrixBuilder) {
  44829. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  44830. }
  44831. else {
  44832. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44833. }
  44834. return this;
  44835. };
  44836. __decorate([
  44837. BABYLON.serializeAsVector3()
  44838. ], ShadowLight.prototype, "position", null);
  44839. __decorate([
  44840. BABYLON.serializeAsVector3()
  44841. ], ShadowLight.prototype, "direction", null);
  44842. __decorate([
  44843. BABYLON.serialize()
  44844. ], ShadowLight.prototype, "shadowMinZ", null);
  44845. __decorate([
  44846. BABYLON.serialize()
  44847. ], ShadowLight.prototype, "shadowMaxZ", null);
  44848. return ShadowLight;
  44849. }(BABYLON.Light));
  44850. BABYLON.ShadowLight = ShadowLight;
  44851. })(BABYLON || (BABYLON = {}));
  44852. //# sourceMappingURL=babylon.shadowLight.js.map
  44853. var BABYLON;
  44854. (function (BABYLON) {
  44855. /**
  44856. * A point light is a light defined by an unique point in world space.
  44857. * The light is emitted in every direction from this point.
  44858. * A good example of a point light is a standard light bulb.
  44859. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44860. */
  44861. var PointLight = /** @class */ (function (_super) {
  44862. __extends(PointLight, _super);
  44863. /**
  44864. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  44865. * A PointLight emits the light in every direction.
  44866. * It can cast shadows.
  44867. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  44868. * ```javascript
  44869. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  44870. * ```
  44871. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44872. * @param name The light friendly name
  44873. * @param position The position of the point light in the scene
  44874. * @param scene The scene the lights belongs to
  44875. */
  44876. function PointLight(name, position, scene) {
  44877. var _this = _super.call(this, name, scene) || this;
  44878. _this._shadowAngle = Math.PI / 2;
  44879. _this.position = position;
  44880. return _this;
  44881. }
  44882. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  44883. /**
  44884. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44885. * This specifies what angle the shadow will use to be created.
  44886. *
  44887. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44888. */
  44889. get: function () {
  44890. return this._shadowAngle;
  44891. },
  44892. /**
  44893. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44894. * This specifies what angle the shadow will use to be created.
  44895. *
  44896. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44897. */
  44898. set: function (value) {
  44899. this._shadowAngle = value;
  44900. this.forceProjectionMatrixCompute();
  44901. },
  44902. enumerable: true,
  44903. configurable: true
  44904. });
  44905. Object.defineProperty(PointLight.prototype, "direction", {
  44906. /**
  44907. * Gets the direction if it has been set.
  44908. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44909. */
  44910. get: function () {
  44911. return this._direction;
  44912. },
  44913. /**
  44914. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44915. */
  44916. set: function (value) {
  44917. var previousNeedCube = this.needCube();
  44918. this._direction = value;
  44919. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  44920. this._shadowGenerator.recreateShadowMap();
  44921. }
  44922. },
  44923. enumerable: true,
  44924. configurable: true
  44925. });
  44926. /**
  44927. * Returns the string "PointLight"
  44928. * @returns the class name
  44929. */
  44930. PointLight.prototype.getClassName = function () {
  44931. return "PointLight";
  44932. };
  44933. /**
  44934. * Returns the integer 0.
  44935. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44936. */
  44937. PointLight.prototype.getTypeID = function () {
  44938. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  44939. };
  44940. /**
  44941. * Specifies wether or not the shadowmap should be a cube texture.
  44942. * @returns true if the shadowmap needs to be a cube texture.
  44943. */
  44944. PointLight.prototype.needCube = function () {
  44945. return !this.direction;
  44946. };
  44947. /**
  44948. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  44949. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44950. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44951. */
  44952. PointLight.prototype.getShadowDirection = function (faceIndex) {
  44953. if (this.direction) {
  44954. return _super.prototype.getShadowDirection.call(this, faceIndex);
  44955. }
  44956. else {
  44957. switch (faceIndex) {
  44958. case 0:
  44959. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  44960. case 1:
  44961. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  44962. case 2:
  44963. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  44964. case 3:
  44965. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  44966. case 4:
  44967. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  44968. case 5:
  44969. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  44970. }
  44971. }
  44972. return BABYLON.Vector3.Zero();
  44973. };
  44974. /**
  44975. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  44976. * - fov = PI / 2
  44977. * - aspect ratio : 1.0
  44978. * - z-near and far equal to the active camera minZ and maxZ.
  44979. * Returns the PointLight.
  44980. */
  44981. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44982. var activeCamera = this.getScene().activeCamera;
  44983. if (!activeCamera) {
  44984. return;
  44985. }
  44986. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  44987. };
  44988. PointLight.prototype._buildUniformLayout = function () {
  44989. this._uniformBuffer.addUniform("vLightData", 4);
  44990. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44991. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44992. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44993. this._uniformBuffer.addUniform("depthValues", 2);
  44994. this._uniformBuffer.create();
  44995. };
  44996. /**
  44997. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  44998. * @param effect The effect to update
  44999. * @param lightIndex The index of the light in the effect to update
  45000. * @returns The point light
  45001. */
  45002. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45003. if (this.computeTransformedInformation()) {
  45004. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45005. return this;
  45006. }
  45007. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45008. return this;
  45009. };
  45010. __decorate([
  45011. BABYLON.serialize()
  45012. ], PointLight.prototype, "shadowAngle", null);
  45013. return PointLight;
  45014. }(BABYLON.ShadowLight));
  45015. BABYLON.PointLight = PointLight;
  45016. })(BABYLON || (BABYLON = {}));
  45017. //# sourceMappingURL=babylon.pointLight.js.map
  45018. var BABYLON;
  45019. (function (BABYLON) {
  45020. /**
  45021. * A directional light is defined by a direction (what a surprise!).
  45022. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45023. * 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.
  45024. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45025. */
  45026. var DirectionalLight = /** @class */ (function (_super) {
  45027. __extends(DirectionalLight, _super);
  45028. /**
  45029. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45030. * The directional light is emitted from everywhere in the given direction.
  45031. * It can cast shawdows.
  45032. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45033. * @param name The friendly name of the light
  45034. * @param direction The direction of the light
  45035. * @param scene The scene the light belongs to
  45036. */
  45037. function DirectionalLight(name, direction, scene) {
  45038. var _this = _super.call(this, name, scene) || this;
  45039. _this._shadowFrustumSize = 0;
  45040. _this._shadowOrthoScale = 0.5;
  45041. /**
  45042. * Automatically compute the projection matrix to best fit (including all the casters)
  45043. * on each frame.
  45044. */
  45045. _this.autoUpdateExtends = true;
  45046. // Cache
  45047. _this._orthoLeft = Number.MAX_VALUE;
  45048. _this._orthoRight = Number.MIN_VALUE;
  45049. _this._orthoTop = Number.MIN_VALUE;
  45050. _this._orthoBottom = Number.MAX_VALUE;
  45051. _this.position = direction.scale(-1.0);
  45052. _this.direction = direction;
  45053. return _this;
  45054. }
  45055. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45056. /**
  45057. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45058. */
  45059. get: function () {
  45060. return this._shadowFrustumSize;
  45061. },
  45062. /**
  45063. * Specifies a fix frustum size for the shadow generation.
  45064. */
  45065. set: function (value) {
  45066. this._shadowFrustumSize = value;
  45067. this.forceProjectionMatrixCompute();
  45068. },
  45069. enumerable: true,
  45070. configurable: true
  45071. });
  45072. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45073. /**
  45074. * Gets the shadow projection scale against the optimal computed one.
  45075. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45076. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45077. */
  45078. get: function () {
  45079. return this._shadowOrthoScale;
  45080. },
  45081. /**
  45082. * Sets the shadow projection scale against the optimal computed one.
  45083. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45084. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45085. */
  45086. set: function (value) {
  45087. this._shadowOrthoScale = value;
  45088. this.forceProjectionMatrixCompute();
  45089. },
  45090. enumerable: true,
  45091. configurable: true
  45092. });
  45093. /**
  45094. * Returns the string "DirectionalLight".
  45095. * @return The class name
  45096. */
  45097. DirectionalLight.prototype.getClassName = function () {
  45098. return "DirectionalLight";
  45099. };
  45100. /**
  45101. * Returns the integer 1.
  45102. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45103. */
  45104. DirectionalLight.prototype.getTypeID = function () {
  45105. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45106. };
  45107. /**
  45108. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45109. * Returns the DirectionalLight Shadow projection matrix.
  45110. */
  45111. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45112. if (this.shadowFrustumSize > 0) {
  45113. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45114. }
  45115. else {
  45116. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45117. }
  45118. };
  45119. /**
  45120. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45121. * Returns the DirectionalLight Shadow projection matrix.
  45122. */
  45123. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45124. var activeCamera = this.getScene().activeCamera;
  45125. if (!activeCamera) {
  45126. return;
  45127. }
  45128. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45129. };
  45130. /**
  45131. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45132. * Returns the DirectionalLight Shadow projection matrix.
  45133. */
  45134. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45135. var activeCamera = this.getScene().activeCamera;
  45136. if (!activeCamera) {
  45137. return;
  45138. }
  45139. // Check extends
  45140. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45141. var tempVector3 = BABYLON.Vector3.Zero();
  45142. this._orthoLeft = Number.MAX_VALUE;
  45143. this._orthoRight = Number.MIN_VALUE;
  45144. this._orthoTop = Number.MIN_VALUE;
  45145. this._orthoBottom = Number.MAX_VALUE;
  45146. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45147. var mesh = renderList[meshIndex];
  45148. if (!mesh) {
  45149. continue;
  45150. }
  45151. var boundingInfo = mesh.getBoundingInfo();
  45152. var boundingBox = boundingInfo.boundingBox;
  45153. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45154. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45155. if (tempVector3.x < this._orthoLeft)
  45156. this._orthoLeft = tempVector3.x;
  45157. if (tempVector3.y < this._orthoBottom)
  45158. this._orthoBottom = tempVector3.y;
  45159. if (tempVector3.x > this._orthoRight)
  45160. this._orthoRight = tempVector3.x;
  45161. if (tempVector3.y > this._orthoTop)
  45162. this._orthoTop = tempVector3.y;
  45163. }
  45164. }
  45165. }
  45166. var xOffset = this._orthoRight - this._orthoLeft;
  45167. var yOffset = this._orthoTop - this._orthoBottom;
  45168. 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);
  45169. };
  45170. DirectionalLight.prototype._buildUniformLayout = function () {
  45171. this._uniformBuffer.addUniform("vLightData", 4);
  45172. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45173. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45174. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45175. this._uniformBuffer.addUniform("depthValues", 2);
  45176. this._uniformBuffer.create();
  45177. };
  45178. /**
  45179. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45180. * @param effect The effect to update
  45181. * @param lightIndex The index of the light in the effect to update
  45182. * @returns The directional light
  45183. */
  45184. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45185. if (this.computeTransformedInformation()) {
  45186. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45187. return this;
  45188. }
  45189. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45190. return this;
  45191. };
  45192. /**
  45193. * Gets the minZ used for shadow according to both the scene and the light.
  45194. *
  45195. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45196. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45197. * @param activeCamera The camera we are returning the min for
  45198. * @returns the depth min z
  45199. */
  45200. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45201. return 1;
  45202. };
  45203. /**
  45204. * Gets the maxZ used for shadow according to both the scene and the light.
  45205. *
  45206. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45207. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45208. * @param activeCamera The camera we are returning the max for
  45209. * @returns the depth max z
  45210. */
  45211. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45212. return 1;
  45213. };
  45214. __decorate([
  45215. BABYLON.serialize()
  45216. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45217. __decorate([
  45218. BABYLON.serialize()
  45219. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45220. __decorate([
  45221. BABYLON.serialize()
  45222. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45223. return DirectionalLight;
  45224. }(BABYLON.ShadowLight));
  45225. BABYLON.DirectionalLight = DirectionalLight;
  45226. })(BABYLON || (BABYLON = {}));
  45227. //# sourceMappingURL=babylon.directionalLight.js.map
  45228. var BABYLON;
  45229. (function (BABYLON) {
  45230. /**
  45231. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45232. * These values define a cone of light starting from the position, emitting toward the direction.
  45233. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45234. * and the exponent defines the speed of the decay of the light with distance (reach).
  45235. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45236. */
  45237. var SpotLight = /** @class */ (function (_super) {
  45238. __extends(SpotLight, _super);
  45239. /**
  45240. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45241. * It can cast shadows.
  45242. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45243. * @param name The light friendly name
  45244. * @param position The position of the spot light in the scene
  45245. * @param direction The direction of the light in the scene
  45246. * @param angle The cone angle of the light in Radians
  45247. * @param exponent The light decay speed with the distance from the emission spot
  45248. * @param scene The scene the lights belongs to
  45249. */
  45250. function SpotLight(name, position, direction, angle, exponent, scene) {
  45251. var _this = _super.call(this, name, scene) || this;
  45252. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45253. _this._projectionTextureLightNear = 1e-6;
  45254. _this._projectionTextureLightFar = 1000.0;
  45255. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45256. _this._projectionTextureViewLightDirty = true;
  45257. _this._projectionTextureProjectionLightDirty = true;
  45258. _this._projectionTextureDirty = true;
  45259. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45260. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45261. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45262. _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
  45263. _this.position = position;
  45264. _this.direction = direction;
  45265. _this.angle = angle;
  45266. _this.exponent = exponent;
  45267. return _this;
  45268. }
  45269. Object.defineProperty(SpotLight.prototype, "angle", {
  45270. /**
  45271. * Gets the cone angle of the spot light in Radians.
  45272. */
  45273. get: function () {
  45274. return this._angle;
  45275. },
  45276. /**
  45277. * Sets the cone angle of the spot light in Radians.
  45278. */
  45279. set: function (value) {
  45280. this._angle = value;
  45281. this._projectionTextureProjectionLightDirty = true;
  45282. this.forceProjectionMatrixCompute();
  45283. },
  45284. enumerable: true,
  45285. configurable: true
  45286. });
  45287. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45288. /**
  45289. * Allows scaling the angle of the light for shadow generation only.
  45290. */
  45291. get: function () {
  45292. return this._shadowAngleScale;
  45293. },
  45294. /**
  45295. * Allows scaling the angle of the light for shadow generation only.
  45296. */
  45297. set: function (value) {
  45298. this._shadowAngleScale = value;
  45299. this.forceProjectionMatrixCompute();
  45300. },
  45301. enumerable: true,
  45302. configurable: true
  45303. });
  45304. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45305. /**
  45306. * Allows reading the projecton texture
  45307. */
  45308. get: function () {
  45309. return this._projectionTextureMatrix;
  45310. },
  45311. enumerable: true,
  45312. configurable: true
  45313. });
  45314. ;
  45315. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45316. /**
  45317. * Gets the near clip of the Spotlight for texture projection.
  45318. */
  45319. get: function () {
  45320. return this._projectionTextureLightNear;
  45321. },
  45322. /**
  45323. * Sets the near clip of the Spotlight for texture projection.
  45324. */
  45325. set: function (value) {
  45326. this._projectionTextureLightNear = value;
  45327. this._projectionTextureProjectionLightDirty = true;
  45328. },
  45329. enumerable: true,
  45330. configurable: true
  45331. });
  45332. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45333. /**
  45334. * Gets the far clip of the Spotlight for texture projection.
  45335. */
  45336. get: function () {
  45337. return this._projectionTextureLightFar;
  45338. },
  45339. /**
  45340. * Sets the far clip of the Spotlight for texture projection.
  45341. */
  45342. set: function (value) {
  45343. this._projectionTextureLightFar = value;
  45344. this._projectionTextureProjectionLightDirty = true;
  45345. },
  45346. enumerable: true,
  45347. configurable: true
  45348. });
  45349. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45350. /**
  45351. * Gets the Up vector of the Spotlight for texture projection.
  45352. */
  45353. get: function () {
  45354. return this._projectionTextureUpDirection;
  45355. },
  45356. /**
  45357. * Sets the Up vector of the Spotlight for texture projection.
  45358. */
  45359. set: function (value) {
  45360. this._projectionTextureUpDirection = value;
  45361. this._projectionTextureProjectionLightDirty = true;
  45362. },
  45363. enumerable: true,
  45364. configurable: true
  45365. });
  45366. ;
  45367. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45368. /**
  45369. * Gets the projection texture of the light.
  45370. */
  45371. get: function () {
  45372. return this._projectionTexture;
  45373. },
  45374. /**
  45375. * Sets the projection texture of the light.
  45376. */
  45377. set: function (value) {
  45378. this._projectionTexture = value;
  45379. this._projectionTextureDirty = true;
  45380. },
  45381. enumerable: true,
  45382. configurable: true
  45383. });
  45384. /**
  45385. * Returns the string "SpotLight".
  45386. * @returns the class name
  45387. */
  45388. SpotLight.prototype.getClassName = function () {
  45389. return "SpotLight";
  45390. };
  45391. /**
  45392. * Returns the integer 2.
  45393. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45394. */
  45395. SpotLight.prototype.getTypeID = function () {
  45396. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45397. };
  45398. /**
  45399. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45400. */
  45401. SpotLight.prototype._setDirection = function (value) {
  45402. _super.prototype._setDirection.call(this, value);
  45403. this._projectionTextureViewLightDirty = true;
  45404. };
  45405. /**
  45406. * Overrides the position setter to recompute the projection texture view light Matrix.
  45407. */
  45408. SpotLight.prototype._setPosition = function (value) {
  45409. _super.prototype._setPosition.call(this, value);
  45410. this._projectionTextureViewLightDirty = true;
  45411. };
  45412. /**
  45413. * 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.
  45414. * Returns the SpotLight.
  45415. */
  45416. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45417. var activeCamera = this.getScene().activeCamera;
  45418. if (!activeCamera) {
  45419. return;
  45420. }
  45421. this._shadowAngleScale = this._shadowAngleScale || 1;
  45422. var angle = this._shadowAngleScale * this._angle;
  45423. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45424. };
  45425. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45426. this._projectionTextureViewLightDirty = false;
  45427. this._projectionTextureDirty = true;
  45428. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45429. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45430. };
  45431. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45432. this._projectionTextureProjectionLightDirty = false;
  45433. this._projectionTextureDirty = true;
  45434. var light_far = this.projectionTextureLightFar;
  45435. var light_near = this.projectionTextureLightNear;
  45436. var P = light_far / (light_far - light_near);
  45437. var Q = -P * light_near;
  45438. var S = 1.0 / Math.tan(this._angle / 2.0);
  45439. var A = 1.0;
  45440. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
  45441. };
  45442. /**
  45443. * Main function for light texture projection matrix computing.
  45444. */
  45445. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45446. this._projectionTextureDirty = false;
  45447. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45448. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45449. };
  45450. SpotLight.prototype._buildUniformLayout = function () {
  45451. this._uniformBuffer.addUniform("vLightData", 4);
  45452. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45453. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45454. this._uniformBuffer.addUniform("vLightDirection", 3);
  45455. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45456. this._uniformBuffer.addUniform("depthValues", 2);
  45457. this._uniformBuffer.create();
  45458. };
  45459. /**
  45460. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45461. * @param effect The effect to update
  45462. * @param lightIndex The index of the light in the effect to update
  45463. * @returns The spot light
  45464. */
  45465. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45466. var normalizeDirection;
  45467. if (this.computeTransformedInformation()) {
  45468. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45469. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45470. }
  45471. else {
  45472. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45473. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45474. }
  45475. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45476. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45477. if (this._projectionTextureViewLightDirty) {
  45478. this._computeProjectionTextureViewLightMatrix();
  45479. }
  45480. if (this._projectionTextureProjectionLightDirty) {
  45481. this._computeProjectionTextureProjectionLightMatrix();
  45482. }
  45483. if (this._projectionTextureDirty) {
  45484. this._computeProjectionTextureMatrix();
  45485. }
  45486. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45487. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45488. }
  45489. return this;
  45490. };
  45491. /**
  45492. * Disposes the light and the associated resources.
  45493. */
  45494. SpotLight.prototype.dispose = function () {
  45495. _super.prototype.dispose.call(this);
  45496. if (this._projectionTexture) {
  45497. this._projectionTexture.dispose();
  45498. }
  45499. };
  45500. __decorate([
  45501. BABYLON.serialize()
  45502. ], SpotLight.prototype, "angle", null);
  45503. __decorate([
  45504. BABYLON.serialize()
  45505. ], SpotLight.prototype, "shadowAngleScale", null);
  45506. __decorate([
  45507. BABYLON.serialize()
  45508. ], SpotLight.prototype, "exponent", void 0);
  45509. __decorate([
  45510. BABYLON.serialize()
  45511. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45512. __decorate([
  45513. BABYLON.serialize()
  45514. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45515. __decorate([
  45516. BABYLON.serialize()
  45517. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  45518. __decorate([
  45519. BABYLON.serializeAsTexture("projectedLightTexture")
  45520. ], SpotLight.prototype, "_projectionTexture", void 0);
  45521. return SpotLight;
  45522. }(BABYLON.ShadowLight));
  45523. BABYLON.SpotLight = SpotLight;
  45524. })(BABYLON || (BABYLON = {}));
  45525. //# sourceMappingURL=babylon.spotLight.js.map
  45526. var BABYLON;
  45527. (function (BABYLON) {
  45528. var AnimationRange = /** @class */ (function () {
  45529. function AnimationRange(name, from, to) {
  45530. this.name = name;
  45531. this.from = from;
  45532. this.to = to;
  45533. }
  45534. AnimationRange.prototype.clone = function () {
  45535. return new AnimationRange(this.name, this.from, this.to);
  45536. };
  45537. return AnimationRange;
  45538. }());
  45539. BABYLON.AnimationRange = AnimationRange;
  45540. /**
  45541. * Composed of a frame, and an action function
  45542. */
  45543. var AnimationEvent = /** @class */ (function () {
  45544. function AnimationEvent(frame, action, onlyOnce) {
  45545. this.frame = frame;
  45546. this.action = action;
  45547. this.onlyOnce = onlyOnce;
  45548. this.isDone = false;
  45549. }
  45550. return AnimationEvent;
  45551. }());
  45552. BABYLON.AnimationEvent = AnimationEvent;
  45553. var PathCursor = /** @class */ (function () {
  45554. function PathCursor(path) {
  45555. this.path = path;
  45556. this._onchange = new Array();
  45557. this.value = 0;
  45558. this.animations = new Array();
  45559. }
  45560. PathCursor.prototype.getPoint = function () {
  45561. var point = this.path.getPointAtLengthPosition(this.value);
  45562. return new BABYLON.Vector3(point.x, 0, point.y);
  45563. };
  45564. PathCursor.prototype.moveAhead = function (step) {
  45565. if (step === void 0) { step = 0.002; }
  45566. this.move(step);
  45567. return this;
  45568. };
  45569. PathCursor.prototype.moveBack = function (step) {
  45570. if (step === void 0) { step = 0.002; }
  45571. this.move(-step);
  45572. return this;
  45573. };
  45574. PathCursor.prototype.move = function (step) {
  45575. if (Math.abs(step) > 1) {
  45576. throw "step size should be less than 1.";
  45577. }
  45578. this.value += step;
  45579. this.ensureLimits();
  45580. this.raiseOnChange();
  45581. return this;
  45582. };
  45583. PathCursor.prototype.ensureLimits = function () {
  45584. while (this.value > 1) {
  45585. this.value -= 1;
  45586. }
  45587. while (this.value < 0) {
  45588. this.value += 1;
  45589. }
  45590. return this;
  45591. };
  45592. // used by animation engine
  45593. PathCursor.prototype.raiseOnChange = function () {
  45594. var _this = this;
  45595. this._onchange.forEach(function (f) { return f(_this); });
  45596. return this;
  45597. };
  45598. PathCursor.prototype.onchange = function (f) {
  45599. this._onchange.push(f);
  45600. return this;
  45601. };
  45602. return PathCursor;
  45603. }());
  45604. BABYLON.PathCursor = PathCursor;
  45605. var AnimationKeyInterpolation;
  45606. (function (AnimationKeyInterpolation) {
  45607. /**
  45608. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  45609. */
  45610. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  45611. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  45612. var Animation = /** @class */ (function () {
  45613. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  45614. this.name = name;
  45615. this.targetProperty = targetProperty;
  45616. this.framePerSecond = framePerSecond;
  45617. this.dataType = dataType;
  45618. this.loopMode = loopMode;
  45619. this.enableBlending = enableBlending;
  45620. this._runtimeAnimations = new Array();
  45621. // The set of event that will be linked to this animation
  45622. this._events = new Array();
  45623. this.blendingSpeed = 0.01;
  45624. this._ranges = {};
  45625. this.targetPropertyPath = targetProperty.split(".");
  45626. this.dataType = dataType;
  45627. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  45628. }
  45629. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  45630. var dataType = undefined;
  45631. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  45632. dataType = Animation.ANIMATIONTYPE_FLOAT;
  45633. }
  45634. else if (from instanceof BABYLON.Quaternion) {
  45635. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  45636. }
  45637. else if (from instanceof BABYLON.Vector3) {
  45638. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  45639. }
  45640. else if (from instanceof BABYLON.Vector2) {
  45641. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  45642. }
  45643. else if (from instanceof BABYLON.Color3) {
  45644. dataType = Animation.ANIMATIONTYPE_COLOR3;
  45645. }
  45646. else if (from instanceof BABYLON.Size) {
  45647. dataType = Animation.ANIMATIONTYPE_SIZE;
  45648. }
  45649. if (dataType == undefined) {
  45650. return null;
  45651. }
  45652. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  45653. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  45654. animation.setKeys(keys);
  45655. if (easingFunction !== undefined) {
  45656. animation.setEasingFunction(easingFunction);
  45657. }
  45658. return animation;
  45659. };
  45660. /**
  45661. * Sets up an animation.
  45662. * @param property the property to animate
  45663. * @param animationType the animation type to apply
  45664. * @param easingFunction the easing function used in the animation
  45665. * @returns The created animation
  45666. */
  45667. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  45668. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  45669. animation.setEasingFunction(easingFunction);
  45670. return animation;
  45671. };
  45672. /**
  45673. * Create and start an animation on a node
  45674. * @param {string} name defines the name of the global animation that will be run on all nodes
  45675. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45676. * @param {string} targetProperty defines property to animate
  45677. * @param {number} framePerSecond defines the number of frame per second yo use
  45678. * @param {number} totalFrame defines the number of frames in total
  45679. * @param {any} from defines the initial value
  45680. * @param {any} to defines the final value
  45681. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45682. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45683. * @param onAnimationEnd defines the callback to call when animation end
  45684. * @returns the animatable created for this animation
  45685. */
  45686. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45687. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45688. if (!animation) {
  45689. return null;
  45690. }
  45691. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45692. };
  45693. /**
  45694. * Create and start an animation on a node and its descendants
  45695. * @param {string} name defines the name of the global animation that will be run on all nodes
  45696. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45697. * @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.
  45698. * @param {string} targetProperty defines property to animate
  45699. * @param {number} framePerSecond defines the number of frame per second yo use
  45700. * @param {number} totalFrame defines the number of frames in total
  45701. * @param {any} from defines the initial value
  45702. * @param {any} to defines the final value
  45703. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45704. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45705. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  45706. * @returns the list of animatables created for all nodes
  45707. * @example https://www.babylonjs-playground.com/#MH0VLI
  45708. */
  45709. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45710. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45711. if (!animation) {
  45712. return null;
  45713. }
  45714. var scene = node.getScene();
  45715. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45716. };
  45717. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45718. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45719. if (!animation) {
  45720. return null;
  45721. }
  45722. node.animations.push(animation);
  45723. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45724. };
  45725. /**
  45726. * Transition property of the Camera to the target Value.
  45727. * @param property The property to transition
  45728. * @param targetValue The target Value of the property
  45729. * @param host The object where the property to animate belongs
  45730. * @param scene Scene used to run the animation
  45731. * @param frameRate Framerate (in frame/s) to use
  45732. * @param transition The transition type we want to use
  45733. * @param duration The duration of the animation, in milliseconds
  45734. * @param onAnimationEnd Call back trigger at the end of the animation.
  45735. */
  45736. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  45737. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  45738. if (duration <= 0) {
  45739. host[property] = targetValue;
  45740. if (onAnimationEnd) {
  45741. onAnimationEnd();
  45742. }
  45743. return null;
  45744. }
  45745. var endFrame = frameRate * (duration / 1000);
  45746. transition.setKeys([{
  45747. frame: 0,
  45748. value: host[property].clone ? host[property].clone() : host[property]
  45749. },
  45750. {
  45751. frame: endFrame,
  45752. value: targetValue
  45753. }]);
  45754. if (!host.animations) {
  45755. host.animations = [];
  45756. }
  45757. host.animations.push(transition);
  45758. var animation = scene.beginAnimation(host, 0, endFrame, false);
  45759. animation.onAnimationEnd = onAnimationEnd;
  45760. return animation;
  45761. };
  45762. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  45763. /**
  45764. * Return the array of runtime animations currently using this animation
  45765. */
  45766. get: function () {
  45767. return this._runtimeAnimations;
  45768. },
  45769. enumerable: true,
  45770. configurable: true
  45771. });
  45772. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  45773. get: function () {
  45774. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  45775. var runtimeAnimation = _a[_i];
  45776. if (!runtimeAnimation.isStopped) {
  45777. return true;
  45778. }
  45779. }
  45780. return false;
  45781. },
  45782. enumerable: true,
  45783. configurable: true
  45784. });
  45785. // Methods
  45786. /**
  45787. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  45788. */
  45789. Animation.prototype.toString = function (fullDetails) {
  45790. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  45791. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  45792. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  45793. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  45794. if (fullDetails) {
  45795. ret += ", Ranges: {";
  45796. var first = true;
  45797. for (var name in this._ranges) {
  45798. if (first) {
  45799. ret += ", ";
  45800. first = false;
  45801. }
  45802. ret += name;
  45803. }
  45804. ret += "}";
  45805. }
  45806. return ret;
  45807. };
  45808. /**
  45809. * Add an event to this animation.
  45810. */
  45811. Animation.prototype.addEvent = function (event) {
  45812. this._events.push(event);
  45813. };
  45814. /**
  45815. * Remove all events found at the given frame
  45816. * @param frame
  45817. */
  45818. Animation.prototype.removeEvents = function (frame) {
  45819. for (var index = 0; index < this._events.length; index++) {
  45820. if (this._events[index].frame === frame) {
  45821. this._events.splice(index, 1);
  45822. index--;
  45823. }
  45824. }
  45825. };
  45826. Animation.prototype.getEvents = function () {
  45827. return this._events;
  45828. };
  45829. Animation.prototype.createRange = function (name, from, to) {
  45830. // check name not already in use; could happen for bones after serialized
  45831. if (!this._ranges[name]) {
  45832. this._ranges[name] = new AnimationRange(name, from, to);
  45833. }
  45834. };
  45835. Animation.prototype.deleteRange = function (name, deleteFrames) {
  45836. if (deleteFrames === void 0) { deleteFrames = true; }
  45837. var range = this._ranges[name];
  45838. if (!range) {
  45839. return;
  45840. }
  45841. if (deleteFrames) {
  45842. var from = range.from;
  45843. var to = range.to;
  45844. // this loop MUST go high to low for multiple splices to work
  45845. for (var key = this._keys.length - 1; key >= 0; key--) {
  45846. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  45847. this._keys.splice(key, 1);
  45848. }
  45849. }
  45850. }
  45851. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  45852. };
  45853. Animation.prototype.getRange = function (name) {
  45854. return this._ranges[name];
  45855. };
  45856. Animation.prototype.getKeys = function () {
  45857. return this._keys;
  45858. };
  45859. Animation.prototype.getHighestFrame = function () {
  45860. var ret = 0;
  45861. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  45862. if (ret < this._keys[key].frame) {
  45863. ret = this._keys[key].frame;
  45864. }
  45865. }
  45866. return ret;
  45867. };
  45868. Animation.prototype.getEasingFunction = function () {
  45869. return this._easingFunction;
  45870. };
  45871. Animation.prototype.setEasingFunction = function (easingFunction) {
  45872. this._easingFunction = easingFunction;
  45873. };
  45874. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  45875. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  45876. };
  45877. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45878. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45879. };
  45880. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  45881. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  45882. };
  45883. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45884. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  45885. };
  45886. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  45887. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  45888. };
  45889. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45890. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45891. };
  45892. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  45893. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  45894. };
  45895. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45896. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45897. };
  45898. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  45899. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  45900. };
  45901. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  45902. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  45903. };
  45904. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  45905. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  45906. };
  45907. Animation.prototype.clone = function () {
  45908. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  45909. clone.enableBlending = this.enableBlending;
  45910. clone.blendingSpeed = this.blendingSpeed;
  45911. if (this._keys) {
  45912. clone.setKeys(this._keys);
  45913. }
  45914. if (this._ranges) {
  45915. clone._ranges = {};
  45916. for (var name in this._ranges) {
  45917. var range = this._ranges[name];
  45918. if (!range) {
  45919. continue;
  45920. }
  45921. clone._ranges[name] = range.clone();
  45922. }
  45923. }
  45924. return clone;
  45925. };
  45926. Animation.prototype.setKeys = function (values) {
  45927. this._keys = values.slice(0);
  45928. };
  45929. Animation.prototype.serialize = function () {
  45930. var serializationObject = {};
  45931. serializationObject.name = this.name;
  45932. serializationObject.property = this.targetProperty;
  45933. serializationObject.framePerSecond = this.framePerSecond;
  45934. serializationObject.dataType = this.dataType;
  45935. serializationObject.loopBehavior = this.loopMode;
  45936. serializationObject.enableBlending = this.enableBlending;
  45937. serializationObject.blendingSpeed = this.blendingSpeed;
  45938. var dataType = this.dataType;
  45939. serializationObject.keys = [];
  45940. var keys = this.getKeys();
  45941. for (var index = 0; index < keys.length; index++) {
  45942. var animationKey = keys[index];
  45943. var key = {};
  45944. key.frame = animationKey.frame;
  45945. switch (dataType) {
  45946. case Animation.ANIMATIONTYPE_FLOAT:
  45947. key.values = [animationKey.value];
  45948. break;
  45949. case Animation.ANIMATIONTYPE_QUATERNION:
  45950. case Animation.ANIMATIONTYPE_MATRIX:
  45951. case Animation.ANIMATIONTYPE_VECTOR3:
  45952. case Animation.ANIMATIONTYPE_COLOR3:
  45953. key.values = animationKey.value.asArray();
  45954. break;
  45955. }
  45956. serializationObject.keys.push(key);
  45957. }
  45958. serializationObject.ranges = [];
  45959. for (var name in this._ranges) {
  45960. var source = this._ranges[name];
  45961. if (!source) {
  45962. continue;
  45963. }
  45964. var range = {};
  45965. range.name = name;
  45966. range.from = source.from;
  45967. range.to = source.to;
  45968. serializationObject.ranges.push(range);
  45969. }
  45970. return serializationObject;
  45971. };
  45972. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  45973. get: function () {
  45974. return Animation._ANIMATIONTYPE_FLOAT;
  45975. },
  45976. enumerable: true,
  45977. configurable: true
  45978. });
  45979. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  45980. get: function () {
  45981. return Animation._ANIMATIONTYPE_VECTOR3;
  45982. },
  45983. enumerable: true,
  45984. configurable: true
  45985. });
  45986. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  45987. get: function () {
  45988. return Animation._ANIMATIONTYPE_VECTOR2;
  45989. },
  45990. enumerable: true,
  45991. configurable: true
  45992. });
  45993. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  45994. get: function () {
  45995. return Animation._ANIMATIONTYPE_SIZE;
  45996. },
  45997. enumerable: true,
  45998. configurable: true
  45999. });
  46000. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46001. get: function () {
  46002. return Animation._ANIMATIONTYPE_QUATERNION;
  46003. },
  46004. enumerable: true,
  46005. configurable: true
  46006. });
  46007. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46008. get: function () {
  46009. return Animation._ANIMATIONTYPE_MATRIX;
  46010. },
  46011. enumerable: true,
  46012. configurable: true
  46013. });
  46014. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46015. get: function () {
  46016. return Animation._ANIMATIONTYPE_COLOR3;
  46017. },
  46018. enumerable: true,
  46019. configurable: true
  46020. });
  46021. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46022. get: function () {
  46023. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46024. },
  46025. enumerable: true,
  46026. configurable: true
  46027. });
  46028. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46029. get: function () {
  46030. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46031. },
  46032. enumerable: true,
  46033. configurable: true
  46034. });
  46035. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46036. get: function () {
  46037. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46038. },
  46039. enumerable: true,
  46040. configurable: true
  46041. });
  46042. Animation.Parse = function (parsedAnimation) {
  46043. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46044. var dataType = parsedAnimation.dataType;
  46045. var keys = [];
  46046. var data;
  46047. var index;
  46048. if (parsedAnimation.enableBlending) {
  46049. animation.enableBlending = parsedAnimation.enableBlending;
  46050. }
  46051. if (parsedAnimation.blendingSpeed) {
  46052. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46053. }
  46054. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46055. var key = parsedAnimation.keys[index];
  46056. var inTangent;
  46057. var outTangent;
  46058. switch (dataType) {
  46059. case Animation.ANIMATIONTYPE_FLOAT:
  46060. data = key.values[0];
  46061. if (key.values.length >= 1) {
  46062. inTangent = key.values[1];
  46063. }
  46064. if (key.values.length >= 2) {
  46065. outTangent = key.values[2];
  46066. }
  46067. break;
  46068. case Animation.ANIMATIONTYPE_QUATERNION:
  46069. data = BABYLON.Quaternion.FromArray(key.values);
  46070. if (key.values.length >= 8) {
  46071. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46072. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46073. inTangent = _inTangent;
  46074. }
  46075. }
  46076. if (key.values.length >= 12) {
  46077. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46078. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46079. outTangent = _outTangent;
  46080. }
  46081. }
  46082. break;
  46083. case Animation.ANIMATIONTYPE_MATRIX:
  46084. data = BABYLON.Matrix.FromArray(key.values);
  46085. break;
  46086. case Animation.ANIMATIONTYPE_COLOR3:
  46087. data = BABYLON.Color3.FromArray(key.values);
  46088. break;
  46089. case Animation.ANIMATIONTYPE_VECTOR3:
  46090. default:
  46091. data = BABYLON.Vector3.FromArray(key.values);
  46092. break;
  46093. }
  46094. var keyData = {};
  46095. keyData.frame = key.frame;
  46096. keyData.value = data;
  46097. if (inTangent != undefined) {
  46098. keyData.inTangent = inTangent;
  46099. }
  46100. if (outTangent != undefined) {
  46101. keyData.outTangent = outTangent;
  46102. }
  46103. keys.push(keyData);
  46104. }
  46105. animation.setKeys(keys);
  46106. if (parsedAnimation.ranges) {
  46107. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46108. data = parsedAnimation.ranges[index];
  46109. animation.createRange(data.name, data.from, data.to);
  46110. }
  46111. }
  46112. return animation;
  46113. };
  46114. Animation.AppendSerializedAnimations = function (source, destination) {
  46115. if (source.animations) {
  46116. destination.animations = [];
  46117. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46118. var animation = source.animations[animationIndex];
  46119. destination.animations.push(animation.serialize());
  46120. }
  46121. }
  46122. };
  46123. Animation.AllowMatricesInterpolation = false;
  46124. // Statics
  46125. Animation._ANIMATIONTYPE_FLOAT = 0;
  46126. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46127. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46128. Animation._ANIMATIONTYPE_MATRIX = 3;
  46129. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46130. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46131. Animation._ANIMATIONTYPE_SIZE = 6;
  46132. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46133. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46134. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46135. return Animation;
  46136. }());
  46137. BABYLON.Animation = Animation;
  46138. })(BABYLON || (BABYLON = {}));
  46139. //# sourceMappingURL=babylon.animation.js.map
  46140. var BABYLON;
  46141. (function (BABYLON) {
  46142. /**
  46143. * This class defines the direct association between an animation and a target
  46144. */
  46145. var TargetedAnimation = /** @class */ (function () {
  46146. function TargetedAnimation() {
  46147. }
  46148. return TargetedAnimation;
  46149. }());
  46150. BABYLON.TargetedAnimation = TargetedAnimation;
  46151. /**
  46152. * Use this class to create coordinated animations on multiple targets
  46153. */
  46154. var AnimationGroup = /** @class */ (function () {
  46155. function AnimationGroup(name, scene) {
  46156. if (scene === void 0) { scene = null; }
  46157. this.name = name;
  46158. this._targetedAnimations = new Array();
  46159. this._animatables = new Array();
  46160. this._from = Number.MAX_VALUE;
  46161. this._to = -Number.MAX_VALUE;
  46162. this._speedRatio = 1;
  46163. this.onAnimationEndObservable = new BABYLON.Observable();
  46164. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46165. this._scene.animationGroups.push(this);
  46166. }
  46167. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46168. /**
  46169. * Define if the animations are started
  46170. */
  46171. get: function () {
  46172. return this._isStarted;
  46173. },
  46174. enumerable: true,
  46175. configurable: true
  46176. });
  46177. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46178. /**
  46179. * Gets or sets the speed ratio to use for all animations
  46180. */
  46181. get: function () {
  46182. return this._speedRatio;
  46183. },
  46184. /**
  46185. * Gets or sets the speed ratio to use for all animations
  46186. */
  46187. set: function (value) {
  46188. if (this._speedRatio === value) {
  46189. return;
  46190. }
  46191. this._speedRatio = value;
  46192. for (var index = 0; index < this._animatables.length; index++) {
  46193. var animatable = this._animatables[index];
  46194. animatable.speedRatio = this._speedRatio;
  46195. }
  46196. },
  46197. enumerable: true,
  46198. configurable: true
  46199. });
  46200. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46201. /**
  46202. * Gets the targeted animations for this animation group
  46203. */
  46204. get: function () {
  46205. return this._targetedAnimations;
  46206. },
  46207. enumerable: true,
  46208. configurable: true
  46209. });
  46210. /**
  46211. * Add an animation (with its target) in the group
  46212. * @param animation defines the animation we want to add
  46213. * @param target defines the target of the animation
  46214. * @returns the {BABYLON.TargetedAnimation} object
  46215. */
  46216. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46217. var targetedAnimation = {
  46218. animation: animation,
  46219. target: target
  46220. };
  46221. var keys = animation.getKeys();
  46222. if (this._from > keys[0].frame) {
  46223. this._from = keys[0].frame;
  46224. }
  46225. if (this._to < keys[keys.length - 1].frame) {
  46226. this._to = keys[keys.length - 1].frame;
  46227. }
  46228. this._targetedAnimations.push(targetedAnimation);
  46229. return targetedAnimation;
  46230. };
  46231. /**
  46232. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46233. * It can add constant keys at begin or end
  46234. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46235. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46236. */
  46237. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46238. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46239. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46240. beginFrame = Math.max(beginFrame, this._from);
  46241. endFrame = Math.min(endFrame, this._to);
  46242. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46243. var targetedAnimation = this._targetedAnimations[index];
  46244. var keys = targetedAnimation.animation.getKeys();
  46245. var startKey = keys[0];
  46246. var endKey = keys[keys.length - 1];
  46247. if (startKey.frame > beginFrame) {
  46248. var newKey = {
  46249. frame: beginFrame,
  46250. value: startKey.value,
  46251. inTangent: startKey.inTangent,
  46252. outTangent: startKey.outTangent,
  46253. interpolation: startKey.interpolation
  46254. };
  46255. keys.splice(0, 0, newKey);
  46256. }
  46257. if (endKey.frame < endFrame) {
  46258. var newKey = {
  46259. frame: endFrame,
  46260. value: endKey.value,
  46261. inTangent: endKey.outTangent,
  46262. outTangent: endKey.outTangent,
  46263. interpolation: endKey.interpolation
  46264. };
  46265. keys.push(newKey);
  46266. }
  46267. }
  46268. return this;
  46269. };
  46270. /**
  46271. * Start all animations on given targets
  46272. * @param loop defines if animations must loop
  46273. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46274. */
  46275. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46276. var _this = this;
  46277. if (loop === void 0) { loop = false; }
  46278. if (speedRatio === void 0) { speedRatio = 1; }
  46279. if (this._isStarted || this._targetedAnimations.length === 0) {
  46280. return this;
  46281. }
  46282. var _loop_1 = function () {
  46283. var targetedAnimation = this_1._targetedAnimations[index];
  46284. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46285. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46286. }));
  46287. };
  46288. var this_1 = this;
  46289. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46290. _loop_1();
  46291. }
  46292. this._speedRatio = speedRatio;
  46293. this._isStarted = true;
  46294. return this;
  46295. };
  46296. /**
  46297. * Pause all animations
  46298. */
  46299. AnimationGroup.prototype.pause = function () {
  46300. if (!this._isStarted) {
  46301. return this;
  46302. }
  46303. for (var index = 0; index < this._animatables.length; index++) {
  46304. var animatable = this._animatables[index];
  46305. animatable.pause();
  46306. }
  46307. return this;
  46308. };
  46309. /**
  46310. * Play all animations to initial state
  46311. * This function will start() the animations if they were not started or will restart() them if they were paused
  46312. * @param loop defines if animations must loop
  46313. */
  46314. AnimationGroup.prototype.play = function (loop) {
  46315. if (this.isStarted) {
  46316. if (loop !== undefined) {
  46317. for (var index = 0; index < this._animatables.length; index++) {
  46318. var animatable = this._animatables[index];
  46319. animatable.loopAnimation = loop;
  46320. }
  46321. }
  46322. this.restart();
  46323. }
  46324. else {
  46325. this.start(loop, this._speedRatio);
  46326. }
  46327. return this;
  46328. };
  46329. /**
  46330. * Reset all animations to initial state
  46331. */
  46332. AnimationGroup.prototype.reset = function () {
  46333. if (!this._isStarted) {
  46334. return this;
  46335. }
  46336. for (var index = 0; index < this._animatables.length; index++) {
  46337. var animatable = this._animatables[index];
  46338. animatable.reset();
  46339. }
  46340. return this;
  46341. };
  46342. /**
  46343. * Restart animations from key 0
  46344. */
  46345. AnimationGroup.prototype.restart = function () {
  46346. if (!this._isStarted) {
  46347. return this;
  46348. }
  46349. for (var index = 0; index < this._animatables.length; index++) {
  46350. var animatable = this._animatables[index];
  46351. animatable.restart();
  46352. }
  46353. return this;
  46354. };
  46355. /**
  46356. * Stop all animations
  46357. */
  46358. AnimationGroup.prototype.stop = function () {
  46359. if (!this._isStarted) {
  46360. return this;
  46361. }
  46362. for (var index = 0; index < this._animatables.length; index++) {
  46363. var animatable = this._animatables[index];
  46364. animatable.stop();
  46365. }
  46366. this._isStarted = false;
  46367. return this;
  46368. };
  46369. /**
  46370. * Dispose all associated resources
  46371. */
  46372. AnimationGroup.prototype.dispose = function () {
  46373. this._targetedAnimations = [];
  46374. this._animatables = [];
  46375. var index = this._scene.animationGroups.indexOf(this);
  46376. if (index > -1) {
  46377. this._scene.animationGroups.splice(index, 1);
  46378. }
  46379. };
  46380. return AnimationGroup;
  46381. }());
  46382. BABYLON.AnimationGroup = AnimationGroup;
  46383. })(BABYLON || (BABYLON = {}));
  46384. //# sourceMappingURL=babylon.animationGroup.js.map
  46385. var BABYLON;
  46386. (function (BABYLON) {
  46387. var RuntimeAnimation = /** @class */ (function () {
  46388. function RuntimeAnimation(target, animation) {
  46389. this._offsetsCache = {};
  46390. this._highLimitsCache = {};
  46391. this._stopped = false;
  46392. this._blendingFactor = 0;
  46393. this._ratioOffset = 0;
  46394. this._animation = animation;
  46395. this._target = target;
  46396. animation._runtimeAnimations.push(this);
  46397. }
  46398. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46399. get: function () {
  46400. return this._animation;
  46401. },
  46402. enumerable: true,
  46403. configurable: true
  46404. });
  46405. RuntimeAnimation.prototype.reset = function () {
  46406. this._offsetsCache = {};
  46407. this._highLimitsCache = {};
  46408. this.currentFrame = 0;
  46409. this._blendingFactor = 0;
  46410. this._originalBlendValue = null;
  46411. };
  46412. RuntimeAnimation.prototype.isStopped = function () {
  46413. return this._stopped;
  46414. };
  46415. RuntimeAnimation.prototype.dispose = function () {
  46416. var index = this._animation.runtimeAnimations.indexOf(this);
  46417. if (index > -1) {
  46418. this._animation.runtimeAnimations.splice(index, 1);
  46419. }
  46420. };
  46421. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46422. if (typeof value === "function") {
  46423. return value();
  46424. }
  46425. return value;
  46426. };
  46427. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46428. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46429. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46430. }
  46431. this.currentFrame = currentFrame;
  46432. var keys = this._animation.getKeys();
  46433. // Try to get a hash to find the right key
  46434. 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));
  46435. if (keys[startKeyIndex].frame >= currentFrame) {
  46436. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46437. startKeyIndex--;
  46438. }
  46439. }
  46440. for (var key = startKeyIndex; key < keys.length; key++) {
  46441. var endKey = keys[key + 1];
  46442. if (endKey.frame >= currentFrame) {
  46443. var startKey = keys[key];
  46444. var startValue = this._getKeyValue(startKey.value);
  46445. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46446. return startValue;
  46447. }
  46448. var endValue = this._getKeyValue(endKey.value);
  46449. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46450. var frameDelta = endKey.frame - startKey.frame;
  46451. // gradient : percent of currentFrame between the frame inf and the frame sup
  46452. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46453. // check for easingFunction and correction of gradient
  46454. var easingFunction = this._animation.getEasingFunction();
  46455. if (easingFunction != null) {
  46456. gradient = easingFunction.ease(gradient);
  46457. }
  46458. switch (this._animation.dataType) {
  46459. // Float
  46460. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46461. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46462. switch (loopMode) {
  46463. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46464. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46465. return floatValue;
  46466. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46467. return offsetValue * repeatCount + floatValue;
  46468. }
  46469. break;
  46470. // Quaternion
  46471. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46472. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46473. switch (loopMode) {
  46474. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46475. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46476. return quatValue;
  46477. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46478. return quatValue.add(offsetValue.scale(repeatCount));
  46479. }
  46480. return quatValue;
  46481. // Vector3
  46482. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46483. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46484. switch (loopMode) {
  46485. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46486. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46487. return vec3Value;
  46488. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46489. return vec3Value.add(offsetValue.scale(repeatCount));
  46490. }
  46491. // Vector2
  46492. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46493. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46494. switch (loopMode) {
  46495. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46496. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46497. return vec2Value;
  46498. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46499. return vec2Value.add(offsetValue.scale(repeatCount));
  46500. }
  46501. // Size
  46502. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46503. switch (loopMode) {
  46504. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46505. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46506. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46507. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46508. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46509. }
  46510. // Color3
  46511. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46512. switch (loopMode) {
  46513. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46514. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46515. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46516. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46517. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46518. }
  46519. // Matrix
  46520. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  46521. switch (loopMode) {
  46522. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46523. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46524. if (BABYLON.Animation.AllowMatricesInterpolation) {
  46525. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  46526. }
  46527. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46528. return startValue;
  46529. }
  46530. default:
  46531. break;
  46532. }
  46533. break;
  46534. }
  46535. }
  46536. return this._getKeyValue(keys[keys.length - 1].value);
  46537. };
  46538. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  46539. if (blend === void 0) { blend = false; }
  46540. // Set value
  46541. var path;
  46542. var destination;
  46543. var targetPropertyPath = this._animation.targetPropertyPath;
  46544. if (targetPropertyPath.length > 1) {
  46545. var property = this._target[targetPropertyPath[0]];
  46546. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  46547. property = property[targetPropertyPath[index]];
  46548. }
  46549. path = targetPropertyPath[targetPropertyPath.length - 1];
  46550. destination = property;
  46551. }
  46552. else {
  46553. path = targetPropertyPath[0];
  46554. destination = this._target;
  46555. }
  46556. // Blending
  46557. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  46558. if (!this._originalBlendValue) {
  46559. if (destination[path].clone) {
  46560. this._originalBlendValue = destination[path].clone();
  46561. }
  46562. else {
  46563. this._originalBlendValue = destination[path];
  46564. }
  46565. }
  46566. if (this._originalBlendValue.prototype) {
  46567. if (this._originalBlendValue.prototype.Lerp) {
  46568. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  46569. }
  46570. else {
  46571. destination[path] = currentValue;
  46572. }
  46573. }
  46574. else if (this._originalBlendValue.m) {
  46575. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  46576. }
  46577. else {
  46578. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  46579. }
  46580. this._blendingFactor += this._animation.blendingSpeed;
  46581. }
  46582. else {
  46583. destination[path] = currentValue;
  46584. }
  46585. if (this._target.markAsDirty) {
  46586. this._target.markAsDirty(this._animation.targetProperty);
  46587. }
  46588. };
  46589. RuntimeAnimation.prototype.goToFrame = function (frame) {
  46590. var keys = this._animation.getKeys();
  46591. if (frame < keys[0].frame) {
  46592. frame = keys[0].frame;
  46593. }
  46594. else if (frame > keys[keys.length - 1].frame) {
  46595. frame = keys[keys.length - 1].frame;
  46596. }
  46597. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  46598. this.setValue(currentValue);
  46599. };
  46600. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  46601. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  46602. this._ratioOffset = this._previousRatio - newRatio;
  46603. };
  46604. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  46605. if (blend === void 0) { blend = false; }
  46606. var targetPropertyPath = this._animation.targetPropertyPath;
  46607. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  46608. this._stopped = true;
  46609. return false;
  46610. }
  46611. var returnValue = true;
  46612. var keys = this._animation.getKeys();
  46613. // Adding a start key at frame 0 if missing
  46614. if (keys[0].frame !== 0) {
  46615. var newKey = { frame: 0, value: keys[0].value };
  46616. keys.splice(0, 0, newKey);
  46617. }
  46618. // Check limits
  46619. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  46620. from = keys[0].frame;
  46621. }
  46622. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  46623. to = keys[keys.length - 1].frame;
  46624. }
  46625. //to and from cannot be the same key
  46626. if (from === to) {
  46627. if (from > keys[0].frame) {
  46628. from--;
  46629. }
  46630. else if (to < keys[keys.length - 1].frame) {
  46631. to++;
  46632. }
  46633. }
  46634. // Compute ratio
  46635. var range = to - from;
  46636. var offsetValue;
  46637. // ratio represents the frame delta between from and to
  46638. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  46639. var highLimitValue = 0;
  46640. this._previousDelay = delay;
  46641. this._previousRatio = ratio;
  46642. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  46643. returnValue = false;
  46644. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  46645. }
  46646. else {
  46647. // Get max value if required
  46648. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  46649. var keyOffset = to.toString() + from.toString();
  46650. if (!this._offsetsCache[keyOffset]) {
  46651. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46652. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46653. switch (this._animation.dataType) {
  46654. // Float
  46655. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46656. this._offsetsCache[keyOffset] = toValue - fromValue;
  46657. break;
  46658. // Quaternion
  46659. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46660. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46661. break;
  46662. // Vector3
  46663. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46664. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46665. // Vector2
  46666. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46667. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46668. // Size
  46669. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46670. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46671. // Color3
  46672. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46673. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46674. default:
  46675. break;
  46676. }
  46677. this._highLimitsCache[keyOffset] = toValue;
  46678. }
  46679. highLimitValue = this._highLimitsCache[keyOffset];
  46680. offsetValue = this._offsetsCache[keyOffset];
  46681. }
  46682. }
  46683. if (offsetValue === undefined) {
  46684. switch (this._animation.dataType) {
  46685. // Float
  46686. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46687. offsetValue = 0;
  46688. break;
  46689. // Quaternion
  46690. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46691. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  46692. break;
  46693. // Vector3
  46694. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46695. offsetValue = BABYLON.Vector3.Zero();
  46696. break;
  46697. // Vector2
  46698. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46699. offsetValue = BABYLON.Vector2.Zero();
  46700. break;
  46701. // Size
  46702. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46703. offsetValue = BABYLON.Size.Zero();
  46704. break;
  46705. // Color3
  46706. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46707. offsetValue = BABYLON.Color3.Black();
  46708. }
  46709. }
  46710. // Compute value
  46711. var repeatCount = (ratio / range) >> 0;
  46712. var currentFrame = returnValue ? from + ratio % range : to;
  46713. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  46714. // Set value
  46715. this.setValue(currentValue);
  46716. // Check events
  46717. var events = this._animation.getEvents();
  46718. for (var index = 0; index < events.length; index++) {
  46719. // Make sure current frame has passed event frame and that event frame is within the current range
  46720. // Also, handle both forward and reverse animations
  46721. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  46722. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  46723. var event = events[index];
  46724. if (!event.isDone) {
  46725. // If event should be done only once, remove it.
  46726. if (event.onlyOnce) {
  46727. events.splice(index, 1);
  46728. index--;
  46729. }
  46730. event.isDone = true;
  46731. event.action();
  46732. } // Don't do anything if the event has already be done.
  46733. }
  46734. else if (events[index].isDone && !events[index].onlyOnce) {
  46735. // reset event, the animation is looping
  46736. events[index].isDone = false;
  46737. }
  46738. }
  46739. if (!returnValue) {
  46740. this._stopped = true;
  46741. }
  46742. return returnValue;
  46743. };
  46744. return RuntimeAnimation;
  46745. }());
  46746. BABYLON.RuntimeAnimation = RuntimeAnimation;
  46747. })(BABYLON || (BABYLON = {}));
  46748. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  46749. var BABYLON;
  46750. (function (BABYLON) {
  46751. var Animatable = /** @class */ (function () {
  46752. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  46753. if (fromFrame === void 0) { fromFrame = 0; }
  46754. if (toFrame === void 0) { toFrame = 100; }
  46755. if (loopAnimation === void 0) { loopAnimation = false; }
  46756. if (speedRatio === void 0) { speedRatio = 1.0; }
  46757. this.target = target;
  46758. this.fromFrame = fromFrame;
  46759. this.toFrame = toFrame;
  46760. this.loopAnimation = loopAnimation;
  46761. this.onAnimationEnd = onAnimationEnd;
  46762. this._localDelayOffset = null;
  46763. this._pausedDelay = null;
  46764. this._runtimeAnimations = new Array();
  46765. this._paused = false;
  46766. this._speedRatio = 1;
  46767. this.animationStarted = false;
  46768. if (animations) {
  46769. this.appendAnimations(target, animations);
  46770. }
  46771. this._speedRatio = speedRatio;
  46772. this._scene = scene;
  46773. scene._activeAnimatables.push(this);
  46774. }
  46775. Object.defineProperty(Animatable.prototype, "speedRatio", {
  46776. get: function () {
  46777. return this._speedRatio;
  46778. },
  46779. set: function (value) {
  46780. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  46781. var animation = this._runtimeAnimations[index];
  46782. animation._prepareForSpeedRatioChange(value);
  46783. }
  46784. this._speedRatio = value;
  46785. },
  46786. enumerable: true,
  46787. configurable: true
  46788. });
  46789. // Methods
  46790. Animatable.prototype.getAnimations = function () {
  46791. return this._runtimeAnimations;
  46792. };
  46793. Animatable.prototype.appendAnimations = function (target, animations) {
  46794. for (var index = 0; index < animations.length; index++) {
  46795. var animation = animations[index];
  46796. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  46797. }
  46798. };
  46799. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  46800. var runtimeAnimations = this._runtimeAnimations;
  46801. for (var index = 0; index < runtimeAnimations.length; index++) {
  46802. if (runtimeAnimations[index].animation.targetProperty === property) {
  46803. return runtimeAnimations[index].animation;
  46804. }
  46805. }
  46806. return null;
  46807. };
  46808. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  46809. var runtimeAnimations = this._runtimeAnimations;
  46810. for (var index = 0; index < runtimeAnimations.length; index++) {
  46811. if (runtimeAnimations[index].animation.targetProperty === property) {
  46812. return runtimeAnimations[index];
  46813. }
  46814. }
  46815. return null;
  46816. };
  46817. Animatable.prototype.reset = function () {
  46818. var runtimeAnimations = this._runtimeAnimations;
  46819. for (var index = 0; index < runtimeAnimations.length; index++) {
  46820. runtimeAnimations[index].reset();
  46821. }
  46822. // Reset to original value
  46823. for (index = 0; index < runtimeAnimations.length; index++) {
  46824. var animation = runtimeAnimations[index];
  46825. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  46826. }
  46827. this._localDelayOffset = null;
  46828. this._pausedDelay = null;
  46829. };
  46830. Animatable.prototype.enableBlending = function (blendingSpeed) {
  46831. var runtimeAnimations = this._runtimeAnimations;
  46832. for (var index = 0; index < runtimeAnimations.length; index++) {
  46833. runtimeAnimations[index].animation.enableBlending = true;
  46834. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  46835. }
  46836. };
  46837. Animatable.prototype.disableBlending = function () {
  46838. var runtimeAnimations = this._runtimeAnimations;
  46839. for (var index = 0; index < runtimeAnimations.length; index++) {
  46840. runtimeAnimations[index].animation.enableBlending = false;
  46841. }
  46842. };
  46843. Animatable.prototype.goToFrame = function (frame) {
  46844. var runtimeAnimations = this._runtimeAnimations;
  46845. if (runtimeAnimations[0]) {
  46846. var fps = runtimeAnimations[0].animation.framePerSecond;
  46847. var currentFrame = runtimeAnimations[0].currentFrame;
  46848. var adjustTime = frame - currentFrame;
  46849. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  46850. if (this._localDelayOffset === null) {
  46851. this._localDelayOffset = 0;
  46852. }
  46853. this._localDelayOffset -= delay;
  46854. }
  46855. for (var index = 0; index < runtimeAnimations.length; index++) {
  46856. runtimeAnimations[index].goToFrame(frame);
  46857. }
  46858. };
  46859. Animatable.prototype.pause = function () {
  46860. if (this._paused) {
  46861. return;
  46862. }
  46863. this._paused = true;
  46864. };
  46865. Animatable.prototype.restart = function () {
  46866. this._paused = false;
  46867. };
  46868. Animatable.prototype.stop = function (animationName) {
  46869. if (animationName) {
  46870. var idx = this._scene._activeAnimatables.indexOf(this);
  46871. if (idx > -1) {
  46872. var runtimeAnimations = this._runtimeAnimations;
  46873. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  46874. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  46875. continue;
  46876. }
  46877. runtimeAnimations[index].dispose();
  46878. runtimeAnimations.splice(index, 1);
  46879. }
  46880. if (runtimeAnimations.length == 0) {
  46881. this._scene._activeAnimatables.splice(idx, 1);
  46882. if (this.onAnimationEnd) {
  46883. this.onAnimationEnd();
  46884. }
  46885. }
  46886. }
  46887. }
  46888. else {
  46889. var index = this._scene._activeAnimatables.indexOf(this);
  46890. if (index > -1) {
  46891. this._scene._activeAnimatables.splice(index, 1);
  46892. var runtimeAnimations = this._runtimeAnimations;
  46893. for (var index = 0; index < runtimeAnimations.length; index++) {
  46894. runtimeAnimations[index].dispose();
  46895. }
  46896. if (this.onAnimationEnd) {
  46897. this.onAnimationEnd();
  46898. }
  46899. }
  46900. }
  46901. };
  46902. Animatable.prototype._animate = function (delay) {
  46903. if (this._paused) {
  46904. this.animationStarted = false;
  46905. if (this._pausedDelay === null) {
  46906. this._pausedDelay = delay;
  46907. }
  46908. return true;
  46909. }
  46910. if (this._localDelayOffset === null) {
  46911. this._localDelayOffset = delay;
  46912. this._pausedDelay = null;
  46913. }
  46914. else if (this._pausedDelay !== null) {
  46915. this._localDelayOffset += delay - this._pausedDelay;
  46916. this._pausedDelay = null;
  46917. }
  46918. // Animating
  46919. var running = false;
  46920. var runtimeAnimations = this._runtimeAnimations;
  46921. var index;
  46922. for (index = 0; index < runtimeAnimations.length; index++) {
  46923. var animation = runtimeAnimations[index];
  46924. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  46925. running = running || isRunning;
  46926. }
  46927. this.animationStarted = running;
  46928. if (!running) {
  46929. // Remove from active animatables
  46930. index = this._scene._activeAnimatables.indexOf(this);
  46931. this._scene._activeAnimatables.splice(index, 1);
  46932. // Dispose all runtime animations
  46933. for (index = 0; index < runtimeAnimations.length; index++) {
  46934. runtimeAnimations[index].dispose();
  46935. }
  46936. }
  46937. if (!running && this.onAnimationEnd) {
  46938. this.onAnimationEnd();
  46939. this.onAnimationEnd = null;
  46940. }
  46941. return running;
  46942. };
  46943. return Animatable;
  46944. }());
  46945. BABYLON.Animatable = Animatable;
  46946. })(BABYLON || (BABYLON = {}));
  46947. //# sourceMappingURL=babylon.animatable.js.map
  46948. var BABYLON;
  46949. (function (BABYLON) {
  46950. var EasingFunction = /** @class */ (function () {
  46951. function EasingFunction() {
  46952. // Properties
  46953. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  46954. }
  46955. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  46956. get: function () {
  46957. return EasingFunction._EASINGMODE_EASEIN;
  46958. },
  46959. enumerable: true,
  46960. configurable: true
  46961. });
  46962. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  46963. get: function () {
  46964. return EasingFunction._EASINGMODE_EASEOUT;
  46965. },
  46966. enumerable: true,
  46967. configurable: true
  46968. });
  46969. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  46970. get: function () {
  46971. return EasingFunction._EASINGMODE_EASEINOUT;
  46972. },
  46973. enumerable: true,
  46974. configurable: true
  46975. });
  46976. EasingFunction.prototype.setEasingMode = function (easingMode) {
  46977. var n = Math.min(Math.max(easingMode, 0), 2);
  46978. this._easingMode = n;
  46979. };
  46980. EasingFunction.prototype.getEasingMode = function () {
  46981. return this._easingMode;
  46982. };
  46983. EasingFunction.prototype.easeInCore = function (gradient) {
  46984. throw new Error('You must implement this method');
  46985. };
  46986. EasingFunction.prototype.ease = function (gradient) {
  46987. switch (this._easingMode) {
  46988. case EasingFunction.EASINGMODE_EASEIN:
  46989. return this.easeInCore(gradient);
  46990. case EasingFunction.EASINGMODE_EASEOUT:
  46991. return (1 - this.easeInCore(1 - gradient));
  46992. }
  46993. if (gradient >= 0.5) {
  46994. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  46995. }
  46996. return (this.easeInCore(gradient * 2) * 0.5);
  46997. };
  46998. //Statics
  46999. EasingFunction._EASINGMODE_EASEIN = 0;
  47000. EasingFunction._EASINGMODE_EASEOUT = 1;
  47001. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47002. return EasingFunction;
  47003. }());
  47004. BABYLON.EasingFunction = EasingFunction;
  47005. var CircleEase = /** @class */ (function (_super) {
  47006. __extends(CircleEase, _super);
  47007. function CircleEase() {
  47008. return _super !== null && _super.apply(this, arguments) || this;
  47009. }
  47010. CircleEase.prototype.easeInCore = function (gradient) {
  47011. gradient = Math.max(0, Math.min(1, gradient));
  47012. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47013. };
  47014. return CircleEase;
  47015. }(EasingFunction));
  47016. BABYLON.CircleEase = CircleEase;
  47017. var BackEase = /** @class */ (function (_super) {
  47018. __extends(BackEase, _super);
  47019. function BackEase(amplitude) {
  47020. if (amplitude === void 0) { amplitude = 1; }
  47021. var _this = _super.call(this) || this;
  47022. _this.amplitude = amplitude;
  47023. return _this;
  47024. }
  47025. BackEase.prototype.easeInCore = function (gradient) {
  47026. var num = Math.max(0, this.amplitude);
  47027. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47028. };
  47029. return BackEase;
  47030. }(EasingFunction));
  47031. BABYLON.BackEase = BackEase;
  47032. var BounceEase = /** @class */ (function (_super) {
  47033. __extends(BounceEase, _super);
  47034. function BounceEase(bounces, bounciness) {
  47035. if (bounces === void 0) { bounces = 3; }
  47036. if (bounciness === void 0) { bounciness = 2; }
  47037. var _this = _super.call(this) || this;
  47038. _this.bounces = bounces;
  47039. _this.bounciness = bounciness;
  47040. return _this;
  47041. }
  47042. BounceEase.prototype.easeInCore = function (gradient) {
  47043. var y = Math.max(0.0, this.bounces);
  47044. var bounciness = this.bounciness;
  47045. if (bounciness <= 1.0) {
  47046. bounciness = 1.001;
  47047. }
  47048. var num9 = Math.pow(bounciness, y);
  47049. var num5 = 1.0 - bounciness;
  47050. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47051. var num15 = gradient * num4;
  47052. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47053. var num3 = Math.floor(num65);
  47054. var num13 = num3 + 1.0;
  47055. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47056. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47057. var num7 = (num8 + num12) * 0.5;
  47058. var num6 = gradient - num7;
  47059. var num2 = num7 - num8;
  47060. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47061. };
  47062. return BounceEase;
  47063. }(EasingFunction));
  47064. BABYLON.BounceEase = BounceEase;
  47065. var CubicEase = /** @class */ (function (_super) {
  47066. __extends(CubicEase, _super);
  47067. function CubicEase() {
  47068. return _super !== null && _super.apply(this, arguments) || this;
  47069. }
  47070. CubicEase.prototype.easeInCore = function (gradient) {
  47071. return (gradient * gradient * gradient);
  47072. };
  47073. return CubicEase;
  47074. }(EasingFunction));
  47075. BABYLON.CubicEase = CubicEase;
  47076. var ElasticEase = /** @class */ (function (_super) {
  47077. __extends(ElasticEase, _super);
  47078. function ElasticEase(oscillations, springiness) {
  47079. if (oscillations === void 0) { oscillations = 3; }
  47080. if (springiness === void 0) { springiness = 3; }
  47081. var _this = _super.call(this) || this;
  47082. _this.oscillations = oscillations;
  47083. _this.springiness = springiness;
  47084. return _this;
  47085. }
  47086. ElasticEase.prototype.easeInCore = function (gradient) {
  47087. var num2;
  47088. var num3 = Math.max(0.0, this.oscillations);
  47089. var num = Math.max(0.0, this.springiness);
  47090. if (num == 0) {
  47091. num2 = gradient;
  47092. }
  47093. else {
  47094. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47095. }
  47096. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47097. };
  47098. return ElasticEase;
  47099. }(EasingFunction));
  47100. BABYLON.ElasticEase = ElasticEase;
  47101. var ExponentialEase = /** @class */ (function (_super) {
  47102. __extends(ExponentialEase, _super);
  47103. function ExponentialEase(exponent) {
  47104. if (exponent === void 0) { exponent = 2; }
  47105. var _this = _super.call(this) || this;
  47106. _this.exponent = exponent;
  47107. return _this;
  47108. }
  47109. ExponentialEase.prototype.easeInCore = function (gradient) {
  47110. if (this.exponent <= 0) {
  47111. return gradient;
  47112. }
  47113. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47114. };
  47115. return ExponentialEase;
  47116. }(EasingFunction));
  47117. BABYLON.ExponentialEase = ExponentialEase;
  47118. var PowerEase = /** @class */ (function (_super) {
  47119. __extends(PowerEase, _super);
  47120. function PowerEase(power) {
  47121. if (power === void 0) { power = 2; }
  47122. var _this = _super.call(this) || this;
  47123. _this.power = power;
  47124. return _this;
  47125. }
  47126. PowerEase.prototype.easeInCore = function (gradient) {
  47127. var y = Math.max(0.0, this.power);
  47128. return Math.pow(gradient, y);
  47129. };
  47130. return PowerEase;
  47131. }(EasingFunction));
  47132. BABYLON.PowerEase = PowerEase;
  47133. var QuadraticEase = /** @class */ (function (_super) {
  47134. __extends(QuadraticEase, _super);
  47135. function QuadraticEase() {
  47136. return _super !== null && _super.apply(this, arguments) || this;
  47137. }
  47138. QuadraticEase.prototype.easeInCore = function (gradient) {
  47139. return (gradient * gradient);
  47140. };
  47141. return QuadraticEase;
  47142. }(EasingFunction));
  47143. BABYLON.QuadraticEase = QuadraticEase;
  47144. var QuarticEase = /** @class */ (function (_super) {
  47145. __extends(QuarticEase, _super);
  47146. function QuarticEase() {
  47147. return _super !== null && _super.apply(this, arguments) || this;
  47148. }
  47149. QuarticEase.prototype.easeInCore = function (gradient) {
  47150. return (gradient * gradient * gradient * gradient);
  47151. };
  47152. return QuarticEase;
  47153. }(EasingFunction));
  47154. BABYLON.QuarticEase = QuarticEase;
  47155. var QuinticEase = /** @class */ (function (_super) {
  47156. __extends(QuinticEase, _super);
  47157. function QuinticEase() {
  47158. return _super !== null && _super.apply(this, arguments) || this;
  47159. }
  47160. QuinticEase.prototype.easeInCore = function (gradient) {
  47161. return (gradient * gradient * gradient * gradient * gradient);
  47162. };
  47163. return QuinticEase;
  47164. }(EasingFunction));
  47165. BABYLON.QuinticEase = QuinticEase;
  47166. var SineEase = /** @class */ (function (_super) {
  47167. __extends(SineEase, _super);
  47168. function SineEase() {
  47169. return _super !== null && _super.apply(this, arguments) || this;
  47170. }
  47171. SineEase.prototype.easeInCore = function (gradient) {
  47172. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47173. };
  47174. return SineEase;
  47175. }(EasingFunction));
  47176. BABYLON.SineEase = SineEase;
  47177. var BezierCurveEase = /** @class */ (function (_super) {
  47178. __extends(BezierCurveEase, _super);
  47179. function BezierCurveEase(x1, y1, x2, y2) {
  47180. if (x1 === void 0) { x1 = 0; }
  47181. if (y1 === void 0) { y1 = 0; }
  47182. if (x2 === void 0) { x2 = 1; }
  47183. if (y2 === void 0) { y2 = 1; }
  47184. var _this = _super.call(this) || this;
  47185. _this.x1 = x1;
  47186. _this.y1 = y1;
  47187. _this.x2 = x2;
  47188. _this.y2 = y2;
  47189. return _this;
  47190. }
  47191. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47192. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47193. };
  47194. return BezierCurveEase;
  47195. }(EasingFunction));
  47196. BABYLON.BezierCurveEase = BezierCurveEase;
  47197. })(BABYLON || (BABYLON = {}));
  47198. //# sourceMappingURL=babylon.easing.js.map
  47199. var BABYLON;
  47200. (function (BABYLON) {
  47201. var Condition = /** @class */ (function () {
  47202. function Condition(actionManager) {
  47203. this._actionManager = actionManager;
  47204. }
  47205. Condition.prototype.isValid = function () {
  47206. return true;
  47207. };
  47208. Condition.prototype._getProperty = function (propertyPath) {
  47209. return this._actionManager._getProperty(propertyPath);
  47210. };
  47211. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47212. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47213. };
  47214. Condition.prototype.serialize = function () {
  47215. };
  47216. Condition.prototype._serialize = function (serializedCondition) {
  47217. return {
  47218. type: 2,
  47219. children: [],
  47220. name: serializedCondition.name,
  47221. properties: serializedCondition.properties
  47222. };
  47223. };
  47224. return Condition;
  47225. }());
  47226. BABYLON.Condition = Condition;
  47227. var ValueCondition = /** @class */ (function (_super) {
  47228. __extends(ValueCondition, _super);
  47229. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47230. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47231. var _this = _super.call(this, actionManager) || this;
  47232. _this.propertyPath = propertyPath;
  47233. _this.value = value;
  47234. _this.operator = operator;
  47235. _this._target = target;
  47236. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47237. _this._property = _this._getProperty(_this.propertyPath);
  47238. return _this;
  47239. }
  47240. Object.defineProperty(ValueCondition, "IsEqual", {
  47241. get: function () {
  47242. return ValueCondition._IsEqual;
  47243. },
  47244. enumerable: true,
  47245. configurable: true
  47246. });
  47247. Object.defineProperty(ValueCondition, "IsDifferent", {
  47248. get: function () {
  47249. return ValueCondition._IsDifferent;
  47250. },
  47251. enumerable: true,
  47252. configurable: true
  47253. });
  47254. Object.defineProperty(ValueCondition, "IsGreater", {
  47255. get: function () {
  47256. return ValueCondition._IsGreater;
  47257. },
  47258. enumerable: true,
  47259. configurable: true
  47260. });
  47261. Object.defineProperty(ValueCondition, "IsLesser", {
  47262. get: function () {
  47263. return ValueCondition._IsLesser;
  47264. },
  47265. enumerable: true,
  47266. configurable: true
  47267. });
  47268. // Methods
  47269. ValueCondition.prototype.isValid = function () {
  47270. switch (this.operator) {
  47271. case ValueCondition.IsGreater:
  47272. return this._effectiveTarget[this._property] > this.value;
  47273. case ValueCondition.IsLesser:
  47274. return this._effectiveTarget[this._property] < this.value;
  47275. case ValueCondition.IsEqual:
  47276. case ValueCondition.IsDifferent:
  47277. var check;
  47278. if (this.value.equals) {
  47279. check = this.value.equals(this._effectiveTarget[this._property]);
  47280. }
  47281. else {
  47282. check = this.value === this._effectiveTarget[this._property];
  47283. }
  47284. return this.operator === ValueCondition.IsEqual ? check : !check;
  47285. }
  47286. return false;
  47287. };
  47288. ValueCondition.prototype.serialize = function () {
  47289. return this._serialize({
  47290. name: "ValueCondition",
  47291. properties: [
  47292. BABYLON.Action._GetTargetProperty(this._target),
  47293. { name: "propertyPath", value: this.propertyPath },
  47294. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47295. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47296. ]
  47297. });
  47298. };
  47299. ValueCondition.GetOperatorName = function (operator) {
  47300. switch (operator) {
  47301. case ValueCondition._IsEqual: return "IsEqual";
  47302. case ValueCondition._IsDifferent: return "IsDifferent";
  47303. case ValueCondition._IsGreater: return "IsGreater";
  47304. case ValueCondition._IsLesser: return "IsLesser";
  47305. default: return "";
  47306. }
  47307. };
  47308. // Statics
  47309. ValueCondition._IsEqual = 0;
  47310. ValueCondition._IsDifferent = 1;
  47311. ValueCondition._IsGreater = 2;
  47312. ValueCondition._IsLesser = 3;
  47313. return ValueCondition;
  47314. }(Condition));
  47315. BABYLON.ValueCondition = ValueCondition;
  47316. var PredicateCondition = /** @class */ (function (_super) {
  47317. __extends(PredicateCondition, _super);
  47318. function PredicateCondition(actionManager, predicate) {
  47319. var _this = _super.call(this, actionManager) || this;
  47320. _this.predicate = predicate;
  47321. return _this;
  47322. }
  47323. PredicateCondition.prototype.isValid = function () {
  47324. return this.predicate();
  47325. };
  47326. return PredicateCondition;
  47327. }(Condition));
  47328. BABYLON.PredicateCondition = PredicateCondition;
  47329. var StateCondition = /** @class */ (function (_super) {
  47330. __extends(StateCondition, _super);
  47331. function StateCondition(actionManager, target, value) {
  47332. var _this = _super.call(this, actionManager) || this;
  47333. _this.value = value;
  47334. _this._target = target;
  47335. return _this;
  47336. }
  47337. // Methods
  47338. StateCondition.prototype.isValid = function () {
  47339. return this._target.state === this.value;
  47340. };
  47341. StateCondition.prototype.serialize = function () {
  47342. return this._serialize({
  47343. name: "StateCondition",
  47344. properties: [
  47345. BABYLON.Action._GetTargetProperty(this._target),
  47346. { name: "value", value: this.value }
  47347. ]
  47348. });
  47349. };
  47350. return StateCondition;
  47351. }(Condition));
  47352. BABYLON.StateCondition = StateCondition;
  47353. })(BABYLON || (BABYLON = {}));
  47354. //# sourceMappingURL=babylon.condition.js.map
  47355. var BABYLON;
  47356. (function (BABYLON) {
  47357. var Action = /** @class */ (function () {
  47358. function Action(triggerOptions, condition) {
  47359. this.triggerOptions = triggerOptions;
  47360. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47361. if (triggerOptions.parameter) {
  47362. this.trigger = triggerOptions.trigger;
  47363. this._triggerParameter = triggerOptions.parameter;
  47364. }
  47365. else {
  47366. this.trigger = triggerOptions;
  47367. }
  47368. this._nextActiveAction = this;
  47369. this._condition = condition;
  47370. }
  47371. // Methods
  47372. Action.prototype._prepare = function () {
  47373. };
  47374. Action.prototype.getTriggerParameter = function () {
  47375. return this._triggerParameter;
  47376. };
  47377. Action.prototype._executeCurrent = function (evt) {
  47378. if (this._nextActiveAction._condition) {
  47379. var condition = this._nextActiveAction._condition;
  47380. var currentRenderId = this._actionManager.getScene().getRenderId();
  47381. // We cache the current evaluation for the current frame
  47382. if (condition._evaluationId === currentRenderId) {
  47383. if (!condition._currentResult) {
  47384. return;
  47385. }
  47386. }
  47387. else {
  47388. condition._evaluationId = currentRenderId;
  47389. if (!condition.isValid()) {
  47390. condition._currentResult = false;
  47391. return;
  47392. }
  47393. condition._currentResult = true;
  47394. }
  47395. }
  47396. this.onBeforeExecuteObservable.notifyObservers(this);
  47397. this._nextActiveAction.execute(evt);
  47398. this.skipToNextActiveAction();
  47399. };
  47400. Action.prototype.execute = function (evt) {
  47401. };
  47402. Action.prototype.skipToNextActiveAction = function () {
  47403. if (this._nextActiveAction._child) {
  47404. if (!this._nextActiveAction._child._actionManager) {
  47405. this._nextActiveAction._child._actionManager = this._actionManager;
  47406. }
  47407. this._nextActiveAction = this._nextActiveAction._child;
  47408. }
  47409. else {
  47410. this._nextActiveAction = this;
  47411. }
  47412. };
  47413. Action.prototype.then = function (action) {
  47414. this._child = action;
  47415. action._actionManager = this._actionManager;
  47416. action._prepare();
  47417. return action;
  47418. };
  47419. Action.prototype._getProperty = function (propertyPath) {
  47420. return this._actionManager._getProperty(propertyPath);
  47421. };
  47422. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47423. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47424. };
  47425. Action.prototype.serialize = function (parent) {
  47426. };
  47427. // Called by BABYLON.Action objects in serialize(...). Internal use
  47428. Action.prototype._serialize = function (serializedAction, parent) {
  47429. var serializationObject = {
  47430. type: 1,
  47431. children: [],
  47432. name: serializedAction.name,
  47433. properties: serializedAction.properties || []
  47434. };
  47435. // Serialize child
  47436. if (this._child) {
  47437. this._child.serialize(serializationObject);
  47438. }
  47439. // Check if "this" has a condition
  47440. if (this._condition) {
  47441. var serializedCondition = this._condition.serialize();
  47442. serializedCondition.children.push(serializationObject);
  47443. if (parent) {
  47444. parent.children.push(serializedCondition);
  47445. }
  47446. return serializedCondition;
  47447. }
  47448. if (parent) {
  47449. parent.children.push(serializationObject);
  47450. }
  47451. return serializationObject;
  47452. };
  47453. Action._SerializeValueAsString = function (value) {
  47454. if (typeof value === "number") {
  47455. return value.toString();
  47456. }
  47457. if (typeof value === "boolean") {
  47458. return value ? "true" : "false";
  47459. }
  47460. if (value instanceof BABYLON.Vector2) {
  47461. return value.x + ", " + value.y;
  47462. }
  47463. if (value instanceof BABYLON.Vector3) {
  47464. return value.x + ", " + value.y + ", " + value.z;
  47465. }
  47466. if (value instanceof BABYLON.Color3) {
  47467. return value.r + ", " + value.g + ", " + value.b;
  47468. }
  47469. if (value instanceof BABYLON.Color4) {
  47470. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47471. }
  47472. return value; // string
  47473. };
  47474. Action._GetTargetProperty = function (target) {
  47475. return {
  47476. name: "target",
  47477. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47478. : target instanceof BABYLON.Light ? "LightProperties"
  47479. : target instanceof BABYLON.Camera ? "CameraProperties"
  47480. : "SceneProperties",
  47481. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47482. };
  47483. };
  47484. return Action;
  47485. }());
  47486. BABYLON.Action = Action;
  47487. })(BABYLON || (BABYLON = {}));
  47488. //# sourceMappingURL=babylon.action.js.map
  47489. var BABYLON;
  47490. (function (BABYLON) {
  47491. /**
  47492. * ActionEvent is the event beint sent when an action is triggered.
  47493. */
  47494. var ActionEvent = /** @class */ (function () {
  47495. /**
  47496. * @param source The mesh or sprite that triggered the action.
  47497. * @param pointerX The X mouse cursor position at the time of the event
  47498. * @param pointerY The Y mouse cursor position at the time of the event
  47499. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47500. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47501. */
  47502. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47503. this.source = source;
  47504. this.pointerX = pointerX;
  47505. this.pointerY = pointerY;
  47506. this.meshUnderPointer = meshUnderPointer;
  47507. this.sourceEvent = sourceEvent;
  47508. this.additionalData = additionalData;
  47509. }
  47510. /**
  47511. * Helper function to auto-create an ActionEvent from a source mesh.
  47512. * @param source The source mesh that triggered the event
  47513. * @param evt {Event} The original (browser) event
  47514. */
  47515. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47516. var scene = source.getScene();
  47517. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47518. };
  47519. /**
  47520. * Helper function to auto-create an ActionEvent from a source mesh.
  47521. * @param source The source sprite that triggered the event
  47522. * @param scene Scene associated with the sprite
  47523. * @param evt {Event} The original (browser) event
  47524. */
  47525. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  47526. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47527. };
  47528. /**
  47529. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  47530. * @param scene the scene where the event occurred
  47531. * @param evt {Event} The original (browser) event
  47532. */
  47533. ActionEvent.CreateNewFromScene = function (scene, evt) {
  47534. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  47535. };
  47536. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  47537. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  47538. };
  47539. return ActionEvent;
  47540. }());
  47541. BABYLON.ActionEvent = ActionEvent;
  47542. /**
  47543. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47544. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  47545. */
  47546. var ActionManager = /** @class */ (function () {
  47547. function ActionManager(scene) {
  47548. // Members
  47549. this.actions = new Array();
  47550. this.hoverCursor = '';
  47551. this._scene = scene;
  47552. scene._actionManagers.push(this);
  47553. }
  47554. Object.defineProperty(ActionManager, "NothingTrigger", {
  47555. get: function () {
  47556. return ActionManager._NothingTrigger;
  47557. },
  47558. enumerable: true,
  47559. configurable: true
  47560. });
  47561. Object.defineProperty(ActionManager, "OnPickTrigger", {
  47562. get: function () {
  47563. return ActionManager._OnPickTrigger;
  47564. },
  47565. enumerable: true,
  47566. configurable: true
  47567. });
  47568. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  47569. get: function () {
  47570. return ActionManager._OnLeftPickTrigger;
  47571. },
  47572. enumerable: true,
  47573. configurable: true
  47574. });
  47575. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  47576. get: function () {
  47577. return ActionManager._OnRightPickTrigger;
  47578. },
  47579. enumerable: true,
  47580. configurable: true
  47581. });
  47582. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  47583. get: function () {
  47584. return ActionManager._OnCenterPickTrigger;
  47585. },
  47586. enumerable: true,
  47587. configurable: true
  47588. });
  47589. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  47590. get: function () {
  47591. return ActionManager._OnPickDownTrigger;
  47592. },
  47593. enumerable: true,
  47594. configurable: true
  47595. });
  47596. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  47597. get: function () {
  47598. return ActionManager._OnDoublePickTrigger;
  47599. },
  47600. enumerable: true,
  47601. configurable: true
  47602. });
  47603. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  47604. get: function () {
  47605. return ActionManager._OnPickUpTrigger;
  47606. },
  47607. enumerable: true,
  47608. configurable: true
  47609. });
  47610. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  47611. /// This trigger will only be raised if you also declared a OnPickDown
  47612. get: function () {
  47613. return ActionManager._OnPickOutTrigger;
  47614. },
  47615. enumerable: true,
  47616. configurable: true
  47617. });
  47618. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  47619. get: function () {
  47620. return ActionManager._OnLongPressTrigger;
  47621. },
  47622. enumerable: true,
  47623. configurable: true
  47624. });
  47625. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  47626. get: function () {
  47627. return ActionManager._OnPointerOverTrigger;
  47628. },
  47629. enumerable: true,
  47630. configurable: true
  47631. });
  47632. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  47633. get: function () {
  47634. return ActionManager._OnPointerOutTrigger;
  47635. },
  47636. enumerable: true,
  47637. configurable: true
  47638. });
  47639. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  47640. get: function () {
  47641. return ActionManager._OnEveryFrameTrigger;
  47642. },
  47643. enumerable: true,
  47644. configurable: true
  47645. });
  47646. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  47647. get: function () {
  47648. return ActionManager._OnIntersectionEnterTrigger;
  47649. },
  47650. enumerable: true,
  47651. configurable: true
  47652. });
  47653. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  47654. get: function () {
  47655. return ActionManager._OnIntersectionExitTrigger;
  47656. },
  47657. enumerable: true,
  47658. configurable: true
  47659. });
  47660. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  47661. get: function () {
  47662. return ActionManager._OnKeyDownTrigger;
  47663. },
  47664. enumerable: true,
  47665. configurable: true
  47666. });
  47667. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  47668. get: function () {
  47669. return ActionManager._OnKeyUpTrigger;
  47670. },
  47671. enumerable: true,
  47672. configurable: true
  47673. });
  47674. // Methods
  47675. ActionManager.prototype.dispose = function () {
  47676. var index = this._scene._actionManagers.indexOf(this);
  47677. for (var i = 0; i < this.actions.length; i++) {
  47678. var action = this.actions[i];
  47679. ActionManager.Triggers[action.trigger]--;
  47680. if (ActionManager.Triggers[action.trigger] === 0) {
  47681. delete ActionManager.Triggers[action.trigger];
  47682. }
  47683. }
  47684. if (index > -1) {
  47685. this._scene._actionManagers.splice(index, 1);
  47686. }
  47687. };
  47688. ActionManager.prototype.getScene = function () {
  47689. return this._scene;
  47690. };
  47691. /**
  47692. * Does this action manager handles actions of any of the given triggers
  47693. * @param {number[]} triggers - the triggers to be tested
  47694. * @return {boolean} whether one (or more) of the triggers is handeled
  47695. */
  47696. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  47697. for (var index = 0; index < this.actions.length; index++) {
  47698. var action = this.actions[index];
  47699. if (triggers.indexOf(action.trigger) > -1) {
  47700. return true;
  47701. }
  47702. }
  47703. return false;
  47704. };
  47705. /**
  47706. * Does this action manager handles actions of a given trigger
  47707. * @param {number} trigger - the trigger to be tested
  47708. * @return {boolean} whether the trigger is handeled
  47709. */
  47710. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  47711. for (var index = 0; index < this.actions.length; index++) {
  47712. var action = this.actions[index];
  47713. if (action.trigger === trigger) {
  47714. return true;
  47715. }
  47716. }
  47717. return false;
  47718. };
  47719. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  47720. /**
  47721. * Does this action manager has pointer triggers
  47722. * @return {boolean} whether or not it has pointer triggers
  47723. */
  47724. get: function () {
  47725. for (var index = 0; index < this.actions.length; index++) {
  47726. var action = this.actions[index];
  47727. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  47728. return true;
  47729. }
  47730. }
  47731. return false;
  47732. },
  47733. enumerable: true,
  47734. configurable: true
  47735. });
  47736. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  47737. /**
  47738. * Does this action manager has pick triggers
  47739. * @return {boolean} whether or not it has pick triggers
  47740. */
  47741. get: function () {
  47742. for (var index = 0; index < this.actions.length; index++) {
  47743. var action = this.actions[index];
  47744. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  47745. return true;
  47746. }
  47747. }
  47748. return false;
  47749. },
  47750. enumerable: true,
  47751. configurable: true
  47752. });
  47753. Object.defineProperty(ActionManager, "HasTriggers", {
  47754. /**
  47755. * Does exist one action manager with at least one trigger
  47756. * @return {boolean} whether or not it exists one action manager with one trigger
  47757. **/
  47758. get: function () {
  47759. for (var t in ActionManager.Triggers) {
  47760. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47761. return true;
  47762. }
  47763. }
  47764. return false;
  47765. },
  47766. enumerable: true,
  47767. configurable: true
  47768. });
  47769. Object.defineProperty(ActionManager, "HasPickTriggers", {
  47770. /**
  47771. * Does exist one action manager with at least one pick trigger
  47772. * @return {boolean} whether or not it exists one action manager with one pick trigger
  47773. **/
  47774. get: function () {
  47775. for (var t in ActionManager.Triggers) {
  47776. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47777. var t_int = parseInt(t);
  47778. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  47779. return true;
  47780. }
  47781. }
  47782. }
  47783. return false;
  47784. },
  47785. enumerable: true,
  47786. configurable: true
  47787. });
  47788. /**
  47789. * Does exist one action manager that handles actions of a given trigger
  47790. * @param {number} trigger - the trigger to be tested
  47791. * @return {boolean} whether the trigger is handeled by at least one action manager
  47792. **/
  47793. ActionManager.HasSpecificTrigger = function (trigger) {
  47794. for (var t in ActionManager.Triggers) {
  47795. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47796. var t_int = parseInt(t);
  47797. if (t_int === trigger) {
  47798. return true;
  47799. }
  47800. }
  47801. }
  47802. return false;
  47803. };
  47804. /**
  47805. * Registers an action to this action manager
  47806. * @param {BABYLON.Action} action - the action to be registered
  47807. * @return {BABYLON.Action} the action amended (prepared) after registration
  47808. */
  47809. ActionManager.prototype.registerAction = function (action) {
  47810. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  47811. if (this.getScene().actionManager !== this) {
  47812. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  47813. return null;
  47814. }
  47815. }
  47816. this.actions.push(action);
  47817. if (ActionManager.Triggers[action.trigger]) {
  47818. ActionManager.Triggers[action.trigger]++;
  47819. }
  47820. else {
  47821. ActionManager.Triggers[action.trigger] = 1;
  47822. }
  47823. action._actionManager = this;
  47824. action._prepare();
  47825. return action;
  47826. };
  47827. /**
  47828. * Unregisters an action to this action manager
  47829. * @param action The action to be unregistered
  47830. * @return whether the action has been unregistered
  47831. */
  47832. ActionManager.prototype.unregisterAction = function (action) {
  47833. var index = this.actions.indexOf(action);
  47834. if (index !== -1) {
  47835. this.actions.splice(index, 1);
  47836. ActionManager.Triggers[action.trigger] -= 1;
  47837. if (ActionManager.Triggers[action.trigger] === 0) {
  47838. delete ActionManager.Triggers[action.trigger];
  47839. }
  47840. delete action._actionManager;
  47841. return true;
  47842. }
  47843. return false;
  47844. };
  47845. /**
  47846. * Process a specific trigger
  47847. * @param {number} trigger - the trigger to process
  47848. * @param evt {BABYLON.ActionEvent} the event details to be processed
  47849. */
  47850. ActionManager.prototype.processTrigger = function (trigger, evt) {
  47851. for (var index = 0; index < this.actions.length; index++) {
  47852. var action = this.actions[index];
  47853. if (action.trigger === trigger) {
  47854. if (evt) {
  47855. if (trigger === ActionManager.OnKeyUpTrigger
  47856. || trigger === ActionManager.OnKeyDownTrigger) {
  47857. var parameter = action.getTriggerParameter();
  47858. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  47859. if (!parameter.toLowerCase) {
  47860. continue;
  47861. }
  47862. var lowerCase = parameter.toLowerCase();
  47863. if (lowerCase !== evt.sourceEvent.key) {
  47864. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  47865. var actualkey = String.fromCharCode(unicode).toLowerCase();
  47866. if (actualkey !== lowerCase) {
  47867. continue;
  47868. }
  47869. }
  47870. }
  47871. }
  47872. }
  47873. action._executeCurrent(evt);
  47874. }
  47875. }
  47876. };
  47877. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  47878. var properties = propertyPath.split(".");
  47879. for (var index = 0; index < properties.length - 1; index++) {
  47880. target = target[properties[index]];
  47881. }
  47882. return target;
  47883. };
  47884. ActionManager.prototype._getProperty = function (propertyPath) {
  47885. var properties = propertyPath.split(".");
  47886. return properties[properties.length - 1];
  47887. };
  47888. ActionManager.prototype.serialize = function (name) {
  47889. var root = {
  47890. children: new Array(),
  47891. name: name,
  47892. type: 3,
  47893. properties: new Array() // Empty for root but required
  47894. };
  47895. for (var i = 0; i < this.actions.length; i++) {
  47896. var triggerObject = {
  47897. type: 0,
  47898. children: new Array(),
  47899. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  47900. properties: new Array()
  47901. };
  47902. var triggerOptions = this.actions[i].triggerOptions;
  47903. if (triggerOptions && typeof triggerOptions !== "number") {
  47904. if (triggerOptions.parameter instanceof BABYLON.Node) {
  47905. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  47906. }
  47907. else {
  47908. var parameter = {};
  47909. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  47910. if (triggerOptions.parameter.mesh) {
  47911. parameter._meshId = triggerOptions.parameter.mesh.id;
  47912. }
  47913. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  47914. }
  47915. }
  47916. // Serialize child action, recursively
  47917. this.actions[i].serialize(triggerObject);
  47918. // Add serialized trigger
  47919. root.children.push(triggerObject);
  47920. }
  47921. return root;
  47922. };
  47923. ActionManager.Parse = function (parsedActions, object, scene) {
  47924. var actionManager = new ActionManager(scene);
  47925. if (object === null)
  47926. scene.actionManager = actionManager;
  47927. else
  47928. object.actionManager = actionManager;
  47929. // instanciate a new object
  47930. var instanciate = function (name, params) {
  47931. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  47932. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  47933. newInstance.constructor.apply(newInstance, params);
  47934. return newInstance;
  47935. };
  47936. var parseParameter = function (name, value, target, propertyPath) {
  47937. if (propertyPath === null) {
  47938. // String, boolean or float
  47939. var floatValue = parseFloat(value);
  47940. if (value === "true" || value === "false")
  47941. return value === "true";
  47942. else
  47943. return isNaN(floatValue) ? value : floatValue;
  47944. }
  47945. var effectiveTarget = propertyPath.split(".");
  47946. var values = value.split(",");
  47947. // Get effective Target
  47948. for (var i = 0; i < effectiveTarget.length; i++) {
  47949. target = target[effectiveTarget[i]];
  47950. }
  47951. // Return appropriate value with its type
  47952. if (typeof (target) === "boolean")
  47953. return values[0] === "true";
  47954. if (typeof (target) === "string")
  47955. return values[0];
  47956. // Parameters with multiple values such as Vector3 etc.
  47957. var split = new Array();
  47958. for (var i = 0; i < values.length; i++)
  47959. split.push(parseFloat(values[i]));
  47960. if (target instanceof BABYLON.Vector3)
  47961. return BABYLON.Vector3.FromArray(split);
  47962. if (target instanceof BABYLON.Vector4)
  47963. return BABYLON.Vector4.FromArray(split);
  47964. if (target instanceof BABYLON.Color3)
  47965. return BABYLON.Color3.FromArray(split);
  47966. if (target instanceof BABYLON.Color4)
  47967. return BABYLON.Color4.FromArray(split);
  47968. return parseFloat(values[0]);
  47969. };
  47970. // traverse graph per trigger
  47971. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  47972. if (combineArray === void 0) { combineArray = null; }
  47973. if (parsedAction.detached)
  47974. return;
  47975. var parameters = new Array();
  47976. var target = null;
  47977. var propertyPath = null;
  47978. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  47979. // Parameters
  47980. if (parsedAction.type === 2)
  47981. parameters.push(actionManager);
  47982. else
  47983. parameters.push(trigger);
  47984. if (combine) {
  47985. var actions = new Array();
  47986. for (var j = 0; j < parsedAction.combine.length; j++) {
  47987. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  47988. }
  47989. parameters.push(actions);
  47990. }
  47991. else {
  47992. for (var i = 0; i < parsedAction.properties.length; i++) {
  47993. var value = parsedAction.properties[i].value;
  47994. var name = parsedAction.properties[i].name;
  47995. var targetType = parsedAction.properties[i].targetType;
  47996. if (name === "target")
  47997. if (targetType !== null && targetType === "SceneProperties")
  47998. value = target = scene;
  47999. else
  48000. value = target = scene.getNodeByName(value);
  48001. else if (name === "parent")
  48002. value = scene.getNodeByName(value);
  48003. else if (name === "sound")
  48004. value = scene.getSoundByName(value);
  48005. else if (name !== "propertyPath") {
  48006. if (parsedAction.type === 2 && name === "operator")
  48007. value = BABYLON.ValueCondition[value];
  48008. else
  48009. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48010. }
  48011. else {
  48012. propertyPath = value;
  48013. }
  48014. parameters.push(value);
  48015. }
  48016. }
  48017. if (combineArray === null) {
  48018. parameters.push(condition);
  48019. }
  48020. else {
  48021. parameters.push(null);
  48022. }
  48023. // If interpolate value action
  48024. if (parsedAction.name === "InterpolateValueAction") {
  48025. var param = parameters[parameters.length - 2];
  48026. parameters[parameters.length - 1] = param;
  48027. parameters[parameters.length - 2] = condition;
  48028. }
  48029. // Action or condition(s) and not CombineAction
  48030. var newAction = instanciate(parsedAction.name, parameters);
  48031. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48032. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48033. if (action)
  48034. action.then(nothing);
  48035. else
  48036. actionManager.registerAction(nothing);
  48037. action = nothing;
  48038. }
  48039. if (combineArray === null) {
  48040. if (newAction instanceof BABYLON.Condition) {
  48041. condition = newAction;
  48042. newAction = action;
  48043. }
  48044. else {
  48045. condition = null;
  48046. if (action)
  48047. action.then(newAction);
  48048. else
  48049. actionManager.registerAction(newAction);
  48050. }
  48051. }
  48052. else {
  48053. combineArray.push(newAction);
  48054. }
  48055. for (var i = 0; i < parsedAction.children.length; i++)
  48056. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48057. };
  48058. // triggers
  48059. for (var i = 0; i < parsedActions.children.length; i++) {
  48060. var triggerParams;
  48061. var trigger = parsedActions.children[i];
  48062. if (trigger.properties.length > 0) {
  48063. var param = trigger.properties[0].value;
  48064. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48065. if (value._meshId) {
  48066. value.mesh = scene.getMeshByID(value._meshId);
  48067. }
  48068. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48069. }
  48070. else
  48071. triggerParams = ActionManager[trigger.name];
  48072. for (var j = 0; j < trigger.children.length; j++) {
  48073. if (!trigger.detached)
  48074. traverse(trigger.children[j], triggerParams, null, null);
  48075. }
  48076. }
  48077. };
  48078. ActionManager.GetTriggerName = function (trigger) {
  48079. switch (trigger) {
  48080. case 0: return "NothingTrigger";
  48081. case 1: return "OnPickTrigger";
  48082. case 2: return "OnLeftPickTrigger";
  48083. case 3: return "OnRightPickTrigger";
  48084. case 4: return "OnCenterPickTrigger";
  48085. case 5: return "OnPickDownTrigger";
  48086. case 6: return "OnPickUpTrigger";
  48087. case 7: return "OnLongPressTrigger";
  48088. case 8: return "OnPointerOverTrigger";
  48089. case 9: return "OnPointerOutTrigger";
  48090. case 10: return "OnEveryFrameTrigger";
  48091. case 11: return "OnIntersectionEnterTrigger";
  48092. case 12: return "OnIntersectionExitTrigger";
  48093. case 13: return "OnKeyDownTrigger";
  48094. case 14: return "OnKeyUpTrigger";
  48095. case 15: return "OnPickOutTrigger";
  48096. default: return "";
  48097. }
  48098. };
  48099. // Statics
  48100. ActionManager._NothingTrigger = 0;
  48101. ActionManager._OnPickTrigger = 1;
  48102. ActionManager._OnLeftPickTrigger = 2;
  48103. ActionManager._OnRightPickTrigger = 3;
  48104. ActionManager._OnCenterPickTrigger = 4;
  48105. ActionManager._OnPickDownTrigger = 5;
  48106. ActionManager._OnDoublePickTrigger = 6;
  48107. ActionManager._OnPickUpTrigger = 7;
  48108. ActionManager._OnLongPressTrigger = 8;
  48109. ActionManager._OnPointerOverTrigger = 9;
  48110. ActionManager._OnPointerOutTrigger = 10;
  48111. ActionManager._OnEveryFrameTrigger = 11;
  48112. ActionManager._OnIntersectionEnterTrigger = 12;
  48113. ActionManager._OnIntersectionExitTrigger = 13;
  48114. ActionManager._OnKeyDownTrigger = 14;
  48115. ActionManager._OnKeyUpTrigger = 15;
  48116. ActionManager._OnPickOutTrigger = 16;
  48117. ActionManager.Triggers = {};
  48118. return ActionManager;
  48119. }());
  48120. BABYLON.ActionManager = ActionManager;
  48121. })(BABYLON || (BABYLON = {}));
  48122. //# sourceMappingURL=babylon.actionManager.js.map
  48123. var BABYLON;
  48124. (function (BABYLON) {
  48125. var InterpolateValueAction = /** @class */ (function (_super) {
  48126. __extends(InterpolateValueAction, _super);
  48127. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48128. if (duration === void 0) { duration = 1000; }
  48129. var _this = _super.call(this, triggerOptions, condition) || this;
  48130. _this.propertyPath = propertyPath;
  48131. _this.value = value;
  48132. _this.duration = duration;
  48133. _this.stopOtherAnimations = stopOtherAnimations;
  48134. _this.onInterpolationDone = onInterpolationDone;
  48135. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48136. _this._target = _this._effectiveTarget = target;
  48137. return _this;
  48138. }
  48139. InterpolateValueAction.prototype._prepare = function () {
  48140. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48141. this._property = this._getProperty(this.propertyPath);
  48142. };
  48143. InterpolateValueAction.prototype.execute = function () {
  48144. var _this = this;
  48145. var scene = this._actionManager.getScene();
  48146. var keys = [
  48147. {
  48148. frame: 0,
  48149. value: this._effectiveTarget[this._property]
  48150. }, {
  48151. frame: 100,
  48152. value: this.value
  48153. }
  48154. ];
  48155. var dataType;
  48156. if (typeof this.value === "number") {
  48157. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48158. }
  48159. else if (this.value instanceof BABYLON.Color3) {
  48160. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48161. }
  48162. else if (this.value instanceof BABYLON.Vector3) {
  48163. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48164. }
  48165. else if (this.value instanceof BABYLON.Matrix) {
  48166. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48167. }
  48168. else if (this.value instanceof BABYLON.Quaternion) {
  48169. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48170. }
  48171. else {
  48172. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48173. return;
  48174. }
  48175. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48176. animation.setKeys(keys);
  48177. if (this.stopOtherAnimations) {
  48178. scene.stopAnimation(this._effectiveTarget);
  48179. }
  48180. var wrapper = function () {
  48181. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48182. if (_this.onInterpolationDone) {
  48183. _this.onInterpolationDone();
  48184. }
  48185. };
  48186. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48187. };
  48188. InterpolateValueAction.prototype.serialize = function (parent) {
  48189. return _super.prototype._serialize.call(this, {
  48190. name: "InterpolateValueAction",
  48191. properties: [
  48192. BABYLON.Action._GetTargetProperty(this._target),
  48193. { name: "propertyPath", value: this.propertyPath },
  48194. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48195. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48196. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48197. ]
  48198. }, parent);
  48199. };
  48200. return InterpolateValueAction;
  48201. }(BABYLON.Action));
  48202. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48203. })(BABYLON || (BABYLON = {}));
  48204. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48205. var BABYLON;
  48206. (function (BABYLON) {
  48207. var SwitchBooleanAction = /** @class */ (function (_super) {
  48208. __extends(SwitchBooleanAction, _super);
  48209. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48210. var _this = _super.call(this, triggerOptions, condition) || this;
  48211. _this.propertyPath = propertyPath;
  48212. _this._target = _this._effectiveTarget = target;
  48213. return _this;
  48214. }
  48215. SwitchBooleanAction.prototype._prepare = function () {
  48216. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48217. this._property = this._getProperty(this.propertyPath);
  48218. };
  48219. SwitchBooleanAction.prototype.execute = function () {
  48220. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48221. };
  48222. SwitchBooleanAction.prototype.serialize = function (parent) {
  48223. return _super.prototype._serialize.call(this, {
  48224. name: "SwitchBooleanAction",
  48225. properties: [
  48226. BABYLON.Action._GetTargetProperty(this._target),
  48227. { name: "propertyPath", value: this.propertyPath }
  48228. ]
  48229. }, parent);
  48230. };
  48231. return SwitchBooleanAction;
  48232. }(BABYLON.Action));
  48233. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48234. var SetStateAction = /** @class */ (function (_super) {
  48235. __extends(SetStateAction, _super);
  48236. function SetStateAction(triggerOptions, target, value, condition) {
  48237. var _this = _super.call(this, triggerOptions, condition) || this;
  48238. _this.value = value;
  48239. _this._target = target;
  48240. return _this;
  48241. }
  48242. SetStateAction.prototype.execute = function () {
  48243. this._target.state = this.value;
  48244. };
  48245. SetStateAction.prototype.serialize = function (parent) {
  48246. return _super.prototype._serialize.call(this, {
  48247. name: "SetStateAction",
  48248. properties: [
  48249. BABYLON.Action._GetTargetProperty(this._target),
  48250. { name: "value", value: this.value }
  48251. ]
  48252. }, parent);
  48253. };
  48254. return SetStateAction;
  48255. }(BABYLON.Action));
  48256. BABYLON.SetStateAction = SetStateAction;
  48257. var SetValueAction = /** @class */ (function (_super) {
  48258. __extends(SetValueAction, _super);
  48259. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48260. var _this = _super.call(this, triggerOptions, condition) || this;
  48261. _this.propertyPath = propertyPath;
  48262. _this.value = value;
  48263. _this._target = _this._effectiveTarget = target;
  48264. return _this;
  48265. }
  48266. SetValueAction.prototype._prepare = function () {
  48267. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48268. this._property = this._getProperty(this.propertyPath);
  48269. };
  48270. SetValueAction.prototype.execute = function () {
  48271. this._effectiveTarget[this._property] = this.value;
  48272. if (this._target.markAsDirty) {
  48273. this._target.markAsDirty(this._property);
  48274. }
  48275. };
  48276. SetValueAction.prototype.serialize = function (parent) {
  48277. return _super.prototype._serialize.call(this, {
  48278. name: "SetValueAction",
  48279. properties: [
  48280. BABYLON.Action._GetTargetProperty(this._target),
  48281. { name: "propertyPath", value: this.propertyPath },
  48282. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48283. ]
  48284. }, parent);
  48285. };
  48286. return SetValueAction;
  48287. }(BABYLON.Action));
  48288. BABYLON.SetValueAction = SetValueAction;
  48289. var IncrementValueAction = /** @class */ (function (_super) {
  48290. __extends(IncrementValueAction, _super);
  48291. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48292. var _this = _super.call(this, triggerOptions, condition) || this;
  48293. _this.propertyPath = propertyPath;
  48294. _this.value = value;
  48295. _this._target = _this._effectiveTarget = target;
  48296. return _this;
  48297. }
  48298. IncrementValueAction.prototype._prepare = function () {
  48299. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48300. this._property = this._getProperty(this.propertyPath);
  48301. if (typeof this._effectiveTarget[this._property] !== "number") {
  48302. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48303. }
  48304. };
  48305. IncrementValueAction.prototype.execute = function () {
  48306. this._effectiveTarget[this._property] += this.value;
  48307. if (this._target.markAsDirty) {
  48308. this._target.markAsDirty(this._property);
  48309. }
  48310. };
  48311. IncrementValueAction.prototype.serialize = function (parent) {
  48312. return _super.prototype._serialize.call(this, {
  48313. name: "IncrementValueAction",
  48314. properties: [
  48315. BABYLON.Action._GetTargetProperty(this._target),
  48316. { name: "propertyPath", value: this.propertyPath },
  48317. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48318. ]
  48319. }, parent);
  48320. };
  48321. return IncrementValueAction;
  48322. }(BABYLON.Action));
  48323. BABYLON.IncrementValueAction = IncrementValueAction;
  48324. var PlayAnimationAction = /** @class */ (function (_super) {
  48325. __extends(PlayAnimationAction, _super);
  48326. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48327. var _this = _super.call(this, triggerOptions, condition) || this;
  48328. _this.from = from;
  48329. _this.to = to;
  48330. _this.loop = loop;
  48331. _this._target = target;
  48332. return _this;
  48333. }
  48334. PlayAnimationAction.prototype._prepare = function () {
  48335. };
  48336. PlayAnimationAction.prototype.execute = function () {
  48337. var scene = this._actionManager.getScene();
  48338. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48339. };
  48340. PlayAnimationAction.prototype.serialize = function (parent) {
  48341. return _super.prototype._serialize.call(this, {
  48342. name: "PlayAnimationAction",
  48343. properties: [
  48344. BABYLON.Action._GetTargetProperty(this._target),
  48345. { name: "from", value: String(this.from) },
  48346. { name: "to", value: String(this.to) },
  48347. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48348. ]
  48349. }, parent);
  48350. };
  48351. return PlayAnimationAction;
  48352. }(BABYLON.Action));
  48353. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48354. var StopAnimationAction = /** @class */ (function (_super) {
  48355. __extends(StopAnimationAction, _super);
  48356. function StopAnimationAction(triggerOptions, target, condition) {
  48357. var _this = _super.call(this, triggerOptions, condition) || this;
  48358. _this._target = target;
  48359. return _this;
  48360. }
  48361. StopAnimationAction.prototype._prepare = function () {
  48362. };
  48363. StopAnimationAction.prototype.execute = function () {
  48364. var scene = this._actionManager.getScene();
  48365. scene.stopAnimation(this._target);
  48366. };
  48367. StopAnimationAction.prototype.serialize = function (parent) {
  48368. return _super.prototype._serialize.call(this, {
  48369. name: "StopAnimationAction",
  48370. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48371. }, parent);
  48372. };
  48373. return StopAnimationAction;
  48374. }(BABYLON.Action));
  48375. BABYLON.StopAnimationAction = StopAnimationAction;
  48376. var DoNothingAction = /** @class */ (function (_super) {
  48377. __extends(DoNothingAction, _super);
  48378. function DoNothingAction(triggerOptions, condition) {
  48379. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48380. return _super.call(this, triggerOptions, condition) || this;
  48381. }
  48382. DoNothingAction.prototype.execute = function () {
  48383. };
  48384. DoNothingAction.prototype.serialize = function (parent) {
  48385. return _super.prototype._serialize.call(this, {
  48386. name: "DoNothingAction",
  48387. properties: []
  48388. }, parent);
  48389. };
  48390. return DoNothingAction;
  48391. }(BABYLON.Action));
  48392. BABYLON.DoNothingAction = DoNothingAction;
  48393. var CombineAction = /** @class */ (function (_super) {
  48394. __extends(CombineAction, _super);
  48395. function CombineAction(triggerOptions, children, condition) {
  48396. var _this = _super.call(this, triggerOptions, condition) || this;
  48397. _this.children = children;
  48398. return _this;
  48399. }
  48400. CombineAction.prototype._prepare = function () {
  48401. for (var index = 0; index < this.children.length; index++) {
  48402. this.children[index]._actionManager = this._actionManager;
  48403. this.children[index]._prepare();
  48404. }
  48405. };
  48406. CombineAction.prototype.execute = function (evt) {
  48407. for (var index = 0; index < this.children.length; index++) {
  48408. this.children[index].execute(evt);
  48409. }
  48410. };
  48411. CombineAction.prototype.serialize = function (parent) {
  48412. var serializationObject = _super.prototype._serialize.call(this, {
  48413. name: "CombineAction",
  48414. properties: [],
  48415. combine: []
  48416. }, parent);
  48417. for (var i = 0; i < this.children.length; i++) {
  48418. serializationObject.combine.push(this.children[i].serialize(null));
  48419. }
  48420. return serializationObject;
  48421. };
  48422. return CombineAction;
  48423. }(BABYLON.Action));
  48424. BABYLON.CombineAction = CombineAction;
  48425. var ExecuteCodeAction = /** @class */ (function (_super) {
  48426. __extends(ExecuteCodeAction, _super);
  48427. function ExecuteCodeAction(triggerOptions, func, condition) {
  48428. var _this = _super.call(this, triggerOptions, condition) || this;
  48429. _this.func = func;
  48430. return _this;
  48431. }
  48432. ExecuteCodeAction.prototype.execute = function (evt) {
  48433. this.func(evt);
  48434. };
  48435. return ExecuteCodeAction;
  48436. }(BABYLON.Action));
  48437. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48438. var SetParentAction = /** @class */ (function (_super) {
  48439. __extends(SetParentAction, _super);
  48440. function SetParentAction(triggerOptions, target, parent, condition) {
  48441. var _this = _super.call(this, triggerOptions, condition) || this;
  48442. _this._target = target;
  48443. _this._parent = parent;
  48444. return _this;
  48445. }
  48446. SetParentAction.prototype._prepare = function () {
  48447. };
  48448. SetParentAction.prototype.execute = function () {
  48449. if (this._target.parent === this._parent) {
  48450. return;
  48451. }
  48452. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48453. invertParentWorldMatrix.invert();
  48454. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48455. this._target.parent = this._parent;
  48456. };
  48457. SetParentAction.prototype.serialize = function (parent) {
  48458. return _super.prototype._serialize.call(this, {
  48459. name: "SetParentAction",
  48460. properties: [
  48461. BABYLON.Action._GetTargetProperty(this._target),
  48462. BABYLON.Action._GetTargetProperty(this._parent),
  48463. ]
  48464. }, parent);
  48465. };
  48466. return SetParentAction;
  48467. }(BABYLON.Action));
  48468. BABYLON.SetParentAction = SetParentAction;
  48469. var PlaySoundAction = /** @class */ (function (_super) {
  48470. __extends(PlaySoundAction, _super);
  48471. function PlaySoundAction(triggerOptions, sound, condition) {
  48472. var _this = _super.call(this, triggerOptions, condition) || this;
  48473. _this._sound = sound;
  48474. return _this;
  48475. }
  48476. PlaySoundAction.prototype._prepare = function () {
  48477. };
  48478. PlaySoundAction.prototype.execute = function () {
  48479. if (this._sound !== undefined)
  48480. this._sound.play();
  48481. };
  48482. PlaySoundAction.prototype.serialize = function (parent) {
  48483. return _super.prototype._serialize.call(this, {
  48484. name: "PlaySoundAction",
  48485. properties: [{ name: "sound", value: this._sound.name }]
  48486. }, parent);
  48487. };
  48488. return PlaySoundAction;
  48489. }(BABYLON.Action));
  48490. BABYLON.PlaySoundAction = PlaySoundAction;
  48491. var StopSoundAction = /** @class */ (function (_super) {
  48492. __extends(StopSoundAction, _super);
  48493. function StopSoundAction(triggerOptions, sound, condition) {
  48494. var _this = _super.call(this, triggerOptions, condition) || this;
  48495. _this._sound = sound;
  48496. return _this;
  48497. }
  48498. StopSoundAction.prototype._prepare = function () {
  48499. };
  48500. StopSoundAction.prototype.execute = function () {
  48501. if (this._sound !== undefined)
  48502. this._sound.stop();
  48503. };
  48504. StopSoundAction.prototype.serialize = function (parent) {
  48505. return _super.prototype._serialize.call(this, {
  48506. name: "StopSoundAction",
  48507. properties: [{ name: "sound", value: this._sound.name }]
  48508. }, parent);
  48509. };
  48510. return StopSoundAction;
  48511. }(BABYLON.Action));
  48512. BABYLON.StopSoundAction = StopSoundAction;
  48513. })(BABYLON || (BABYLON = {}));
  48514. //# sourceMappingURL=babylon.directActions.js.map
  48515. var BABYLON;
  48516. (function (BABYLON) {
  48517. var SpriteManager = /** @class */ (function () {
  48518. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  48519. if (epsilon === void 0) { epsilon = 0.01; }
  48520. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48521. this.name = name;
  48522. this.sprites = new Array();
  48523. this.renderingGroupId = 0;
  48524. this.layerMask = 0x0FFFFFFF;
  48525. this.fogEnabled = true;
  48526. this.isPickable = false;
  48527. /**
  48528. * An event triggered when the manager is disposed.
  48529. * @type {BABYLON.Observable}
  48530. */
  48531. this.onDisposeObservable = new BABYLON.Observable();
  48532. this._vertexBuffers = {};
  48533. this._capacity = capacity;
  48534. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  48535. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48536. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48537. if (cellSize.width && cellSize.height) {
  48538. this.cellWidth = cellSize.width;
  48539. this.cellHeight = cellSize.height;
  48540. }
  48541. else if (cellSize !== undefined) {
  48542. this.cellWidth = cellSize;
  48543. this.cellHeight = cellSize;
  48544. }
  48545. else {
  48546. return;
  48547. }
  48548. this._epsilon = epsilon;
  48549. this._scene = scene;
  48550. this._scene.spriteManagers.push(this);
  48551. var indices = [];
  48552. var index = 0;
  48553. for (var count = 0; count < capacity; count++) {
  48554. indices.push(index);
  48555. indices.push(index + 1);
  48556. indices.push(index + 2);
  48557. indices.push(index);
  48558. indices.push(index + 2);
  48559. indices.push(index + 3);
  48560. index += 4;
  48561. }
  48562. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  48563. // VBO
  48564. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  48565. this._vertexData = new Float32Array(capacity * 16 * 4);
  48566. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  48567. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  48568. var options = this._buffer.createVertexBuffer("options", 4, 4);
  48569. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  48570. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  48571. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48572. this._vertexBuffers["options"] = options;
  48573. this._vertexBuffers["cellInfo"] = cellInfo;
  48574. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48575. // Effects
  48576. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  48577. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  48578. }
  48579. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  48580. set: function (callback) {
  48581. if (this._onDisposeObserver) {
  48582. this.onDisposeObservable.remove(this._onDisposeObserver);
  48583. }
  48584. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48585. },
  48586. enumerable: true,
  48587. configurable: true
  48588. });
  48589. Object.defineProperty(SpriteManager.prototype, "texture", {
  48590. get: function () {
  48591. return this._spriteTexture;
  48592. },
  48593. set: function (value) {
  48594. this._spriteTexture = value;
  48595. },
  48596. enumerable: true,
  48597. configurable: true
  48598. });
  48599. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  48600. var arrayOffset = index * 16;
  48601. if (offsetX === 0)
  48602. offsetX = this._epsilon;
  48603. else if (offsetX === 1)
  48604. offsetX = 1 - this._epsilon;
  48605. if (offsetY === 0)
  48606. offsetY = this._epsilon;
  48607. else if (offsetY === 1)
  48608. offsetY = 1 - this._epsilon;
  48609. this._vertexData[arrayOffset] = sprite.position.x;
  48610. this._vertexData[arrayOffset + 1] = sprite.position.y;
  48611. this._vertexData[arrayOffset + 2] = sprite.position.z;
  48612. this._vertexData[arrayOffset + 3] = sprite.angle;
  48613. this._vertexData[arrayOffset + 4] = sprite.width;
  48614. this._vertexData[arrayOffset + 5] = sprite.height;
  48615. this._vertexData[arrayOffset + 6] = offsetX;
  48616. this._vertexData[arrayOffset + 7] = offsetY;
  48617. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  48618. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  48619. var offset = (sprite.cellIndex / rowSize) >> 0;
  48620. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  48621. this._vertexData[arrayOffset + 11] = offset;
  48622. // Color
  48623. this._vertexData[arrayOffset + 12] = sprite.color.r;
  48624. this._vertexData[arrayOffset + 13] = sprite.color.g;
  48625. this._vertexData[arrayOffset + 14] = sprite.color.b;
  48626. this._vertexData[arrayOffset + 15] = sprite.color.a;
  48627. };
  48628. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  48629. var count = Math.min(this._capacity, this.sprites.length);
  48630. var min = BABYLON.Vector3.Zero();
  48631. var max = BABYLON.Vector3.Zero();
  48632. var distance = Number.MAX_VALUE;
  48633. var currentSprite = null;
  48634. var cameraSpacePosition = BABYLON.Vector3.Zero();
  48635. var cameraView = camera.getViewMatrix();
  48636. for (var index = 0; index < count; index++) {
  48637. var sprite = this.sprites[index];
  48638. if (!sprite) {
  48639. continue;
  48640. }
  48641. if (predicate) {
  48642. if (!predicate(sprite)) {
  48643. continue;
  48644. }
  48645. }
  48646. else if (!sprite.isPickable) {
  48647. continue;
  48648. }
  48649. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  48650. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  48651. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  48652. if (ray.intersectsBoxMinMax(min, max)) {
  48653. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  48654. if (distance > currentDistance) {
  48655. distance = currentDistance;
  48656. currentSprite = sprite;
  48657. if (fastCheck) {
  48658. break;
  48659. }
  48660. }
  48661. }
  48662. }
  48663. if (currentSprite) {
  48664. var result = new BABYLON.PickingInfo();
  48665. result.hit = true;
  48666. result.pickedSprite = currentSprite;
  48667. result.distance = distance;
  48668. return result;
  48669. }
  48670. return null;
  48671. };
  48672. SpriteManager.prototype.render = function () {
  48673. // Check
  48674. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  48675. return;
  48676. var engine = this._scene.getEngine();
  48677. var baseSize = this._spriteTexture.getBaseSize();
  48678. // Sprites
  48679. var deltaTime = engine.getDeltaTime();
  48680. var max = Math.min(this._capacity, this.sprites.length);
  48681. var rowSize = baseSize.width / this.cellWidth;
  48682. var offset = 0;
  48683. for (var index = 0; index < max; index++) {
  48684. var sprite = this.sprites[index];
  48685. if (!sprite) {
  48686. continue;
  48687. }
  48688. sprite._animate(deltaTime);
  48689. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  48690. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  48691. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  48692. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  48693. }
  48694. this._buffer.update(this._vertexData);
  48695. // Render
  48696. var effect = this._effectBase;
  48697. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48698. effect = this._effectFog;
  48699. }
  48700. engine.enableEffect(effect);
  48701. var viewMatrix = this._scene.getViewMatrix();
  48702. effect.setTexture("diffuseSampler", this._spriteTexture);
  48703. effect.setMatrix("view", viewMatrix);
  48704. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48705. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  48706. // Fog
  48707. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48708. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  48709. effect.setColor3("vFogColor", this._scene.fogColor);
  48710. }
  48711. // VBOs
  48712. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48713. // Draw order
  48714. engine.setDepthFunctionToLessOrEqual();
  48715. effect.setBool("alphaTest", true);
  48716. engine.setColorWrite(false);
  48717. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48718. engine.setColorWrite(true);
  48719. effect.setBool("alphaTest", false);
  48720. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48721. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48722. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48723. };
  48724. SpriteManager.prototype.dispose = function () {
  48725. if (this._buffer) {
  48726. this._buffer.dispose();
  48727. this._buffer = null;
  48728. }
  48729. if (this._indexBuffer) {
  48730. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48731. this._indexBuffer = null;
  48732. }
  48733. if (this._spriteTexture) {
  48734. this._spriteTexture.dispose();
  48735. this._spriteTexture = null;
  48736. }
  48737. // Remove from scene
  48738. var index = this._scene.spriteManagers.indexOf(this);
  48739. this._scene.spriteManagers.splice(index, 1);
  48740. // Callback
  48741. this.onDisposeObservable.notifyObservers(this);
  48742. this.onDisposeObservable.clear();
  48743. };
  48744. return SpriteManager;
  48745. }());
  48746. BABYLON.SpriteManager = SpriteManager;
  48747. })(BABYLON || (BABYLON = {}));
  48748. //# sourceMappingURL=babylon.spriteManager.js.map
  48749. var BABYLON;
  48750. (function (BABYLON) {
  48751. var Sprite = /** @class */ (function () {
  48752. function Sprite(name, manager) {
  48753. this.name = name;
  48754. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48755. this.width = 1.0;
  48756. this.height = 1.0;
  48757. this.angle = 0;
  48758. this.cellIndex = 0;
  48759. this.invertU = 0;
  48760. this.invertV = 0;
  48761. this.animations = new Array();
  48762. this.isPickable = false;
  48763. this._animationStarted = false;
  48764. this._loopAnimation = false;
  48765. this._fromIndex = 0;
  48766. this._toIndex = 0;
  48767. this._delay = 0;
  48768. this._direction = 1;
  48769. this._time = 0;
  48770. this._manager = manager;
  48771. this._manager.sprites.push(this);
  48772. this.position = BABYLON.Vector3.Zero();
  48773. }
  48774. Object.defineProperty(Sprite.prototype, "size", {
  48775. get: function () {
  48776. return this.width;
  48777. },
  48778. set: function (value) {
  48779. this.width = value;
  48780. this.height = value;
  48781. },
  48782. enumerable: true,
  48783. configurable: true
  48784. });
  48785. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  48786. this._fromIndex = from;
  48787. this._toIndex = to;
  48788. this._loopAnimation = loop;
  48789. this._delay = delay;
  48790. this._animationStarted = true;
  48791. this._direction = from < to ? 1 : -1;
  48792. this.cellIndex = from;
  48793. this._time = 0;
  48794. this._onAnimationEnd = onAnimationEnd;
  48795. };
  48796. Sprite.prototype.stopAnimation = function () {
  48797. this._animationStarted = false;
  48798. };
  48799. Sprite.prototype._animate = function (deltaTime) {
  48800. if (!this._animationStarted)
  48801. return;
  48802. this._time += deltaTime;
  48803. if (this._time > this._delay) {
  48804. this._time = this._time % this._delay;
  48805. this.cellIndex += this._direction;
  48806. if (this.cellIndex > this._toIndex) {
  48807. if (this._loopAnimation) {
  48808. this.cellIndex = this._fromIndex;
  48809. }
  48810. else {
  48811. this.cellIndex = this._toIndex;
  48812. this._animationStarted = false;
  48813. if (this._onAnimationEnd) {
  48814. this._onAnimationEnd();
  48815. }
  48816. if (this.disposeWhenFinishedAnimating) {
  48817. this.dispose();
  48818. }
  48819. }
  48820. }
  48821. }
  48822. };
  48823. Sprite.prototype.dispose = function () {
  48824. for (var i = 0; i < this._manager.sprites.length; i++) {
  48825. if (this._manager.sprites[i] == this) {
  48826. this._manager.sprites.splice(i, 1);
  48827. }
  48828. }
  48829. };
  48830. return Sprite;
  48831. }());
  48832. BABYLON.Sprite = Sprite;
  48833. })(BABYLON || (BABYLON = {}));
  48834. //# sourceMappingURL=babylon.sprite.js.map
  48835. var BABYLON;
  48836. (function (BABYLON) {
  48837. var IntersectionInfo = /** @class */ (function () {
  48838. function IntersectionInfo(bu, bv, distance) {
  48839. this.bu = bu;
  48840. this.bv = bv;
  48841. this.distance = distance;
  48842. this.faceId = 0;
  48843. this.subMeshId = 0;
  48844. }
  48845. return IntersectionInfo;
  48846. }());
  48847. BABYLON.IntersectionInfo = IntersectionInfo;
  48848. var PickingInfo = /** @class */ (function () {
  48849. function PickingInfo() {
  48850. this.hit = false;
  48851. this.distance = 0;
  48852. this.pickedPoint = null;
  48853. this.pickedMesh = null;
  48854. this.bu = 0;
  48855. this.bv = 0;
  48856. this.faceId = -1;
  48857. this.subMeshId = 0;
  48858. this.pickedSprite = null;
  48859. }
  48860. // Methods
  48861. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  48862. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  48863. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  48864. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  48865. return null;
  48866. }
  48867. var indices = this.pickedMesh.getIndices();
  48868. if (!indices) {
  48869. return null;
  48870. }
  48871. var result;
  48872. if (useVerticesNormals) {
  48873. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48874. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  48875. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  48876. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  48877. normal0 = normal0.scale(this.bu);
  48878. normal1 = normal1.scale(this.bv);
  48879. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  48880. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  48881. }
  48882. else {
  48883. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48884. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  48885. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  48886. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  48887. var p1p2 = vertex1.subtract(vertex2);
  48888. var p3p2 = vertex3.subtract(vertex2);
  48889. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  48890. }
  48891. if (useWorldCoordinates) {
  48892. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  48893. }
  48894. return BABYLON.Vector3.Normalize(result);
  48895. };
  48896. PickingInfo.prototype.getTextureCoordinates = function () {
  48897. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48898. return null;
  48899. }
  48900. var indices = this.pickedMesh.getIndices();
  48901. if (!indices) {
  48902. return null;
  48903. }
  48904. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48905. if (!uvs) {
  48906. return null;
  48907. }
  48908. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  48909. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  48910. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  48911. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  48912. uv1 = uv1.scale(this.bu);
  48913. uv2 = uv2.scale(this.bv);
  48914. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  48915. };
  48916. return PickingInfo;
  48917. }());
  48918. BABYLON.PickingInfo = PickingInfo;
  48919. })(BABYLON || (BABYLON = {}));
  48920. //# sourceMappingURL=babylon.pickingInfo.js.map
  48921. var BABYLON;
  48922. (function (BABYLON) {
  48923. var Ray = /** @class */ (function () {
  48924. function Ray(origin, direction, length) {
  48925. if (length === void 0) { length = Number.MAX_VALUE; }
  48926. this.origin = origin;
  48927. this.direction = direction;
  48928. this.length = length;
  48929. }
  48930. // Methods
  48931. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  48932. var d = 0.0;
  48933. var maxValue = Number.MAX_VALUE;
  48934. var inv;
  48935. var min;
  48936. var max;
  48937. var temp;
  48938. if (Math.abs(this.direction.x) < 0.0000001) {
  48939. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  48940. return false;
  48941. }
  48942. }
  48943. else {
  48944. inv = 1.0 / this.direction.x;
  48945. min = (minimum.x - this.origin.x) * inv;
  48946. max = (maximum.x - this.origin.x) * inv;
  48947. if (max === -Infinity) {
  48948. max = Infinity;
  48949. }
  48950. if (min > max) {
  48951. temp = min;
  48952. min = max;
  48953. max = temp;
  48954. }
  48955. d = Math.max(min, d);
  48956. maxValue = Math.min(max, maxValue);
  48957. if (d > maxValue) {
  48958. return false;
  48959. }
  48960. }
  48961. if (Math.abs(this.direction.y) < 0.0000001) {
  48962. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  48963. return false;
  48964. }
  48965. }
  48966. else {
  48967. inv = 1.0 / this.direction.y;
  48968. min = (minimum.y - this.origin.y) * inv;
  48969. max = (maximum.y - this.origin.y) * inv;
  48970. if (max === -Infinity) {
  48971. max = Infinity;
  48972. }
  48973. if (min > max) {
  48974. temp = min;
  48975. min = max;
  48976. max = temp;
  48977. }
  48978. d = Math.max(min, d);
  48979. maxValue = Math.min(max, maxValue);
  48980. if (d > maxValue) {
  48981. return false;
  48982. }
  48983. }
  48984. if (Math.abs(this.direction.z) < 0.0000001) {
  48985. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  48986. return false;
  48987. }
  48988. }
  48989. else {
  48990. inv = 1.0 / this.direction.z;
  48991. min = (minimum.z - this.origin.z) * inv;
  48992. max = (maximum.z - this.origin.z) * inv;
  48993. if (max === -Infinity) {
  48994. max = Infinity;
  48995. }
  48996. if (min > max) {
  48997. temp = min;
  48998. min = max;
  48999. max = temp;
  49000. }
  49001. d = Math.max(min, d);
  49002. maxValue = Math.min(max, maxValue);
  49003. if (d > maxValue) {
  49004. return false;
  49005. }
  49006. }
  49007. return true;
  49008. };
  49009. Ray.prototype.intersectsBox = function (box) {
  49010. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49011. };
  49012. Ray.prototype.intersectsSphere = function (sphere) {
  49013. var x = sphere.center.x - this.origin.x;
  49014. var y = sphere.center.y - this.origin.y;
  49015. var z = sphere.center.z - this.origin.z;
  49016. var pyth = (x * x) + (y * y) + (z * z);
  49017. var rr = sphere.radius * sphere.radius;
  49018. if (pyth <= rr) {
  49019. return true;
  49020. }
  49021. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49022. if (dot < 0.0) {
  49023. return false;
  49024. }
  49025. var temp = pyth - (dot * dot);
  49026. return temp <= rr;
  49027. };
  49028. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49029. if (!this._edge1) {
  49030. this._edge1 = BABYLON.Vector3.Zero();
  49031. this._edge2 = BABYLON.Vector3.Zero();
  49032. this._pvec = BABYLON.Vector3.Zero();
  49033. this._tvec = BABYLON.Vector3.Zero();
  49034. this._qvec = BABYLON.Vector3.Zero();
  49035. }
  49036. vertex1.subtractToRef(vertex0, this._edge1);
  49037. vertex2.subtractToRef(vertex0, this._edge2);
  49038. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49039. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49040. if (det === 0) {
  49041. return null;
  49042. }
  49043. var invdet = 1 / det;
  49044. this.origin.subtractToRef(vertex0, this._tvec);
  49045. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49046. if (bu < 0 || bu > 1.0) {
  49047. return null;
  49048. }
  49049. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49050. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49051. if (bv < 0 || bu + bv > 1.0) {
  49052. return null;
  49053. }
  49054. //check if the distance is longer than the predefined length.
  49055. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49056. if (distance > this.length) {
  49057. return null;
  49058. }
  49059. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49060. };
  49061. Ray.prototype.intersectsPlane = function (plane) {
  49062. var distance;
  49063. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49064. if (Math.abs(result1) < 9.99999997475243E-07) {
  49065. return null;
  49066. }
  49067. else {
  49068. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49069. distance = (-plane.d - result2) / result1;
  49070. if (distance < 0.0) {
  49071. if (distance < -9.99999997475243E-07) {
  49072. return null;
  49073. }
  49074. else {
  49075. return 0;
  49076. }
  49077. }
  49078. return distance;
  49079. }
  49080. };
  49081. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49082. var tm = BABYLON.Tmp.Matrix[0];
  49083. mesh.getWorldMatrix().invertToRef(tm);
  49084. if (this._tmpRay) {
  49085. Ray.TransformToRef(this, tm, this._tmpRay);
  49086. }
  49087. else {
  49088. this._tmpRay = Ray.Transform(this, tm);
  49089. }
  49090. return mesh.intersects(this._tmpRay, fastCheck);
  49091. };
  49092. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49093. if (results) {
  49094. results.length = 0;
  49095. }
  49096. else {
  49097. results = [];
  49098. }
  49099. for (var i = 0; i < meshes.length; i++) {
  49100. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49101. if (pickInfo.hit) {
  49102. results.push(pickInfo);
  49103. }
  49104. }
  49105. results.sort(this._comparePickingInfo);
  49106. return results;
  49107. };
  49108. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49109. if (pickingInfoA.distance < pickingInfoB.distance) {
  49110. return -1;
  49111. }
  49112. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49113. return 1;
  49114. }
  49115. else {
  49116. return 0;
  49117. }
  49118. };
  49119. /**
  49120. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49121. * @param sega the first point of the segment to test the intersection against
  49122. * @param segb the second point of the segment to test the intersection against
  49123. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49124. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49125. */
  49126. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49127. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49128. var u = segb.subtract(sega);
  49129. var v = rsegb.subtract(this.origin);
  49130. var w = sega.subtract(this.origin);
  49131. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49132. var b = BABYLON.Vector3.Dot(u, v);
  49133. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49134. var d = BABYLON.Vector3.Dot(u, w);
  49135. var e = BABYLON.Vector3.Dot(v, w);
  49136. var D = a * c - b * b; // always >= 0
  49137. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49138. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49139. // compute the line parameters of the two closest points
  49140. if (D < Ray.smallnum) {
  49141. sN = 0.0; // force using point P0 on segment S1
  49142. sD = 1.0; // to prevent possible division by 0.0 later
  49143. tN = e;
  49144. tD = c;
  49145. }
  49146. else {
  49147. sN = (b * e - c * d);
  49148. tN = (a * e - b * d);
  49149. if (sN < 0.0) {
  49150. sN = 0.0;
  49151. tN = e;
  49152. tD = c;
  49153. }
  49154. else if (sN > sD) {
  49155. sN = sD;
  49156. tN = e + b;
  49157. tD = c;
  49158. }
  49159. }
  49160. if (tN < 0.0) {
  49161. tN = 0.0;
  49162. // recompute sc for this edge
  49163. if (-d < 0.0) {
  49164. sN = 0.0;
  49165. }
  49166. else if (-d > a)
  49167. sN = sD;
  49168. else {
  49169. sN = -d;
  49170. sD = a;
  49171. }
  49172. }
  49173. else if (tN > tD) {
  49174. tN = tD;
  49175. // recompute sc for this edge
  49176. if ((-d + b) < 0.0) {
  49177. sN = 0;
  49178. }
  49179. else if ((-d + b) > a) {
  49180. sN = sD;
  49181. }
  49182. else {
  49183. sN = (-d + b);
  49184. sD = a;
  49185. }
  49186. }
  49187. // finally do the division to get sc and tc
  49188. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49189. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49190. // get the difference of the two closest points
  49191. var qtc = v.multiplyByFloats(tc, tc, tc);
  49192. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49193. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49194. if (isIntersected) {
  49195. return qtc.length();
  49196. }
  49197. return -1;
  49198. };
  49199. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49200. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49201. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49202. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49203. this.direction.normalize();
  49204. return this;
  49205. };
  49206. // Statics
  49207. Ray.Zero = function () {
  49208. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49209. };
  49210. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49211. var result = Ray.Zero();
  49212. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49213. };
  49214. /**
  49215. * 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
  49216. * transformed to the given world matrix.
  49217. * @param origin The origin point
  49218. * @param end The end point
  49219. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49220. */
  49221. Ray.CreateNewFromTo = function (origin, end, world) {
  49222. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49223. var direction = end.subtract(origin);
  49224. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49225. direction.normalize();
  49226. return Ray.Transform(new Ray(origin, direction, length), world);
  49227. };
  49228. Ray.Transform = function (ray, matrix) {
  49229. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49230. Ray.TransformToRef(ray, matrix, result);
  49231. return result;
  49232. };
  49233. Ray.TransformToRef = function (ray, matrix, result) {
  49234. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49235. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49236. result.length = ray.length;
  49237. var dir = result.direction;
  49238. var len = dir.length();
  49239. if (!(len === 0 || len === 1)) {
  49240. var num = 1.0 / len;
  49241. dir.x *= num;
  49242. dir.y *= num;
  49243. dir.z *= num;
  49244. result.length *= len;
  49245. }
  49246. };
  49247. Ray.smallnum = 0.00000001;
  49248. Ray.rayl = 10e8;
  49249. return Ray;
  49250. }());
  49251. BABYLON.Ray = Ray;
  49252. })(BABYLON || (BABYLON = {}));
  49253. //# sourceMappingURL=babylon.ray.js.map
  49254. var BABYLON;
  49255. (function (BABYLON) {
  49256. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49257. if (boxMin.x > sphereCenter.x + sphereRadius)
  49258. return false;
  49259. if (sphereCenter.x - sphereRadius > boxMax.x)
  49260. return false;
  49261. if (boxMin.y > sphereCenter.y + sphereRadius)
  49262. return false;
  49263. if (sphereCenter.y - sphereRadius > boxMax.y)
  49264. return false;
  49265. if (boxMin.z > sphereCenter.z + sphereRadius)
  49266. return false;
  49267. if (sphereCenter.z - sphereRadius > boxMax.z)
  49268. return false;
  49269. return true;
  49270. };
  49271. var getLowestRoot = (function () {
  49272. var result = { root: 0, found: false };
  49273. return function (a, b, c, maxR) {
  49274. result.root = 0;
  49275. result.found = false;
  49276. var determinant = b * b - 4.0 * a * c;
  49277. if (determinant < 0)
  49278. return result;
  49279. var sqrtD = Math.sqrt(determinant);
  49280. var r1 = (-b - sqrtD) / (2.0 * a);
  49281. var r2 = (-b + sqrtD) / (2.0 * a);
  49282. if (r1 > r2) {
  49283. var temp = r2;
  49284. r2 = r1;
  49285. r1 = temp;
  49286. }
  49287. if (r1 > 0 && r1 < maxR) {
  49288. result.root = r1;
  49289. result.found = true;
  49290. return result;
  49291. }
  49292. if (r2 > 0 && r2 < maxR) {
  49293. result.root = r2;
  49294. result.found = true;
  49295. return result;
  49296. }
  49297. return result;
  49298. };
  49299. })();
  49300. var Collider = /** @class */ (function () {
  49301. function Collider() {
  49302. this._collisionPoint = BABYLON.Vector3.Zero();
  49303. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49304. this._tempVector = BABYLON.Vector3.Zero();
  49305. this._tempVector2 = BABYLON.Vector3.Zero();
  49306. this._tempVector3 = BABYLON.Vector3.Zero();
  49307. this._tempVector4 = BABYLON.Vector3.Zero();
  49308. this._edge = BABYLON.Vector3.Zero();
  49309. this._baseToVertex = BABYLON.Vector3.Zero();
  49310. this._destinationPoint = BABYLON.Vector3.Zero();
  49311. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49312. this._displacementVector = BABYLON.Vector3.Zero();
  49313. this._radius = BABYLON.Vector3.One();
  49314. this._retry = 0;
  49315. this._basePointWorld = BABYLON.Vector3.Zero();
  49316. this._velocityWorld = BABYLON.Vector3.Zero();
  49317. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49318. this._collisionMask = -1;
  49319. }
  49320. Object.defineProperty(Collider.prototype, "collisionMask", {
  49321. get: function () {
  49322. return this._collisionMask;
  49323. },
  49324. set: function (mask) {
  49325. this._collisionMask = !isNaN(mask) ? mask : -1;
  49326. },
  49327. enumerable: true,
  49328. configurable: true
  49329. });
  49330. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49331. /**
  49332. * Gets the plane normal used to compute the sliding response (in local space)
  49333. */
  49334. get: function () {
  49335. return this._slidePlaneNormal;
  49336. },
  49337. enumerable: true,
  49338. configurable: true
  49339. });
  49340. // Methods
  49341. Collider.prototype._initialize = function (source, dir, e) {
  49342. this._velocity = dir;
  49343. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49344. this._basePoint = source;
  49345. source.multiplyToRef(this._radius, this._basePointWorld);
  49346. dir.multiplyToRef(this._radius, this._velocityWorld);
  49347. this._velocityWorldLength = this._velocityWorld.length();
  49348. this._epsilon = e;
  49349. this.collisionFound = false;
  49350. };
  49351. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49352. pa.subtractToRef(point, this._tempVector);
  49353. pb.subtractToRef(point, this._tempVector2);
  49354. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49355. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49356. if (d < 0)
  49357. return false;
  49358. pc.subtractToRef(point, this._tempVector3);
  49359. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49360. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49361. if (d < 0)
  49362. return false;
  49363. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49364. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49365. return d >= 0;
  49366. };
  49367. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49368. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49369. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49370. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49371. return false;
  49372. }
  49373. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49374. return false;
  49375. return true;
  49376. };
  49377. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49378. var t0;
  49379. var embeddedInPlane = false;
  49380. //defensive programming, actually not needed.
  49381. if (!trianglePlaneArray) {
  49382. trianglePlaneArray = [];
  49383. }
  49384. if (!trianglePlaneArray[faceIndex]) {
  49385. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49386. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49387. }
  49388. var trianglePlane = trianglePlaneArray[faceIndex];
  49389. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49390. return;
  49391. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49392. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49393. if (normalDotVelocity == 0) {
  49394. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49395. return;
  49396. embeddedInPlane = true;
  49397. t0 = 0;
  49398. }
  49399. else {
  49400. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49401. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49402. if (t0 > t1) {
  49403. var temp = t1;
  49404. t1 = t0;
  49405. t0 = temp;
  49406. }
  49407. if (t0 > 1.0 || t1 < 0.0)
  49408. return;
  49409. if (t0 < 0)
  49410. t0 = 0;
  49411. if (t0 > 1.0)
  49412. t0 = 1.0;
  49413. }
  49414. this._collisionPoint.copyFromFloats(0, 0, 0);
  49415. var found = false;
  49416. var t = 1.0;
  49417. if (!embeddedInPlane) {
  49418. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49419. this._velocity.scaleToRef(t0, this._tempVector);
  49420. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49421. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49422. found = true;
  49423. t = t0;
  49424. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49425. }
  49426. }
  49427. if (!found) {
  49428. var velocitySquaredLength = this._velocity.lengthSquared();
  49429. var a = velocitySquaredLength;
  49430. this._basePoint.subtractToRef(p1, this._tempVector);
  49431. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49432. var c = this._tempVector.lengthSquared() - 1.0;
  49433. var lowestRoot = getLowestRoot(a, b, c, t);
  49434. if (lowestRoot.found) {
  49435. t = lowestRoot.root;
  49436. found = true;
  49437. this._collisionPoint.copyFrom(p1);
  49438. }
  49439. this._basePoint.subtractToRef(p2, this._tempVector);
  49440. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49441. c = this._tempVector.lengthSquared() - 1.0;
  49442. lowestRoot = getLowestRoot(a, b, c, t);
  49443. if (lowestRoot.found) {
  49444. t = lowestRoot.root;
  49445. found = true;
  49446. this._collisionPoint.copyFrom(p2);
  49447. }
  49448. this._basePoint.subtractToRef(p3, this._tempVector);
  49449. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49450. c = this._tempVector.lengthSquared() - 1.0;
  49451. lowestRoot = getLowestRoot(a, b, c, t);
  49452. if (lowestRoot.found) {
  49453. t = lowestRoot.root;
  49454. found = true;
  49455. this._collisionPoint.copyFrom(p3);
  49456. }
  49457. p2.subtractToRef(p1, this._edge);
  49458. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49459. var edgeSquaredLength = this._edge.lengthSquared();
  49460. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49461. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49462. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49463. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49464. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49465. lowestRoot = getLowestRoot(a, b, c, t);
  49466. if (lowestRoot.found) {
  49467. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49468. if (f >= 0.0 && f <= 1.0) {
  49469. t = lowestRoot.root;
  49470. found = true;
  49471. this._edge.scaleInPlace(f);
  49472. p1.addToRef(this._edge, this._collisionPoint);
  49473. }
  49474. }
  49475. p3.subtractToRef(p2, this._edge);
  49476. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49477. edgeSquaredLength = this._edge.lengthSquared();
  49478. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49479. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49480. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49481. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49482. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49483. lowestRoot = getLowestRoot(a, b, c, t);
  49484. if (lowestRoot.found) {
  49485. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49486. if (f >= 0.0 && f <= 1.0) {
  49487. t = lowestRoot.root;
  49488. found = true;
  49489. this._edge.scaleInPlace(f);
  49490. p2.addToRef(this._edge, this._collisionPoint);
  49491. }
  49492. }
  49493. p1.subtractToRef(p3, this._edge);
  49494. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49495. edgeSquaredLength = this._edge.lengthSquared();
  49496. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49497. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49498. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49499. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49500. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49501. lowestRoot = getLowestRoot(a, b, c, t);
  49502. if (lowestRoot.found) {
  49503. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49504. if (f >= 0.0 && f <= 1.0) {
  49505. t = lowestRoot.root;
  49506. found = true;
  49507. this._edge.scaleInPlace(f);
  49508. p3.addToRef(this._edge, this._collisionPoint);
  49509. }
  49510. }
  49511. }
  49512. if (found) {
  49513. var distToCollision = t * this._velocity.length();
  49514. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49515. if (!this.intersectionPoint) {
  49516. this.intersectionPoint = this._collisionPoint.clone();
  49517. }
  49518. else {
  49519. this.intersectionPoint.copyFrom(this._collisionPoint);
  49520. }
  49521. this._nearestDistance = distToCollision;
  49522. this.collisionFound = true;
  49523. }
  49524. }
  49525. };
  49526. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  49527. for (var i = indexStart; i < indexEnd; i += 3) {
  49528. var p1 = pts[indices[i] - decal];
  49529. var p2 = pts[indices[i + 1] - decal];
  49530. var p3 = pts[indices[i + 2] - decal];
  49531. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  49532. }
  49533. };
  49534. Collider.prototype._getResponse = function (pos, vel) {
  49535. pos.addToRef(vel, this._destinationPoint);
  49536. vel.scaleInPlace((this._nearestDistance / vel.length()));
  49537. this._basePoint.addToRef(vel, pos);
  49538. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  49539. this._slidePlaneNormal.normalize();
  49540. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  49541. pos.addInPlace(this._displacementVector);
  49542. this.intersectionPoint.addInPlace(this._displacementVector);
  49543. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  49544. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  49545. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  49546. };
  49547. return Collider;
  49548. }());
  49549. BABYLON.Collider = Collider;
  49550. })(BABYLON || (BABYLON = {}));
  49551. //# sourceMappingURL=babylon.collider.js.map
  49552. var BABYLON;
  49553. (function (BABYLON) {
  49554. //WebWorker code will be inserted to this variable.
  49555. BABYLON.CollisionWorker = "";
  49556. var WorkerTaskType;
  49557. (function (WorkerTaskType) {
  49558. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  49559. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  49560. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  49561. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  49562. var WorkerReplyType;
  49563. (function (WorkerReplyType) {
  49564. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  49565. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  49566. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  49567. var CollisionCoordinatorWorker = /** @class */ (function () {
  49568. function CollisionCoordinatorWorker() {
  49569. var _this = this;
  49570. this._scaledPosition = BABYLON.Vector3.Zero();
  49571. this._scaledVelocity = BABYLON.Vector3.Zero();
  49572. this.onMeshUpdated = function (transformNode) {
  49573. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  49574. };
  49575. this.onGeometryUpdated = function (geometry) {
  49576. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  49577. };
  49578. this._afterRender = function () {
  49579. if (!_this._init)
  49580. return;
  49581. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  49582. return;
  49583. }
  49584. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  49585. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  49586. if (_this._runningUpdated > 4) {
  49587. return;
  49588. }
  49589. ++_this._runningUpdated;
  49590. var payload = {
  49591. updatedMeshes: _this._addUpdateMeshesList,
  49592. updatedGeometries: _this._addUpdateGeometriesList,
  49593. removedGeometries: _this._toRemoveGeometryArray,
  49594. removedMeshes: _this._toRemoveMeshesArray
  49595. };
  49596. var message = {
  49597. payload: payload,
  49598. taskType: WorkerTaskType.UPDATE
  49599. };
  49600. var serializable = [];
  49601. for (var id in payload.updatedGeometries) {
  49602. if (payload.updatedGeometries.hasOwnProperty(id)) {
  49603. //prepare transferables
  49604. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  49605. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  49606. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  49607. }
  49608. }
  49609. _this._worker.postMessage(message, serializable);
  49610. _this._addUpdateMeshesList = {};
  49611. _this._addUpdateGeometriesList = {};
  49612. _this._toRemoveGeometryArray = [];
  49613. _this._toRemoveMeshesArray = [];
  49614. };
  49615. this._onMessageFromWorker = function (e) {
  49616. var returnData = e.data;
  49617. if (returnData.error != WorkerReplyType.SUCCESS) {
  49618. //TODO what errors can be returned from the worker?
  49619. BABYLON.Tools.Warn("error returned from worker!");
  49620. return;
  49621. }
  49622. switch (returnData.taskType) {
  49623. case WorkerTaskType.INIT:
  49624. _this._init = true;
  49625. //Update the worked with ALL of the scene's current state
  49626. _this._scene.meshes.forEach(function (mesh) {
  49627. _this.onMeshAdded(mesh);
  49628. });
  49629. _this._scene.getGeometries().forEach(function (geometry) {
  49630. _this.onGeometryAdded(geometry);
  49631. });
  49632. break;
  49633. case WorkerTaskType.UPDATE:
  49634. _this._runningUpdated--;
  49635. break;
  49636. case WorkerTaskType.COLLIDE:
  49637. var returnPayload = returnData.payload;
  49638. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  49639. return;
  49640. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  49641. if (callback) {
  49642. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  49643. if (mesh) {
  49644. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  49645. }
  49646. }
  49647. //cleanup
  49648. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  49649. break;
  49650. }
  49651. };
  49652. this._collisionsCallbackArray = [];
  49653. this._init = false;
  49654. this._runningUpdated = 0;
  49655. this._addUpdateMeshesList = {};
  49656. this._addUpdateGeometriesList = {};
  49657. this._toRemoveGeometryArray = [];
  49658. this._toRemoveMeshesArray = [];
  49659. }
  49660. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49661. if (!this._init)
  49662. return;
  49663. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  49664. return;
  49665. position.divideToRef(collider._radius, this._scaledPosition);
  49666. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49667. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  49668. var payload = {
  49669. collider: {
  49670. position: this._scaledPosition.asArray(),
  49671. velocity: this._scaledVelocity.asArray(),
  49672. radius: collider._radius.asArray()
  49673. },
  49674. collisionId: collisionIndex,
  49675. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  49676. maximumRetry: maximumRetry
  49677. };
  49678. var message = {
  49679. payload: payload,
  49680. taskType: WorkerTaskType.COLLIDE
  49681. };
  49682. this._worker.postMessage(message);
  49683. };
  49684. CollisionCoordinatorWorker.prototype.init = function (scene) {
  49685. this._scene = scene;
  49686. this._scene.registerAfterRender(this._afterRender);
  49687. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  49688. this._worker = new Worker(workerUrl);
  49689. this._worker.onmessage = this._onMessageFromWorker;
  49690. var message = {
  49691. payload: {},
  49692. taskType: WorkerTaskType.INIT
  49693. };
  49694. this._worker.postMessage(message);
  49695. };
  49696. CollisionCoordinatorWorker.prototype.destroy = function () {
  49697. this._scene.unregisterAfterRender(this._afterRender);
  49698. this._worker.terminate();
  49699. };
  49700. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  49701. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  49702. this.onMeshUpdated(mesh);
  49703. };
  49704. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  49705. this._toRemoveMeshesArray.push(mesh.uniqueId);
  49706. };
  49707. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  49708. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  49709. geometry.onGeometryUpdated = this.onGeometryUpdated;
  49710. this.onGeometryUpdated(geometry);
  49711. };
  49712. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  49713. this._toRemoveGeometryArray.push(geometry.id);
  49714. };
  49715. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  49716. var submeshes = [];
  49717. if (mesh.subMeshes) {
  49718. submeshes = mesh.subMeshes.map(function (sm, idx) {
  49719. var boundingInfo = sm.getBoundingInfo();
  49720. return {
  49721. position: idx,
  49722. verticesStart: sm.verticesStart,
  49723. verticesCount: sm.verticesCount,
  49724. indexStart: sm.indexStart,
  49725. indexCount: sm.indexCount,
  49726. hasMaterial: !!sm.getMaterial(),
  49727. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49728. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49729. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49730. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  49731. };
  49732. });
  49733. }
  49734. var geometryId = null;
  49735. if (mesh instanceof BABYLON.Mesh) {
  49736. var geometry = mesh.geometry;
  49737. geometryId = geometry ? geometry.id : null;
  49738. }
  49739. else if (mesh instanceof BABYLON.InstancedMesh) {
  49740. var geometry = mesh.sourceMesh.geometry;
  49741. geometryId = geometry ? geometry.id : null;
  49742. }
  49743. var boundingInfo = mesh.getBoundingInfo();
  49744. return {
  49745. uniqueId: mesh.uniqueId,
  49746. id: mesh.id,
  49747. name: mesh.name,
  49748. geometryId: geometryId,
  49749. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49750. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49751. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49752. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  49753. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  49754. subMeshes: submeshes,
  49755. checkCollisions: mesh.checkCollisions
  49756. };
  49757. };
  49758. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  49759. return {
  49760. id: geometry.id,
  49761. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  49762. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  49763. indices: new Uint32Array(geometry.getIndices() || []),
  49764. };
  49765. };
  49766. return CollisionCoordinatorWorker;
  49767. }());
  49768. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  49769. var CollisionCoordinatorLegacy = /** @class */ (function () {
  49770. function CollisionCoordinatorLegacy() {
  49771. this._scaledPosition = BABYLON.Vector3.Zero();
  49772. this._scaledVelocity = BABYLON.Vector3.Zero();
  49773. this._finalPosition = BABYLON.Vector3.Zero();
  49774. }
  49775. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49776. position.divideToRef(collider._radius, this._scaledPosition);
  49777. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49778. collider.collidedMesh = null;
  49779. collider._retry = 0;
  49780. collider._initialVelocity = this._scaledVelocity;
  49781. collider._initialPosition = this._scaledPosition;
  49782. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  49783. this._finalPosition.multiplyInPlace(collider._radius);
  49784. //run the callback
  49785. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  49786. };
  49787. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  49788. this._scene = scene;
  49789. };
  49790. CollisionCoordinatorLegacy.prototype.destroy = function () {
  49791. //Legacy need no destruction method.
  49792. };
  49793. //No update in legacy mode
  49794. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  49795. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  49796. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  49797. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  49798. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  49799. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  49800. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  49801. if (excludedMesh === void 0) { excludedMesh = null; }
  49802. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  49803. if (collider._retry >= maximumRetry) {
  49804. finalPosition.copyFrom(position);
  49805. return;
  49806. }
  49807. // Check if this is a mesh else camera or -1
  49808. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  49809. collider._initialize(position, velocity, closeDistance);
  49810. // Check all meshes
  49811. for (var index = 0; index < this._scene.meshes.length; index++) {
  49812. var mesh = this._scene.meshes[index];
  49813. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  49814. mesh._checkCollision(collider);
  49815. }
  49816. }
  49817. if (!collider.collisionFound) {
  49818. position.addToRef(velocity, finalPosition);
  49819. return;
  49820. }
  49821. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  49822. collider._getResponse(position, velocity);
  49823. }
  49824. if (velocity.length() <= closeDistance) {
  49825. finalPosition.copyFrom(position);
  49826. return;
  49827. }
  49828. collider._retry++;
  49829. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  49830. };
  49831. return CollisionCoordinatorLegacy;
  49832. }());
  49833. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  49834. })(BABYLON || (BABYLON = {}));
  49835. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  49836. var BABYLON;
  49837. (function (BABYLON) {
  49838. /**
  49839. * A particle represents one of the element emitted by a particle system.
  49840. * This is mainly define by its coordinates, direction, velocity and age.
  49841. */
  49842. var Particle = /** @class */ (function () {
  49843. /**
  49844. * Creates a new instance of @see Particle
  49845. * @param particleSystem the particle system the particle belongs to
  49846. */
  49847. function Particle(particleSystem) {
  49848. this.particleSystem = particleSystem;
  49849. /**
  49850. * The world position of the particle in the scene.
  49851. */
  49852. this.position = BABYLON.Vector3.Zero();
  49853. /**
  49854. * The world direction of the particle in the scene.
  49855. */
  49856. this.direction = BABYLON.Vector3.Zero();
  49857. /**
  49858. * The color of the particle.
  49859. */
  49860. this.color = new BABYLON.Color4(0, 0, 0, 0);
  49861. /**
  49862. * The color change of the particle per step.
  49863. */
  49864. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  49865. /**
  49866. * Defines how long will the life of the particle be.
  49867. */
  49868. this.lifeTime = 1.0;
  49869. /**
  49870. * The current age of the particle.
  49871. */
  49872. this.age = 0;
  49873. /**
  49874. * The current size of the particle.
  49875. */
  49876. this.size = 0;
  49877. /**
  49878. * The current angle of the particle.
  49879. */
  49880. this.angle = 0;
  49881. /**
  49882. * Defines how fast is the angle changing.
  49883. */
  49884. this.angularSpeed = 0;
  49885. /**
  49886. * Defines the cell index used by the particle to be rendered from a sprite.
  49887. */
  49888. this.cellIndex = 0;
  49889. this._currentFrameCounter = 0;
  49890. if (!this.particleSystem.isAnimationSheetEnabled) {
  49891. return;
  49892. }
  49893. this.cellIndex = this.particleSystem.startSpriteCellID;
  49894. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  49895. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  49896. }
  49897. else {
  49898. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  49899. }
  49900. }
  49901. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  49902. // (ageOffset / scaledUpdateSpeed) / available cells
  49903. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  49904. this._currentFrameCounter += scaledUpdateSpeed;
  49905. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  49906. this._currentFrameCounter = 0;
  49907. this.cellIndex++;
  49908. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49909. this.cellIndex = this.particleSystem.endSpriteCellID;
  49910. }
  49911. }
  49912. };
  49913. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  49914. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  49915. this.cellIndex++;
  49916. this._currentFrameCounter = 0;
  49917. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49918. if (this.particleSystem.spriteCellLoop) {
  49919. this.cellIndex = this.particleSystem.startSpriteCellID;
  49920. }
  49921. else {
  49922. this.cellIndex = this.particleSystem.endSpriteCellID;
  49923. }
  49924. }
  49925. }
  49926. else {
  49927. this._currentFrameCounter++;
  49928. }
  49929. };
  49930. /**
  49931. * Copy the properties of particle to another one.
  49932. * @param other the particle to copy the information to.
  49933. */
  49934. Particle.prototype.copyTo = function (other) {
  49935. other.position.copyFrom(this.position);
  49936. other.direction.copyFrom(this.direction);
  49937. other.color.copyFrom(this.color);
  49938. other.colorStep.copyFrom(this.colorStep);
  49939. other.lifeTime = this.lifeTime;
  49940. other.age = this.age;
  49941. other.size = this.size;
  49942. other.angle = this.angle;
  49943. other.angularSpeed = this.angularSpeed;
  49944. other.particleSystem = this.particleSystem;
  49945. other.cellIndex = this.cellIndex;
  49946. };
  49947. return Particle;
  49948. }());
  49949. BABYLON.Particle = Particle;
  49950. })(BABYLON || (BABYLON = {}));
  49951. //# sourceMappingURL=babylon.particle.js.map
  49952. var BABYLON;
  49953. (function (BABYLON) {
  49954. /**
  49955. * This represents a particle system in Babylon.
  49956. * 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.
  49957. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  49958. * @example https://doc.babylonjs.com/babylon101/particles
  49959. */
  49960. var ParticleSystem = /** @class */ (function () {
  49961. /**
  49962. * Instantiates a particle system.
  49963. * 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.
  49964. * @param name The name of the particle system
  49965. * @param capacity The max number of particles alive at the same time
  49966. * @param scene The scene the particle system belongs to
  49967. * @param customEffect a custom effect used to change the way particles are rendered by default
  49968. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  49969. * @param epsilon Offset used to render the particles
  49970. */
  49971. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  49972. if (customEffect === void 0) { customEffect = null; }
  49973. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  49974. if (epsilon === void 0) { epsilon = 0.01; }
  49975. var _this = this;
  49976. /**
  49977. * List of animations used by the particle system.
  49978. */
  49979. this.animations = [];
  49980. /**
  49981. * The rendering group used by the Particle system to chose when to render.
  49982. */
  49983. this.renderingGroupId = 0;
  49984. /**
  49985. * The emitter represents the Mesh or position we are attaching the particle system to.
  49986. */
  49987. this.emitter = null;
  49988. /**
  49989. * The density of particles, the rate of particle flow
  49990. */
  49991. this.emitRate = 10;
  49992. /**
  49993. * If you want to launch only a few particles at once, that can be done, as well.
  49994. */
  49995. this.manualEmitCount = -1;
  49996. /**
  49997. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  49998. */
  49999. this.updateSpeed = 0.01;
  50000. /**
  50001. * The amount of time the particle system is running (depends of the overall speed above).
  50002. */
  50003. this.targetStopDuration = 0;
  50004. /**
  50005. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50006. */
  50007. this.disposeOnStop = false;
  50008. /**
  50009. * Minimum power of emitting particles.
  50010. */
  50011. this.minEmitPower = 1;
  50012. /**
  50013. * Maximum power of emitting particles.
  50014. */
  50015. this.maxEmitPower = 1;
  50016. /**
  50017. * Minimum life time of emitting particles.
  50018. */
  50019. this.minLifeTime = 1;
  50020. /**
  50021. * Maximum life time of emitting particles.
  50022. */
  50023. this.maxLifeTime = 1;
  50024. /**
  50025. * Minimum Size of emitting particles.
  50026. */
  50027. this.minSize = 1;
  50028. /**
  50029. * Maximum Size of emitting particles.
  50030. */
  50031. this.maxSize = 1;
  50032. /**
  50033. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50034. */
  50035. this.minAngularSpeed = 0;
  50036. /**
  50037. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50038. */
  50039. this.maxAngularSpeed = 0;
  50040. /**
  50041. * The layer mask we are rendering the particles through.
  50042. */
  50043. this.layerMask = 0x0FFFFFFF;
  50044. /**
  50045. * This can help using your own shader to render the particle system.
  50046. * The according effect will be created
  50047. */
  50048. this.customShader = null;
  50049. /**
  50050. * By default particle system starts as soon as they are created. This prevents the
  50051. * automatic start to happen and let you decide when to start emitting particles.
  50052. */
  50053. this.preventAutoStart = false;
  50054. /**
  50055. * Callback triggered when the particle animation is ending.
  50056. */
  50057. this.onAnimationEnd = null;
  50058. /**
  50059. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50060. */
  50061. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50062. /**
  50063. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50064. * to override the particles.
  50065. */
  50066. this.forceDepthWrite = false;
  50067. /**
  50068. * You can use gravity if you want to give an orientation to your particles.
  50069. */
  50070. this.gravity = BABYLON.Vector3.Zero();
  50071. /**
  50072. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50073. */
  50074. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  50075. /**
  50076. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50077. */
  50078. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  50079. /**
  50080. * 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.
  50081. */
  50082. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  50083. /**
  50084. * 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.
  50085. */
  50086. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  50087. /**
  50088. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50089. */
  50090. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50091. /**
  50092. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50093. */
  50094. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50095. /**
  50096. * Color the particle will have at the end of its lifetime.
  50097. */
  50098. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50099. /**
  50100. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50101. */
  50102. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50103. /**
  50104. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50105. */
  50106. this.spriteCellLoop = true;
  50107. /**
  50108. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50109. */
  50110. this.spriteCellChangeSpeed = 0;
  50111. /**
  50112. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50113. */
  50114. this.startSpriteCellID = 0;
  50115. /**
  50116. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50117. */
  50118. this.endSpriteCellID = 0;
  50119. /**
  50120. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50121. */
  50122. this.spriteCellWidth = 0;
  50123. /**
  50124. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50125. */
  50126. this.spriteCellHeight = 0;
  50127. /**
  50128. * An event triggered when the system is disposed.
  50129. */
  50130. this.onDisposeObservable = new BABYLON.Observable();
  50131. this._particles = new Array();
  50132. this._stockParticles = new Array();
  50133. this._newPartsExcess = 0;
  50134. this._vertexBuffers = {};
  50135. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50136. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50137. this._scaledDirection = BABYLON.Vector3.Zero();
  50138. this._scaledGravity = BABYLON.Vector3.Zero();
  50139. this._currentRenderId = -1;
  50140. this._started = false;
  50141. this._stopped = false;
  50142. this._actualFrame = 0;
  50143. this._vertexBufferSize = 11;
  50144. this._appendParticleVertexes = null;
  50145. this.id = name;
  50146. this.name = name;
  50147. this._capacity = capacity;
  50148. this._epsilon = epsilon;
  50149. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50150. if (isAnimationSheetEnabled) {
  50151. this._vertexBufferSize = 12;
  50152. }
  50153. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50154. this._customEffect = customEffect;
  50155. scene.particleSystems.push(this);
  50156. this._createIndexBuffer();
  50157. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50158. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50159. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50160. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50161. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50162. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50163. if (this._isAnimationSheetEnabled) {
  50164. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50165. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50166. }
  50167. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50168. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50169. this._vertexBuffers["options"] = options;
  50170. // Default behaviors
  50171. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  50172. this.updateFunction = function (particles) {
  50173. for (var index = 0; index < particles.length; index++) {
  50174. var particle = particles[index];
  50175. particle.age += _this._scaledUpdateSpeed;
  50176. if (particle.age >= particle.lifeTime) {
  50177. _this.recycleParticle(particle);
  50178. index--;
  50179. continue;
  50180. }
  50181. else {
  50182. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50183. particle.color.addInPlace(_this._scaledColorStep);
  50184. if (particle.color.a < 0)
  50185. particle.color.a = 0;
  50186. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50187. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50188. particle.position.addInPlace(_this._scaledDirection);
  50189. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50190. particle.direction.addInPlace(_this._scaledGravity);
  50191. if (_this._isAnimationSheetEnabled) {
  50192. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50193. }
  50194. }
  50195. }
  50196. };
  50197. }
  50198. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50199. /**
  50200. * Sets a callback that will be triggered when the system is disposed.
  50201. */
  50202. set: function (callback) {
  50203. if (this._onDisposeObserver) {
  50204. this.onDisposeObservable.remove(this._onDisposeObserver);
  50205. }
  50206. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50207. },
  50208. enumerable: true,
  50209. configurable: true
  50210. });
  50211. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50212. /**
  50213. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50214. */
  50215. get: function () {
  50216. return this._isAnimationSheetEnabled;
  50217. },
  50218. enumerable: true,
  50219. configurable: true
  50220. });
  50221. ParticleSystem.prototype._createIndexBuffer = function () {
  50222. var indices = [];
  50223. var index = 0;
  50224. for (var count = 0; count < this._capacity; count++) {
  50225. indices.push(index);
  50226. indices.push(index + 1);
  50227. indices.push(index + 2);
  50228. indices.push(index);
  50229. indices.push(index + 2);
  50230. indices.push(index + 3);
  50231. index += 4;
  50232. }
  50233. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50234. };
  50235. /**
  50236. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50237. * Its lifetime will start back at 0.
  50238. * @param particle The particle to recycle
  50239. */
  50240. ParticleSystem.prototype.recycleParticle = function (particle) {
  50241. var lastParticle = this._particles.pop();
  50242. if (lastParticle !== particle) {
  50243. lastParticle.copyTo(particle);
  50244. this._stockParticles.push(lastParticle);
  50245. }
  50246. };
  50247. /**
  50248. * Gets the maximum number of particles active at the same time.
  50249. * @returns The max number of active particles.
  50250. */
  50251. ParticleSystem.prototype.getCapacity = function () {
  50252. return this._capacity;
  50253. };
  50254. /**
  50255. * Gets Wether there are still active particles in the system.
  50256. * @returns True if it is alive, otherwise false.
  50257. */
  50258. ParticleSystem.prototype.isAlive = function () {
  50259. return this._alive;
  50260. };
  50261. /**
  50262. * Gets Wether the system has been started.
  50263. * @returns True if it has been started, otherwise false.
  50264. */
  50265. ParticleSystem.prototype.isStarted = function () {
  50266. return this._started;
  50267. };
  50268. /**
  50269. * Starts the particle system and begins to emit.
  50270. */
  50271. ParticleSystem.prototype.start = function () {
  50272. this._started = true;
  50273. this._stopped = false;
  50274. this._actualFrame = 0;
  50275. };
  50276. /**
  50277. * Stops the particle system.
  50278. */
  50279. ParticleSystem.prototype.stop = function () {
  50280. this._stopped = true;
  50281. };
  50282. /**
  50283. * Remove all active particles
  50284. */
  50285. ParticleSystem.prototype.reset = function () {
  50286. this._stockParticles = [];
  50287. this._particles = [];
  50288. };
  50289. /**
  50290. * @ignore (for internal use only)
  50291. */
  50292. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50293. var offset = index * this._vertexBufferSize;
  50294. this._vertexData[offset] = particle.position.x;
  50295. this._vertexData[offset + 1] = particle.position.y;
  50296. this._vertexData[offset + 2] = particle.position.z;
  50297. this._vertexData[offset + 3] = particle.color.r;
  50298. this._vertexData[offset + 4] = particle.color.g;
  50299. this._vertexData[offset + 5] = particle.color.b;
  50300. this._vertexData[offset + 6] = particle.color.a;
  50301. this._vertexData[offset + 7] = particle.angle;
  50302. this._vertexData[offset + 8] = particle.size;
  50303. this._vertexData[offset + 9] = offsetX;
  50304. this._vertexData[offset + 10] = offsetY;
  50305. };
  50306. /**
  50307. * @ignore (for internal use only)
  50308. */
  50309. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50310. if (offsetX === 0)
  50311. offsetX = this._epsilon;
  50312. else if (offsetX === 1)
  50313. offsetX = 1 - this._epsilon;
  50314. if (offsetY === 0)
  50315. offsetY = this._epsilon;
  50316. else if (offsetY === 1)
  50317. offsetY = 1 - this._epsilon;
  50318. var offset = index * this._vertexBufferSize;
  50319. this._vertexData[offset] = particle.position.x;
  50320. this._vertexData[offset + 1] = particle.position.y;
  50321. this._vertexData[offset + 2] = particle.position.z;
  50322. this._vertexData[offset + 3] = particle.color.r;
  50323. this._vertexData[offset + 4] = particle.color.g;
  50324. this._vertexData[offset + 5] = particle.color.b;
  50325. this._vertexData[offset + 6] = particle.color.a;
  50326. this._vertexData[offset + 7] = particle.angle;
  50327. this._vertexData[offset + 8] = particle.size;
  50328. this._vertexData[offset + 9] = offsetX;
  50329. this._vertexData[offset + 10] = offsetY;
  50330. this._vertexData[offset + 11] = particle.cellIndex;
  50331. };
  50332. ParticleSystem.prototype._update = function (newParticles) {
  50333. // Update current
  50334. this._alive = this._particles.length > 0;
  50335. this.updateFunction(this._particles);
  50336. // Add new ones
  50337. var worldMatrix;
  50338. if (this.emitter.position) {
  50339. var emitterMesh = this.emitter;
  50340. worldMatrix = emitterMesh.getWorldMatrix();
  50341. }
  50342. else {
  50343. var emitterPosition = this.emitter;
  50344. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50345. }
  50346. var particle;
  50347. for (var index = 0; index < newParticles; index++) {
  50348. if (this._particles.length === this._capacity) {
  50349. break;
  50350. }
  50351. if (this._stockParticles.length !== 0) {
  50352. particle = this._stockParticles.pop();
  50353. particle.age = 0;
  50354. particle.cellIndex = this.startSpriteCellID;
  50355. }
  50356. else {
  50357. particle = new BABYLON.Particle(this);
  50358. }
  50359. this._particles.push(particle);
  50360. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50361. if (this.startPositionFunction) {
  50362. this.startPositionFunction(worldMatrix, particle.position, particle);
  50363. }
  50364. else {
  50365. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50366. }
  50367. if (this.startDirectionFunction) {
  50368. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50369. }
  50370. else {
  50371. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50372. }
  50373. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50374. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50375. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50376. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50377. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50378. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50379. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50380. }
  50381. };
  50382. ParticleSystem.prototype._getEffect = function () {
  50383. if (this._customEffect) {
  50384. return this._customEffect;
  50385. }
  50386. ;
  50387. var defines = [];
  50388. if (this._scene.clipPlane) {
  50389. defines.push("#define CLIPPLANE");
  50390. }
  50391. if (this._isAnimationSheetEnabled) {
  50392. defines.push("#define ANIMATESHEET");
  50393. }
  50394. // Effect
  50395. var join = defines.join("\n");
  50396. if (this._cachedDefines !== join) {
  50397. this._cachedDefines = join;
  50398. var attributesNamesOrOptions;
  50399. var effectCreationOption;
  50400. if (this._isAnimationSheetEnabled) {
  50401. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50402. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50403. }
  50404. else {
  50405. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50406. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50407. }
  50408. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50409. }
  50410. return this._effect;
  50411. };
  50412. /**
  50413. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50414. */
  50415. ParticleSystem.prototype.animate = function () {
  50416. if (!this._started)
  50417. return;
  50418. var effect = this._getEffect();
  50419. // Check
  50420. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50421. return;
  50422. if (this._currentRenderId === this._scene.getRenderId()) {
  50423. return;
  50424. }
  50425. this._currentRenderId = this._scene.getRenderId();
  50426. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50427. // determine the number of particles we need to create
  50428. var newParticles;
  50429. if (this.manualEmitCount > -1) {
  50430. newParticles = this.manualEmitCount;
  50431. this._newPartsExcess = 0;
  50432. this.manualEmitCount = 0;
  50433. }
  50434. else {
  50435. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50436. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50437. }
  50438. if (this._newPartsExcess > 1.0) {
  50439. newParticles += this._newPartsExcess >> 0;
  50440. this._newPartsExcess -= this._newPartsExcess >> 0;
  50441. }
  50442. this._alive = false;
  50443. if (!this._stopped) {
  50444. this._actualFrame += this._scaledUpdateSpeed;
  50445. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  50446. this.stop();
  50447. }
  50448. else {
  50449. newParticles = 0;
  50450. }
  50451. this._update(newParticles);
  50452. // Stopped?
  50453. if (this._stopped) {
  50454. if (!this._alive) {
  50455. this._started = false;
  50456. if (this.onAnimationEnd) {
  50457. this.onAnimationEnd();
  50458. }
  50459. if (this.disposeOnStop) {
  50460. this._scene._toBeDisposed.push(this);
  50461. }
  50462. }
  50463. }
  50464. // Animation sheet
  50465. if (this._isAnimationSheetEnabled) {
  50466. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  50467. }
  50468. else {
  50469. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  50470. }
  50471. // Update VBO
  50472. var offset = 0;
  50473. for (var index = 0; index < this._particles.length; index++) {
  50474. var particle = this._particles[index];
  50475. this._appendParticleVertexes(offset, particle);
  50476. offset += 4;
  50477. }
  50478. if (this._vertexBuffer) {
  50479. this._vertexBuffer.update(this._vertexData);
  50480. }
  50481. };
  50482. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  50483. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  50484. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  50485. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  50486. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  50487. };
  50488. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  50489. this._appendParticleVertex(offset++, particle, 0, 0);
  50490. this._appendParticleVertex(offset++, particle, 1, 0);
  50491. this._appendParticleVertex(offset++, particle, 1, 1);
  50492. this._appendParticleVertex(offset++, particle, 0, 1);
  50493. };
  50494. /**
  50495. * Rebuilds the particle system.
  50496. */
  50497. ParticleSystem.prototype.rebuild = function () {
  50498. this._createIndexBuffer();
  50499. if (this._vertexBuffer) {
  50500. this._vertexBuffer._rebuild();
  50501. }
  50502. };
  50503. /**
  50504. * Renders the particle system in its current state.
  50505. * @returns the current number of particles.
  50506. */
  50507. ParticleSystem.prototype.render = function () {
  50508. var effect = this._getEffect();
  50509. // Check
  50510. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  50511. return 0;
  50512. var engine = this._scene.getEngine();
  50513. // Render
  50514. engine.enableEffect(effect);
  50515. engine.setState(false);
  50516. var viewMatrix = this._scene.getViewMatrix();
  50517. effect.setTexture("diffuseSampler", this.particleTexture);
  50518. effect.setMatrix("view", viewMatrix);
  50519. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50520. if (this._isAnimationSheetEnabled) {
  50521. var baseSize = this.particleTexture.getBaseSize();
  50522. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  50523. }
  50524. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  50525. if (this._scene.clipPlane) {
  50526. var clipPlane = this._scene.clipPlane;
  50527. var invView = viewMatrix.clone();
  50528. invView.invert();
  50529. effect.setMatrix("invView", invView);
  50530. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  50531. }
  50532. // VBOs
  50533. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50534. // Draw order
  50535. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  50536. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  50537. }
  50538. else {
  50539. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50540. }
  50541. if (this.forceDepthWrite) {
  50542. engine.setDepthWrite(true);
  50543. }
  50544. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  50545. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50546. return this._particles.length;
  50547. };
  50548. /**
  50549. * Disposes the particle system and free the associated resources.
  50550. */
  50551. ParticleSystem.prototype.dispose = function () {
  50552. if (this._vertexBuffer) {
  50553. this._vertexBuffer.dispose();
  50554. this._vertexBuffer = null;
  50555. }
  50556. if (this._indexBuffer) {
  50557. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50558. this._indexBuffer = null;
  50559. }
  50560. if (this.particleTexture) {
  50561. this.particleTexture.dispose();
  50562. this.particleTexture = null;
  50563. }
  50564. // Remove from scene
  50565. var index = this._scene.particleSystems.indexOf(this);
  50566. if (index > -1) {
  50567. this._scene.particleSystems.splice(index, 1);
  50568. }
  50569. // Callback
  50570. this.onDisposeObservable.notifyObservers(this);
  50571. this.onDisposeObservable.clear();
  50572. };
  50573. /**
  50574. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  50575. * @param radius The radius of the sphere to emit from
  50576. * @returns the emitter
  50577. */
  50578. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  50579. if (radius === void 0) { radius = 1; }
  50580. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  50581. this.particleEmitterType = particleEmitter;
  50582. return particleEmitter;
  50583. };
  50584. /**
  50585. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  50586. * @param radius The radius of the sphere to emit from
  50587. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  50588. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  50589. * @returns the emitter
  50590. */
  50591. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  50592. if (radius === void 0) { radius = 1; }
  50593. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  50594. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  50595. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  50596. this.particleEmitterType = particleEmitter;
  50597. return particleEmitter;
  50598. };
  50599. /**
  50600. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  50601. * @param radius The radius of the cone to emit from
  50602. * @param angle The base angle of the cone
  50603. * @returns the emitter
  50604. */
  50605. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  50606. if (radius === void 0) { radius = 1; }
  50607. if (angle === void 0) { angle = Math.PI / 4; }
  50608. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  50609. this.particleEmitterType = particleEmitter;
  50610. return particleEmitter;
  50611. };
  50612. // 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.
  50613. /**
  50614. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  50615. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  50616. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  50617. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50618. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50619. * @returns the emitter
  50620. */
  50621. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  50622. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  50623. this.direction1 = direction1;
  50624. this.direction2 = direction2;
  50625. this.minEmitBox = minEmitBox;
  50626. this.maxEmitBox = maxEmitBox;
  50627. this.particleEmitterType = particleEmitter;
  50628. return particleEmitter;
  50629. };
  50630. /**
  50631. * Clones the particle system.
  50632. * @param name The name of the cloned object
  50633. * @param newEmitter The new emitter to use
  50634. * @returns the cloned particle system
  50635. */
  50636. ParticleSystem.prototype.clone = function (name, newEmitter) {
  50637. var custom = null;
  50638. var program = null;
  50639. if (this.customShader != null) {
  50640. program = this.customShader;
  50641. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50642. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50643. }
  50644. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  50645. result.customShader = program;
  50646. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  50647. if (newEmitter === undefined) {
  50648. newEmitter = this.emitter;
  50649. }
  50650. result.emitter = newEmitter;
  50651. if (this.particleTexture) {
  50652. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  50653. }
  50654. if (!this.preventAutoStart) {
  50655. result.start();
  50656. }
  50657. return result;
  50658. };
  50659. /**
  50660. * Serializes the particle system to a JSON object.
  50661. * @returns the JSON object
  50662. */
  50663. ParticleSystem.prototype.serialize = function () {
  50664. var serializationObject = {};
  50665. serializationObject.name = this.name;
  50666. serializationObject.id = this.id;
  50667. // Emitter
  50668. if (this.emitter.position) {
  50669. var emitterMesh = this.emitter;
  50670. serializationObject.emitterId = emitterMesh.id;
  50671. }
  50672. else {
  50673. var emitterPosition = this.emitter;
  50674. serializationObject.emitter = emitterPosition.asArray();
  50675. }
  50676. serializationObject.capacity = this.getCapacity();
  50677. if (this.particleTexture) {
  50678. serializationObject.textureName = this.particleTexture.name;
  50679. }
  50680. // Animations
  50681. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  50682. // Particle system
  50683. serializationObject.minAngularSpeed = this.minAngularSpeed;
  50684. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  50685. serializationObject.minSize = this.minSize;
  50686. serializationObject.maxSize = this.maxSize;
  50687. serializationObject.minEmitPower = this.minEmitPower;
  50688. serializationObject.maxEmitPower = this.maxEmitPower;
  50689. serializationObject.minLifeTime = this.minLifeTime;
  50690. serializationObject.maxLifeTime = this.maxLifeTime;
  50691. serializationObject.emitRate = this.emitRate;
  50692. serializationObject.minEmitBox = this.minEmitBox.asArray();
  50693. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  50694. serializationObject.gravity = this.gravity.asArray();
  50695. serializationObject.direction1 = this.direction1.asArray();
  50696. serializationObject.direction2 = this.direction2.asArray();
  50697. serializationObject.color1 = this.color1.asArray();
  50698. serializationObject.color2 = this.color2.asArray();
  50699. serializationObject.colorDead = this.colorDead.asArray();
  50700. serializationObject.updateSpeed = this.updateSpeed;
  50701. serializationObject.targetStopDuration = this.targetStopDuration;
  50702. serializationObject.textureMask = this.textureMask.asArray();
  50703. serializationObject.blendMode = this.blendMode;
  50704. serializationObject.customShader = this.customShader;
  50705. serializationObject.preventAutoStart = this.preventAutoStart;
  50706. serializationObject.startSpriteCellID = this.startSpriteCellID;
  50707. serializationObject.endSpriteCellID = this.endSpriteCellID;
  50708. serializationObject.spriteCellLoop = this.spriteCellLoop;
  50709. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  50710. serializationObject.spriteCellWidth = this.spriteCellWidth;
  50711. serializationObject.spriteCellHeight = this.spriteCellHeight;
  50712. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  50713. return serializationObject;
  50714. };
  50715. /**
  50716. * Parses a JSON object to create a particle system.
  50717. * @param parsedParticleSystem The JSON object to parse
  50718. * @param scene The scene to create the particle system in
  50719. * @param rootUrl The root url to use to load external dependencies like texture
  50720. * @returns the Parsed particle system
  50721. */
  50722. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  50723. var name = parsedParticleSystem.name;
  50724. var custom = null;
  50725. var program = null;
  50726. if (parsedParticleSystem.customShader) {
  50727. program = parsedParticleSystem.customShader;
  50728. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50729. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50730. }
  50731. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  50732. particleSystem.customShader = program;
  50733. if (parsedParticleSystem.id) {
  50734. particleSystem.id = parsedParticleSystem.id;
  50735. }
  50736. // Auto start
  50737. if (parsedParticleSystem.preventAutoStart) {
  50738. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  50739. }
  50740. // Texture
  50741. if (parsedParticleSystem.textureName) {
  50742. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  50743. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  50744. }
  50745. // Emitter
  50746. if (parsedParticleSystem.emitterId) {
  50747. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  50748. }
  50749. else {
  50750. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  50751. }
  50752. // Animations
  50753. if (parsedParticleSystem.animations) {
  50754. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  50755. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  50756. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50757. }
  50758. }
  50759. if (parsedParticleSystem.autoAnimate) {
  50760. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  50761. }
  50762. // Particle system
  50763. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  50764. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  50765. particleSystem.minSize = parsedParticleSystem.minSize;
  50766. particleSystem.maxSize = parsedParticleSystem.maxSize;
  50767. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  50768. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  50769. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  50770. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  50771. particleSystem.emitRate = parsedParticleSystem.emitRate;
  50772. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  50773. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  50774. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  50775. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  50776. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  50777. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  50778. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  50779. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  50780. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  50781. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  50782. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  50783. particleSystem.blendMode = parsedParticleSystem.blendMode;
  50784. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  50785. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  50786. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  50787. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  50788. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  50789. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  50790. if (!particleSystem.preventAutoStart) {
  50791. particleSystem.start();
  50792. }
  50793. return particleSystem;
  50794. };
  50795. /**
  50796. * Source color is added to the destination color without alpha affecting the result.
  50797. */
  50798. ParticleSystem.BLENDMODE_ONEONE = 0;
  50799. /**
  50800. * Blend current color and particle color using particle’s alpha.
  50801. */
  50802. ParticleSystem.BLENDMODE_STANDARD = 1;
  50803. return ParticleSystem;
  50804. }());
  50805. BABYLON.ParticleSystem = ParticleSystem;
  50806. })(BABYLON || (BABYLON = {}));
  50807. //# sourceMappingURL=babylon.particleSystem.js.map
  50808. var BABYLON;
  50809. (function (BABYLON) {
  50810. /**
  50811. * Particle emitter emitting particles from the inside of a box.
  50812. * It emits the particles randomly between 2 given directions.
  50813. */
  50814. var BoxParticleEmitter = /** @class */ (function () {
  50815. // to be updated like the rest of emitters when breaking changes.
  50816. // all property should be come public variables and passed through constructor.
  50817. /**
  50818. * Creates a new instance of @see BoxParticleEmitter
  50819. * @param _particleSystem the particle system associated with the emitter
  50820. */
  50821. function BoxParticleEmitter(_particleSystem) {
  50822. this._particleSystem = _particleSystem;
  50823. }
  50824. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  50825. /**
  50826. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50827. */
  50828. get: function () {
  50829. return this._particleSystem.direction1;
  50830. },
  50831. /**
  50832. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50833. */
  50834. set: function (value) {
  50835. this._particleSystem.direction1 = value;
  50836. },
  50837. enumerable: true,
  50838. configurable: true
  50839. });
  50840. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  50841. /**
  50842. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50843. */
  50844. get: function () {
  50845. return this._particleSystem.direction2;
  50846. },
  50847. /**
  50848. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50849. */
  50850. set: function (value) {
  50851. this._particleSystem.direction2 = value;
  50852. },
  50853. enumerable: true,
  50854. configurable: true
  50855. });
  50856. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  50857. /**
  50858. * 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.
  50859. */
  50860. get: function () {
  50861. return this._particleSystem.minEmitBox;
  50862. },
  50863. /**
  50864. * 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.
  50865. */
  50866. set: function (value) {
  50867. this._particleSystem.minEmitBox = value;
  50868. },
  50869. enumerable: true,
  50870. configurable: true
  50871. });
  50872. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  50873. /**
  50874. * 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.
  50875. */
  50876. get: function () {
  50877. return this._particleSystem.maxEmitBox;
  50878. },
  50879. /**
  50880. * 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.
  50881. */
  50882. set: function (value) {
  50883. this._particleSystem.maxEmitBox = value;
  50884. },
  50885. enumerable: true,
  50886. configurable: true
  50887. });
  50888. /**
  50889. * Called by the particle System when the direction is computed for the created particle.
  50890. * @param emitPower is the power of the particle (speed)
  50891. * @param worldMatrix is the world matrix of the particle system
  50892. * @param directionToUpdate is the direction vector to update with the result
  50893. * @param particle is the particle we are computed the direction for
  50894. */
  50895. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50896. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  50897. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  50898. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  50899. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  50900. };
  50901. /**
  50902. * Called by the particle System when the position is computed for the created particle.
  50903. * @param worldMatrix is the world matrix of the particle system
  50904. * @param positionToUpdate is the position vector to update with the result
  50905. * @param particle is the particle we are computed the position for
  50906. */
  50907. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50908. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  50909. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  50910. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  50911. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50912. };
  50913. /**
  50914. * Clones the current emitter and returns a copy of it
  50915. * @returns the new emitter
  50916. */
  50917. BoxParticleEmitter.prototype.clone = function () {
  50918. var newOne = new BoxParticleEmitter(this._particleSystem);
  50919. BABYLON.Tools.DeepCopy(this, newOne);
  50920. return newOne;
  50921. };
  50922. return BoxParticleEmitter;
  50923. }());
  50924. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  50925. })(BABYLON || (BABYLON = {}));
  50926. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  50927. var BABYLON;
  50928. (function (BABYLON) {
  50929. /**
  50930. * Particle emitter emitting particles from the inside of a cone.
  50931. * It emits the particles alongside the cone volume from the base to the particle.
  50932. * The emission direction might be randomized.
  50933. */
  50934. var ConeParticleEmitter = /** @class */ (function () {
  50935. /**
  50936. * Creates a new instance of @see ConeParticleEmitter
  50937. * @param radius the radius of the emission cone
  50938. * @param angles the cone base angle
  50939. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50940. */
  50941. function ConeParticleEmitter(radius,
  50942. /**
  50943. * The radius of the emission cone.
  50944. */
  50945. angle,
  50946. /**
  50947. * The cone base angle.
  50948. */
  50949. directionRandomizer) {
  50950. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50951. this.angle = angle;
  50952. this.directionRandomizer = directionRandomizer;
  50953. this.radius = radius;
  50954. }
  50955. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  50956. /**
  50957. * Gets the radius of the emission cone.
  50958. */
  50959. get: function () {
  50960. return this._radius;
  50961. },
  50962. /**
  50963. * Sets the radius of the emission cone.
  50964. */
  50965. set: function (value) {
  50966. this._radius = value;
  50967. if (this.angle !== 0) {
  50968. this._height = value / Math.tan(this.angle / 2);
  50969. }
  50970. else {
  50971. this._height = 1;
  50972. }
  50973. },
  50974. enumerable: true,
  50975. configurable: true
  50976. });
  50977. /**
  50978. * Called by the particle System when the direction is computed for the created particle.
  50979. * @param emitPower is the power of the particle (speed)
  50980. * @param worldMatrix is the world matrix of the particle system
  50981. * @param directionToUpdate is the direction vector to update with the result
  50982. * @param particle is the particle we are computed the direction for
  50983. */
  50984. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50985. if (this.angle === 0) {
  50986. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  50987. }
  50988. else {
  50989. // measure the direction Vector from the emitter to the particle.
  50990. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50991. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50992. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50993. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50994. direction.x += randX;
  50995. direction.y += randY;
  50996. direction.z += randZ;
  50997. direction.normalize();
  50998. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  50999. }
  51000. };
  51001. /**
  51002. * Called by the particle System when the position is computed for the created particle.
  51003. * @param worldMatrix is the world matrix of the particle system
  51004. * @param positionToUpdate is the position vector to update with the result
  51005. * @param particle is the particle we are computed the position for
  51006. */
  51007. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51008. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51009. var h = BABYLON.Scalar.RandomRange(0, 1);
  51010. // Better distribution in a cone at normal angles.
  51011. h = 1 - h * h;
  51012. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51013. radius = radius * h / this._height;
  51014. var randX = radius * Math.sin(s);
  51015. var randZ = radius * Math.cos(s);
  51016. var randY = h;
  51017. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51018. };
  51019. /**
  51020. * Clones the current emitter and returns a copy of it
  51021. * @returns the new emitter
  51022. */
  51023. ConeParticleEmitter.prototype.clone = function () {
  51024. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51025. BABYLON.Tools.DeepCopy(this, newOne);
  51026. return newOne;
  51027. };
  51028. return ConeParticleEmitter;
  51029. }());
  51030. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51031. })(BABYLON || (BABYLON = {}));
  51032. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51033. var BABYLON;
  51034. (function (BABYLON) {
  51035. /**
  51036. * Particle emitter emitting particles from the inside of a sphere.
  51037. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51038. */
  51039. var SphereParticleEmitter = /** @class */ (function () {
  51040. /**
  51041. * Creates a new instance of @see SphereParticleEmitter
  51042. * @param radius the radius of the emission sphere
  51043. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51044. */
  51045. function SphereParticleEmitter(
  51046. /**
  51047. * The radius of the emission sphere.
  51048. */
  51049. radius,
  51050. /**
  51051. * How much to randomize the particle direction [0-1].
  51052. */
  51053. directionRandomizer) {
  51054. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51055. this.radius = radius;
  51056. this.directionRandomizer = directionRandomizer;
  51057. }
  51058. /**
  51059. * Called by the particle System when the direction is computed for the created particle.
  51060. * @param emitPower is the power of the particle (speed)
  51061. * @param worldMatrix is the world matrix of the particle system
  51062. * @param directionToUpdate is the direction vector to update with the result
  51063. * @param particle is the particle we are computed the direction for
  51064. */
  51065. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51066. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51067. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51068. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51069. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51070. direction.x += randX;
  51071. direction.y += randY;
  51072. direction.z += randZ;
  51073. direction.normalize();
  51074. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51075. };
  51076. /**
  51077. * Called by the particle System when the position is computed for the created particle.
  51078. * @param worldMatrix is the world matrix of the particle system
  51079. * @param positionToUpdate is the position vector to update with the result
  51080. * @param particle is the particle we are computed the position for
  51081. */
  51082. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51083. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51084. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51085. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  51086. var randY = this.radius * Math.cos(theta);
  51087. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  51088. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51089. };
  51090. /**
  51091. * Clones the current emitter and returns a copy of it
  51092. * @returns the new emitter
  51093. */
  51094. SphereParticleEmitter.prototype.clone = function () {
  51095. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51096. BABYLON.Tools.DeepCopy(this, newOne);
  51097. return newOne;
  51098. };
  51099. return SphereParticleEmitter;
  51100. }());
  51101. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51102. /**
  51103. * Particle emitter emitting particles from the inside of a sphere.
  51104. * It emits the particles randomly between two vectors.
  51105. */
  51106. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51107. __extends(SphereDirectedParticleEmitter, _super);
  51108. /**
  51109. * Creates a new instance of @see SphereDirectedParticleEmitter
  51110. * @param radius the radius of the emission sphere
  51111. * @param direction1 the min limit of the emission direction
  51112. * @param direction2 the max limit of the emission direction
  51113. */
  51114. function SphereDirectedParticleEmitter(radius,
  51115. /**
  51116. * The min limit of the emission direction.
  51117. */
  51118. direction1,
  51119. /**
  51120. * The max limit of the emission direction.
  51121. */
  51122. direction2) {
  51123. var _this = _super.call(this, radius) || this;
  51124. _this.direction1 = direction1;
  51125. _this.direction2 = direction2;
  51126. return _this;
  51127. }
  51128. /**
  51129. * Called by the particle System when the direction is computed for the created particle.
  51130. * @param emitPower is the power of the particle (speed)
  51131. * @param worldMatrix is the world matrix of the particle system
  51132. * @param directionToUpdate is the direction vector to update with the result
  51133. * @param particle is the particle we are computed the direction for
  51134. */
  51135. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51136. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51137. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51138. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51139. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51140. };
  51141. /**
  51142. * Clones the current emitter and returns a copy of it
  51143. * @returns the new emitter
  51144. */
  51145. SphereDirectedParticleEmitter.prototype.clone = function () {
  51146. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51147. BABYLON.Tools.DeepCopy(this, newOne);
  51148. return newOne;
  51149. };
  51150. return SphereDirectedParticleEmitter;
  51151. }(SphereParticleEmitter));
  51152. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51153. })(BABYLON || (BABYLON = {}));
  51154. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51155. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  51156. var BABYLON;
  51157. (function (BABYLON) {
  51158. /**
  51159. * Represents one particle of a solid particle system.
  51160. * @see SolidParticleSystem
  51161. */
  51162. var SolidParticle = /** @class */ (function () {
  51163. /**
  51164. * Creates a Solid Particle object.
  51165. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  51166. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  51167. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  51168. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  51169. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  51170. * @param shapeId (integer) is the model shape identifier in the SPS.
  51171. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  51172. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  51173. */
  51174. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  51175. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  51176. /**
  51177. * particle global index
  51178. */
  51179. this.idx = 0;
  51180. /**
  51181. * The color of the particle
  51182. */
  51183. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51184. /**
  51185. * The world space position of the particle.
  51186. */
  51187. this.position = BABYLON.Vector3.Zero();
  51188. /**
  51189. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  51190. */
  51191. this.rotation = BABYLON.Vector3.Zero();
  51192. /**
  51193. * The scaling of the particle.
  51194. */
  51195. this.scaling = BABYLON.Vector3.One();
  51196. /**
  51197. * The uvs of the particle.
  51198. */
  51199. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  51200. /**
  51201. * The current speed of the particle.
  51202. */
  51203. this.velocity = BABYLON.Vector3.Zero();
  51204. /**
  51205. * The pivot point in the particle local space.
  51206. */
  51207. this.pivot = BABYLON.Vector3.Zero();
  51208. /**
  51209. * Must the particle be translated from its pivot point in its local space ?
  51210. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  51211. * Default : false
  51212. */
  51213. this.translateFromPivot = false;
  51214. /**
  51215. * Is the particle active or not ?
  51216. */
  51217. this.alive = true;
  51218. /**
  51219. * Is the particle visible or not ?
  51220. */
  51221. this.isVisible = true;
  51222. /**
  51223. * Index of this particle in the global "positions" array (Internal use)
  51224. */
  51225. this._pos = 0;
  51226. /**
  51227. * Index of this particle in the global "indices" array (Internal use)
  51228. */
  51229. this._ind = 0;
  51230. /**
  51231. * ModelShape id of this particle
  51232. */
  51233. this.shapeId = 0;
  51234. /**
  51235. * Index of the particle in its shape id (Internal use)
  51236. */
  51237. this.idxInShape = 0;
  51238. /**
  51239. * Still set as invisible in order to skip useless computations (Internal use)
  51240. */
  51241. this._stillInvisible = false;
  51242. /**
  51243. * Last computed particle rotation matrix
  51244. */
  51245. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  51246. /**
  51247. * Parent particle Id, if any.
  51248. * Default null.
  51249. */
  51250. this.parentId = null;
  51251. /**
  51252. * Internal global position in the SPS.
  51253. */
  51254. this._globalPosition = BABYLON.Vector3.Zero();
  51255. this.idx = particleIndex;
  51256. this._pos = positionIndex;
  51257. this._ind = indiceIndex;
  51258. this._model = model;
  51259. this.shapeId = shapeId;
  51260. this.idxInShape = idxInShape;
  51261. this._sps = sps;
  51262. if (modelBoundingInfo) {
  51263. this._modelBoundingInfo = modelBoundingInfo;
  51264. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  51265. }
  51266. }
  51267. Object.defineProperty(SolidParticle.prototype, "scale", {
  51268. /**
  51269. * Legacy support, changed scale to scaling
  51270. */
  51271. get: function () {
  51272. return this.scaling;
  51273. },
  51274. /**
  51275. * Legacy support, changed scale to scaling
  51276. */
  51277. set: function (scale) {
  51278. this.scaling = scale;
  51279. },
  51280. enumerable: true,
  51281. configurable: true
  51282. });
  51283. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  51284. /**
  51285. * Legacy support, changed quaternion to rotationQuaternion
  51286. */
  51287. get: function () {
  51288. return this.rotationQuaternion;
  51289. },
  51290. /**
  51291. * Legacy support, changed quaternion to rotationQuaternion
  51292. */
  51293. set: function (q) {
  51294. this.rotationQuaternion = q;
  51295. },
  51296. enumerable: true,
  51297. configurable: true
  51298. });
  51299. /**
  51300. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  51301. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  51302. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  51303. * @returns true if it intersects
  51304. */
  51305. SolidParticle.prototype.intersectsMesh = function (target) {
  51306. if (!this._boundingInfo || !target._boundingInfo) {
  51307. return false;
  51308. }
  51309. if (this._sps._bSphereOnly) {
  51310. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  51311. }
  51312. return this._boundingInfo.intersects(target._boundingInfo, false);
  51313. };
  51314. return SolidParticle;
  51315. }());
  51316. BABYLON.SolidParticle = SolidParticle;
  51317. /**
  51318. * Represents the shape of the model used by one particle of a solid particle system.
  51319. * SPS internal tool, don't use it manually.
  51320. * @see SolidParticleSystem
  51321. */
  51322. var ModelShape = /** @class */ (function () {
  51323. /**
  51324. * 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.
  51325. * SPS internal tool, don't use it manually.
  51326. * @ignore
  51327. */
  51328. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  51329. /**
  51330. * length of the shape in the model indices array (internal use)
  51331. */
  51332. this._indicesLength = 0;
  51333. this.shapeID = id;
  51334. this._shape = shape;
  51335. this._indicesLength = indicesLength;
  51336. this._shapeUV = shapeUV;
  51337. this._positionFunction = posFunction;
  51338. this._vertexFunction = vtxFunction;
  51339. }
  51340. return ModelShape;
  51341. }());
  51342. BABYLON.ModelShape = ModelShape;
  51343. /**
  51344. * Represents a Depth Sorted Particle in the solid particle system.
  51345. * @see SolidParticleSystem
  51346. */
  51347. var DepthSortedParticle = /** @class */ (function () {
  51348. function DepthSortedParticle() {
  51349. /**
  51350. * Index of the particle in the "indices" array
  51351. */
  51352. this.ind = 0;
  51353. /**
  51354. * Length of the particle shape in the "indices" array
  51355. */
  51356. this.indicesLength = 0;
  51357. /**
  51358. * Squared distance from the particle to the camera
  51359. */
  51360. this.sqDistance = 0.0;
  51361. }
  51362. return DepthSortedParticle;
  51363. }());
  51364. BABYLON.DepthSortedParticle = DepthSortedParticle;
  51365. })(BABYLON || (BABYLON = {}));
  51366. //# sourceMappingURL=babylon.solidParticle.js.map
  51367. var BABYLON;
  51368. (function (BABYLON) {
  51369. /**
  51370. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  51371. *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.
  51372. * The SPS is also a particle system. It provides some methods to manage the particles.
  51373. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  51374. *
  51375. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  51376. */
  51377. var SolidParticleSystem = /** @class */ (function () {
  51378. /**
  51379. * Creates a SPS (Solid Particle System) object.
  51380. * @param name (String) is the SPS name, this will be the underlying mesh name.
  51381. * @param scene (Scene) is the scene in which the SPS is added.
  51382. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  51383. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  51384. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  51385. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  51386. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  51387. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  51388. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  51389. */
  51390. function SolidParticleSystem(name, scene, options) {
  51391. /**
  51392. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  51393. * Example : var p = SPS.particles[i];
  51394. */
  51395. this.particles = new Array();
  51396. /**
  51397. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  51398. */
  51399. this.nbParticles = 0;
  51400. /**
  51401. * If the particles must ever face the camera (default false). Useful for planar particles.
  51402. */
  51403. this.billboard = false;
  51404. /**
  51405. * Recompute normals when adding a shape
  51406. */
  51407. this.recomputeNormals = true;
  51408. /**
  51409. * This a counter ofr your own usage. It's not set by any SPS functions.
  51410. */
  51411. this.counter = 0;
  51412. /**
  51413. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  51414. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  51415. */
  51416. this.vars = {};
  51417. /**
  51418. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  51419. */
  51420. this._bSphereOnly = false;
  51421. /**
  51422. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  51423. */
  51424. this._bSphereRadiusFactor = 1.0;
  51425. this._positions = new Array();
  51426. this._indices = new Array();
  51427. this._normals = new Array();
  51428. this._colors = new Array();
  51429. this._uvs = new Array();
  51430. this._index = 0; // indices index
  51431. this._updatable = true;
  51432. this._pickable = false;
  51433. this._isVisibilityBoxLocked = false;
  51434. this._alwaysVisible = false;
  51435. this._depthSort = false;
  51436. this._shapeCounter = 0;
  51437. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  51438. this._color = new BABYLON.Color4(0, 0, 0, 0);
  51439. this._computeParticleColor = true;
  51440. this._computeParticleTexture = true;
  51441. this._computeParticleRotation = true;
  51442. this._computeParticleVertex = false;
  51443. this._computeBoundingBox = false;
  51444. this._depthSortParticles = true;
  51445. this._cam_axisZ = BABYLON.Vector3.Zero();
  51446. this._cam_axisY = BABYLON.Vector3.Zero();
  51447. this._cam_axisX = BABYLON.Vector3.Zero();
  51448. this._axisZ = BABYLON.Axis.Z;
  51449. this._camDir = BABYLON.Vector3.Zero();
  51450. this._camInvertedPosition = BABYLON.Vector3.Zero();
  51451. this._rotMatrix = new BABYLON.Matrix();
  51452. this._invertMatrix = new BABYLON.Matrix();
  51453. this._rotated = BABYLON.Vector3.Zero();
  51454. this._quaternion = new BABYLON.Quaternion();
  51455. this._vertex = BABYLON.Vector3.Zero();
  51456. this._normal = BABYLON.Vector3.Zero();
  51457. this._yaw = 0.0;
  51458. this._pitch = 0.0;
  51459. this._roll = 0.0;
  51460. this._halfroll = 0.0;
  51461. this._halfpitch = 0.0;
  51462. this._halfyaw = 0.0;
  51463. this._sinRoll = 0.0;
  51464. this._cosRoll = 0.0;
  51465. this._sinPitch = 0.0;
  51466. this._cosPitch = 0.0;
  51467. this._sinYaw = 0.0;
  51468. this._cosYaw = 0.0;
  51469. this._mustUnrotateFixedNormals = false;
  51470. this._minimum = BABYLON.Vector3.Zero();
  51471. this._maximum = BABYLON.Vector3.Zero();
  51472. this._minBbox = BABYLON.Vector3.Zero();
  51473. this._maxBbox = BABYLON.Vector3.Zero();
  51474. this._particlesIntersect = false;
  51475. this._depthSortFunction = function (p1, p2) {
  51476. return (p2.sqDistance - p1.sqDistance);
  51477. };
  51478. this._needs32Bits = false;
  51479. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  51480. this._scaledPivot = BABYLON.Vector3.Zero();
  51481. this._particleHasParent = false;
  51482. this.name = name;
  51483. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51484. this._camera = scene.activeCamera;
  51485. this._pickable = options ? options.isPickable : false;
  51486. this._depthSort = options ? options.enableDepthSort : false;
  51487. this._particlesIntersect = options ? options.particleIntersection : false;
  51488. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  51489. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  51490. if (options && options.updatable) {
  51491. this._updatable = options.updatable;
  51492. }
  51493. else {
  51494. this._updatable = true;
  51495. }
  51496. if (this._pickable) {
  51497. this.pickedParticles = [];
  51498. }
  51499. if (this._depthSort) {
  51500. this.depthSortedParticles = [];
  51501. }
  51502. }
  51503. /**
  51504. * Builds the SPS underlying mesh. Returns a standard Mesh.
  51505. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  51506. * @returns the created mesh
  51507. */
  51508. SolidParticleSystem.prototype.buildMesh = function () {
  51509. if (this.nbParticles === 0) {
  51510. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  51511. this.addShape(triangle, 1);
  51512. triangle.dispose();
  51513. }
  51514. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  51515. this._positions32 = new Float32Array(this._positions);
  51516. this._uvs32 = new Float32Array(this._uvs);
  51517. this._colors32 = new Float32Array(this._colors);
  51518. if (this.recomputeNormals) {
  51519. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  51520. }
  51521. this._normals32 = new Float32Array(this._normals);
  51522. this._fixedNormal32 = new Float32Array(this._normals);
  51523. if (this._mustUnrotateFixedNormals) {
  51524. this._unrotateFixedNormals();
  51525. }
  51526. var vertexData = new BABYLON.VertexData();
  51527. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  51528. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  51529. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  51530. if (this._uvs32) {
  51531. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  51532. ;
  51533. }
  51534. if (this._colors32) {
  51535. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  51536. }
  51537. var mesh = new BABYLON.Mesh(this.name, this._scene);
  51538. vertexData.applyToMesh(mesh, this._updatable);
  51539. this.mesh = mesh;
  51540. this.mesh.isPickable = this._pickable;
  51541. // free memory
  51542. if (!this._depthSort) {
  51543. this._indices = null;
  51544. }
  51545. this._positions = null;
  51546. this._normals = null;
  51547. this._uvs = null;
  51548. this._colors = null;
  51549. if (!this._updatable) {
  51550. this.particles.length = 0;
  51551. }
  51552. return mesh;
  51553. };
  51554. /**
  51555. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  51556. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  51557. * Thus the particles generated from `digest()` have their property `position` set yet.
  51558. * @param mesh ( Mesh ) is the mesh to be digested
  51559. * @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
  51560. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  51561. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  51562. * @returns the current SPS
  51563. */
  51564. SolidParticleSystem.prototype.digest = function (mesh, options) {
  51565. var size = (options && options.facetNb) || 1;
  51566. var number = (options && options.number) || 0;
  51567. var delta = (options && options.delta) || 0;
  51568. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51569. var meshInd = mesh.getIndices();
  51570. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51571. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51572. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51573. var f = 0; // facet counter
  51574. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  51575. // compute size from number
  51576. if (number) {
  51577. number = (number > totalFacets) ? totalFacets : number;
  51578. size = Math.round(totalFacets / number);
  51579. delta = 0;
  51580. }
  51581. else {
  51582. size = (size > totalFacets) ? totalFacets : size;
  51583. }
  51584. var facetPos = []; // submesh positions
  51585. var facetInd = []; // submesh indices
  51586. var facetUV = []; // submesh UV
  51587. var facetCol = []; // submesh colors
  51588. var barycenter = BABYLON.Vector3.Zero();
  51589. var sizeO = size;
  51590. while (f < totalFacets) {
  51591. size = sizeO + Math.floor((1 + delta) * Math.random());
  51592. if (f > totalFacets - size) {
  51593. size = totalFacets - f;
  51594. }
  51595. // reset temp arrays
  51596. facetPos.length = 0;
  51597. facetInd.length = 0;
  51598. facetUV.length = 0;
  51599. facetCol.length = 0;
  51600. // iterate over "size" facets
  51601. var fi = 0;
  51602. for (var j = f * 3; j < (f + size) * 3; j++) {
  51603. facetInd.push(fi);
  51604. var i = meshInd[j];
  51605. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  51606. if (meshUV) {
  51607. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  51608. }
  51609. if (meshCol) {
  51610. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  51611. }
  51612. fi++;
  51613. }
  51614. // create a model shape for each single particle
  51615. var idx = this.nbParticles;
  51616. var shape = this._posToShape(facetPos);
  51617. var shapeUV = this._uvsToShapeUV(facetUV);
  51618. // compute the barycenter of the shape
  51619. var v;
  51620. for (v = 0; v < shape.length; v++) {
  51621. barycenter.addInPlace(shape[v]);
  51622. }
  51623. barycenter.scaleInPlace(1 / shape.length);
  51624. // shift the shape from its barycenter to the origin
  51625. for (v = 0; v < shape.length; v++) {
  51626. shape[v].subtractInPlace(barycenter);
  51627. }
  51628. var bInfo;
  51629. if (this._particlesIntersect) {
  51630. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  51631. }
  51632. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  51633. // add the particle in the SPS
  51634. var currentPos = this._positions.length;
  51635. var currentInd = this._indices.length;
  51636. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  51637. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  51638. // initialize the particle position
  51639. this.particles[this.nbParticles].position.addInPlace(barycenter);
  51640. this._index += shape.length;
  51641. idx++;
  51642. this.nbParticles++;
  51643. this._shapeCounter++;
  51644. f += size;
  51645. }
  51646. return this;
  51647. };
  51648. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  51649. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  51650. var index = 0;
  51651. var idx = 0;
  51652. for (var p = 0; p < this.particles.length; p++) {
  51653. this._particle = this.particles[p];
  51654. this._shape = this._particle._model._shape;
  51655. if (this._particle.rotationQuaternion) {
  51656. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51657. }
  51658. else {
  51659. this._yaw = this._particle.rotation.y;
  51660. this._pitch = this._particle.rotation.x;
  51661. this._roll = this._particle.rotation.z;
  51662. this._quaternionRotationYPR();
  51663. }
  51664. this._quaternionToRotationMatrix();
  51665. this._rotMatrix.invertToRef(this._invertMatrix);
  51666. for (var pt = 0; pt < this._shape.length; pt++) {
  51667. idx = index + pt * 3;
  51668. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  51669. this._fixedNormal32[idx] = this._normal.x;
  51670. this._fixedNormal32[idx + 1] = this._normal.y;
  51671. this._fixedNormal32[idx + 2] = this._normal.z;
  51672. }
  51673. index = idx + 3;
  51674. }
  51675. };
  51676. //reset copy
  51677. SolidParticleSystem.prototype._resetCopy = function () {
  51678. this._copy.position.x = 0;
  51679. this._copy.position.y = 0;
  51680. this._copy.position.z = 0;
  51681. this._copy.rotation.x = 0;
  51682. this._copy.rotation.y = 0;
  51683. this._copy.rotation.z = 0;
  51684. this._copy.rotationQuaternion = null;
  51685. this._copy.scaling.x = 1.0;
  51686. this._copy.scaling.y = 1.0;
  51687. this._copy.scaling.z = 1.0;
  51688. this._copy.uvs.x = 0;
  51689. this._copy.uvs.y = 0;
  51690. this._copy.uvs.z = 1.0;
  51691. this._copy.uvs.w = 1.0;
  51692. this._copy.color = null;
  51693. this._copy.translateFromPivot = false;
  51694. };
  51695. // _meshBuilder : inserts the shape model in the global SPS mesh
  51696. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  51697. var i;
  51698. var u = 0;
  51699. var c = 0;
  51700. var n = 0;
  51701. this._resetCopy();
  51702. if (options && options.positionFunction) {
  51703. options.positionFunction(this._copy, idx, idxInShape);
  51704. this._mustUnrotateFixedNormals = true;
  51705. }
  51706. if (this._copy.rotationQuaternion) {
  51707. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51708. }
  51709. else {
  51710. this._yaw = this._copy.rotation.y;
  51711. this._pitch = this._copy.rotation.x;
  51712. this._roll = this._copy.rotation.z;
  51713. this._quaternionRotationYPR();
  51714. }
  51715. this._quaternionToRotationMatrix();
  51716. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  51717. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  51718. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  51719. if (this._copy.translateFromPivot) {
  51720. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51721. }
  51722. else {
  51723. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  51724. }
  51725. for (i = 0; i < shape.length; i++) {
  51726. this._vertex.x = shape[i].x;
  51727. this._vertex.y = shape[i].y;
  51728. this._vertex.z = shape[i].z;
  51729. if (options && options.vertexFunction) {
  51730. options.vertexFunction(this._copy, this._vertex, i);
  51731. }
  51732. this._vertex.x *= this._copy.scaling.x;
  51733. this._vertex.y *= this._copy.scaling.y;
  51734. this._vertex.z *= this._copy.scaling.z;
  51735. this._vertex.x -= this._scaledPivot.x;
  51736. this._vertex.y -= this._scaledPivot.y;
  51737. this._vertex.z -= this._scaledPivot.z;
  51738. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51739. this._rotated.addInPlace(this._pivotBackTranslation);
  51740. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  51741. if (meshUV) {
  51742. 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);
  51743. u += 2;
  51744. }
  51745. if (this._copy.color) {
  51746. this._color = this._copy.color;
  51747. }
  51748. else if (meshCol && meshCol[c] !== undefined) {
  51749. this._color.r = meshCol[c];
  51750. this._color.g = meshCol[c + 1];
  51751. this._color.b = meshCol[c + 2];
  51752. this._color.a = meshCol[c + 3];
  51753. }
  51754. else {
  51755. this._color.r = 1.0;
  51756. this._color.g = 1.0;
  51757. this._color.b = 1.0;
  51758. this._color.a = 1.0;
  51759. }
  51760. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  51761. c += 4;
  51762. if (!this.recomputeNormals && meshNor) {
  51763. this._normal.x = meshNor[n];
  51764. this._normal.y = meshNor[n + 1];
  51765. this._normal.z = meshNor[n + 2];
  51766. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  51767. normals.push(this._normal.x, this._normal.y, this._normal.z);
  51768. n += 3;
  51769. }
  51770. }
  51771. for (i = 0; i < meshInd.length; i++) {
  51772. var current_ind = p + meshInd[i];
  51773. indices.push(current_ind);
  51774. if (current_ind > 65535) {
  51775. this._needs32Bits = true;
  51776. }
  51777. }
  51778. if (this._pickable) {
  51779. var nbfaces = meshInd.length / 3;
  51780. for (i = 0; i < nbfaces; i++) {
  51781. this.pickedParticles.push({ idx: idx, faceId: i });
  51782. }
  51783. }
  51784. if (this._depthSort) {
  51785. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  51786. }
  51787. return this._copy;
  51788. };
  51789. // returns a shape array from positions array
  51790. SolidParticleSystem.prototype._posToShape = function (positions) {
  51791. var shape = [];
  51792. for (var i = 0; i < positions.length; i += 3) {
  51793. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  51794. }
  51795. return shape;
  51796. };
  51797. // returns a shapeUV array from a Vector4 uvs
  51798. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  51799. var shapeUV = [];
  51800. if (uvs) {
  51801. for (var i = 0; i < uvs.length; i++)
  51802. shapeUV.push(uvs[i]);
  51803. }
  51804. return shapeUV;
  51805. };
  51806. // adds a new particle object in the particles array
  51807. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  51808. if (bInfo === void 0) { bInfo = null; }
  51809. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  51810. this.particles.push(sp);
  51811. return sp;
  51812. };
  51813. /**
  51814. * Adds some particles to the SPS from the model shape. Returns the shape id.
  51815. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  51816. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  51817. * @param nb (positive integer) the number of particles to be created from this model
  51818. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  51819. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  51820. * @returns the number of shapes in the system
  51821. */
  51822. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  51823. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51824. var meshInd = mesh.getIndices();
  51825. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51826. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51827. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51828. var bbInfo;
  51829. if (this._particlesIntersect) {
  51830. bbInfo = mesh.getBoundingInfo();
  51831. }
  51832. var shape = this._posToShape(meshPos);
  51833. var shapeUV = this._uvsToShapeUV(meshUV);
  51834. var posfunc = options ? options.positionFunction : null;
  51835. var vtxfunc = options ? options.vertexFunction : null;
  51836. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  51837. // particles
  51838. var sp;
  51839. var currentCopy;
  51840. var idx = this.nbParticles;
  51841. for (var i = 0; i < nb; i++) {
  51842. var currentPos = this._positions.length;
  51843. var currentInd = this._indices.length;
  51844. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  51845. if (this._updatable) {
  51846. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  51847. sp.position.copyFrom(currentCopy.position);
  51848. sp.rotation.copyFrom(currentCopy.rotation);
  51849. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  51850. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  51851. }
  51852. if (currentCopy.color && sp.color) {
  51853. sp.color.copyFrom(currentCopy.color);
  51854. }
  51855. sp.scaling.copyFrom(currentCopy.scaling);
  51856. sp.uvs.copyFrom(currentCopy.uvs);
  51857. }
  51858. this._index += shape.length;
  51859. idx++;
  51860. }
  51861. this.nbParticles += nb;
  51862. this._shapeCounter++;
  51863. return this._shapeCounter - 1;
  51864. };
  51865. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  51866. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  51867. this._resetCopy();
  51868. if (particle._model._positionFunction) {
  51869. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  51870. }
  51871. if (this._copy.rotationQuaternion) {
  51872. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51873. }
  51874. else {
  51875. this._yaw = this._copy.rotation.y;
  51876. this._pitch = this._copy.rotation.x;
  51877. this._roll = this._copy.rotation.z;
  51878. this._quaternionRotationYPR();
  51879. }
  51880. this._quaternionToRotationMatrix();
  51881. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  51882. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  51883. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  51884. if (this._copy.translateFromPivot) {
  51885. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51886. }
  51887. else {
  51888. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  51889. }
  51890. this._shape = particle._model._shape;
  51891. for (var pt = 0; pt < this._shape.length; pt++) {
  51892. this._vertex.x = this._shape[pt].x;
  51893. this._vertex.y = this._shape[pt].y;
  51894. this._vertex.z = this._shape[pt].z;
  51895. if (particle._model._vertexFunction) {
  51896. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  51897. }
  51898. this._vertex.x *= this._copy.scaling.x;
  51899. this._vertex.y *= this._copy.scaling.y;
  51900. this._vertex.z *= this._copy.scaling.z;
  51901. this._vertex.x -= this._scaledPivot.x;
  51902. this._vertex.y -= this._scaledPivot.y;
  51903. this._vertex.z -= this._scaledPivot.z;
  51904. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51905. this._rotated.addInPlace(this._pivotBackTranslation);
  51906. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  51907. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  51908. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  51909. }
  51910. particle.position.x = 0.0;
  51911. particle.position.y = 0.0;
  51912. particle.position.z = 0.0;
  51913. particle.rotation.x = 0.0;
  51914. particle.rotation.y = 0.0;
  51915. particle.rotation.z = 0.0;
  51916. particle.rotationQuaternion = null;
  51917. particle.scaling.x = 1.0;
  51918. particle.scaling.y = 1.0;
  51919. particle.scaling.z = 1.0;
  51920. particle.uvs.x = 0.0;
  51921. particle.uvs.y = 0.0;
  51922. particle.uvs.z = 1.0;
  51923. particle.uvs.w = 1.0;
  51924. particle.pivot.x = 0.0;
  51925. particle.pivot.y = 0.0;
  51926. particle.pivot.z = 0.0;
  51927. particle.translateFromPivot = false;
  51928. particle.parentId = null;
  51929. };
  51930. /**
  51931. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  51932. * @returns the SPS.
  51933. */
  51934. SolidParticleSystem.prototype.rebuildMesh = function () {
  51935. for (var p = 0; p < this.particles.length; p++) {
  51936. this._rebuildParticle(this.particles[p]);
  51937. }
  51938. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  51939. return this;
  51940. };
  51941. /**
  51942. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  51943. * This method calls `updateParticle()` for each particle of the SPS.
  51944. * For an animated SPS, it is usually called within the render loop.
  51945. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  51946. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  51947. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  51948. * @returns the SPS.
  51949. */
  51950. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  51951. if (start === void 0) { start = 0; }
  51952. if (end === void 0) { end = this.nbParticles - 1; }
  51953. if (update === void 0) { update = true; }
  51954. if (!this._updatable) {
  51955. return this;
  51956. }
  51957. // custom beforeUpdate
  51958. this.beforeUpdateParticles(start, end, update);
  51959. this._cam_axisX.x = 1.0;
  51960. this._cam_axisX.y = 0.0;
  51961. this._cam_axisX.z = 0.0;
  51962. this._cam_axisY.x = 0.0;
  51963. this._cam_axisY.y = 1.0;
  51964. this._cam_axisY.z = 0.0;
  51965. this._cam_axisZ.x = 0.0;
  51966. this._cam_axisZ.y = 0.0;
  51967. this._cam_axisZ.z = 1.0;
  51968. // cases when the World Matrix is to be computed first
  51969. if (this.billboard || this._depthSort) {
  51970. this.mesh.computeWorldMatrix(true);
  51971. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  51972. }
  51973. // if the particles will always face the camera
  51974. if (this.billboard) {
  51975. // compute the camera position and un-rotate it by the current mesh rotation
  51976. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  51977. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  51978. this._cam_axisZ.normalize();
  51979. // same for camera up vector extracted from the cam view matrix
  51980. var view = this._camera.getViewMatrix(true);
  51981. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  51982. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  51983. this._cam_axisY.normalize();
  51984. this._cam_axisX.normalize();
  51985. }
  51986. // if depthSort, compute the camera global position in the mesh local system
  51987. if (this._depthSort) {
  51988. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  51989. }
  51990. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  51991. var idx = 0; // current position index in the global array positions32
  51992. var index = 0; // position start index in the global array positions32 of the current particle
  51993. var colidx = 0; // current color index in the global array colors32
  51994. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  51995. var uvidx = 0; // current uv index in the global array uvs32
  51996. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  51997. var pt = 0; // current index in the particle model shape
  51998. if (this.mesh.isFacetDataEnabled) {
  51999. this._computeBoundingBox = true;
  52000. }
  52001. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52002. if (this._computeBoundingBox) {
  52003. if (start == 0 && end == this.nbParticles - 1) {
  52004. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52005. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52006. }
  52007. else {
  52008. if (this.mesh._boundingInfo) {
  52009. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  52010. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  52011. }
  52012. }
  52013. }
  52014. // particle loop
  52015. index = this.particles[start]._pos;
  52016. var vpos = (index / 3) | 0;
  52017. colorIndex = vpos * 4;
  52018. uvIndex = vpos * 2;
  52019. for (var p = start; p <= end; p++) {
  52020. this._particle = this.particles[p];
  52021. this._shape = this._particle._model._shape;
  52022. this._shapeUV = this._particle._model._shapeUV;
  52023. // call to custom user function to update the particle properties
  52024. this.updateParticle(this._particle);
  52025. // camera-particle distance for depth sorting
  52026. if (this._depthSort && this._depthSortParticles) {
  52027. var dsp = this.depthSortedParticles[p];
  52028. dsp.ind = this._particle._ind;
  52029. dsp.indicesLength = this._particle._model._indicesLength;
  52030. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  52031. }
  52032. // skip the computations for inactive or already invisible particles
  52033. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  52034. // increment indexes for the next particle
  52035. pt = this._shape.length;
  52036. index += pt * 3;
  52037. colorIndex += pt * 4;
  52038. uvIndex += pt * 2;
  52039. continue;
  52040. }
  52041. if (this._particle.isVisible) {
  52042. this._particle._stillInvisible = false; // un-mark permanent invisibility
  52043. this._particleHasParent = (this._particle.parentId !== null);
  52044. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52045. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52046. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52047. // particle rotation matrix
  52048. if (this.billboard) {
  52049. this._particle.rotation.x = 0.0;
  52050. this._particle.rotation.y = 0.0;
  52051. }
  52052. if (this._computeParticleRotation || this.billboard) {
  52053. if (this._particle.rotationQuaternion) {
  52054. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52055. }
  52056. else {
  52057. this._yaw = this._particle.rotation.y;
  52058. this._pitch = this._particle.rotation.x;
  52059. this._roll = this._particle.rotation.z;
  52060. this._quaternionRotationYPR();
  52061. }
  52062. this._quaternionToRotationMatrix();
  52063. }
  52064. if (this._particleHasParent) {
  52065. this._parent = this.particles[this._particle.parentId];
  52066. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  52067. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  52068. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  52069. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  52070. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  52071. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  52072. if (this._computeParticleRotation || this.billboard) {
  52073. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  52074. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  52075. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  52076. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  52077. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  52078. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  52079. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  52080. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  52081. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  52082. }
  52083. }
  52084. else {
  52085. this._particle._globalPosition.x = this._particle.position.x;
  52086. this._particle._globalPosition.y = this._particle.position.y;
  52087. this._particle._globalPosition.z = this._particle.position.z;
  52088. if (this._computeParticleRotation || this.billboard) {
  52089. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  52090. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  52091. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  52092. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  52093. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  52094. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  52095. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  52096. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  52097. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  52098. }
  52099. }
  52100. if (this._particle.translateFromPivot) {
  52101. this._pivotBackTranslation.x = 0.0;
  52102. this._pivotBackTranslation.y = 0.0;
  52103. this._pivotBackTranslation.z = 0.0;
  52104. }
  52105. else {
  52106. this._pivotBackTranslation.x = this._scaledPivot.x;
  52107. this._pivotBackTranslation.y = this._scaledPivot.y;
  52108. this._pivotBackTranslation.z = this._scaledPivot.z;
  52109. }
  52110. // particle vertex loop
  52111. for (pt = 0; pt < this._shape.length; pt++) {
  52112. idx = index + pt * 3;
  52113. colidx = colorIndex + pt * 4;
  52114. uvidx = uvIndex + pt * 2;
  52115. this._vertex.x = this._shape[pt].x;
  52116. this._vertex.y = this._shape[pt].y;
  52117. this._vertex.z = this._shape[pt].z;
  52118. if (this._computeParticleVertex) {
  52119. this.updateParticleVertex(this._particle, this._vertex, pt);
  52120. }
  52121. // positions
  52122. this._vertex.x *= this._particle.scaling.x;
  52123. this._vertex.y *= this._particle.scaling.y;
  52124. this._vertex.z *= this._particle.scaling.z;
  52125. this._vertex.x -= this._scaledPivot.x;
  52126. this._vertex.y -= this._scaledPivot.y;
  52127. this._vertex.z -= this._scaledPivot.z;
  52128. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52129. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52130. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52131. this._rotated.x += this._pivotBackTranslation.x;
  52132. this._rotated.y += this._pivotBackTranslation.y;
  52133. this._rotated.z += this._pivotBackTranslation.z;
  52134. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52135. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  52136. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  52137. if (this._computeBoundingBox) {
  52138. if (this._positions32[idx] < this._minimum.x) {
  52139. this._minimum.x = this._positions32[idx];
  52140. }
  52141. if (this._positions32[idx] > this._maximum.x) {
  52142. this._maximum.x = this._positions32[idx];
  52143. }
  52144. if (this._positions32[idx + 1] < this._minimum.y) {
  52145. this._minimum.y = this._positions32[idx + 1];
  52146. }
  52147. if (this._positions32[idx + 1] > this._maximum.y) {
  52148. this._maximum.y = this._positions32[idx + 1];
  52149. }
  52150. if (this._positions32[idx + 2] < this._minimum.z) {
  52151. this._minimum.z = this._positions32[idx + 2];
  52152. }
  52153. if (this._positions32[idx + 2] > this._maximum.z) {
  52154. this._maximum.z = this._positions32[idx + 2];
  52155. }
  52156. }
  52157. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52158. if (!this._computeParticleVertex) {
  52159. this._normal.x = this._fixedNormal32[idx];
  52160. this._normal.y = this._fixedNormal32[idx + 1];
  52161. this._normal.z = this._fixedNormal32[idx + 2];
  52162. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  52163. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  52164. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  52165. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52166. 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;
  52167. 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;
  52168. }
  52169. if (this._computeParticleColor && this._particle.color) {
  52170. this._colors32[colidx] = this._particle.color.r;
  52171. this._colors32[colidx + 1] = this._particle.color.g;
  52172. this._colors32[colidx + 2] = this._particle.color.b;
  52173. this._colors32[colidx + 3] = this._particle.color.a;
  52174. }
  52175. if (this._computeParticleTexture) {
  52176. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52177. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52178. }
  52179. }
  52180. }
  52181. else {
  52182. this._particle._stillInvisible = true; // mark the particle as invisible
  52183. for (pt = 0; pt < this._shape.length; pt++) {
  52184. idx = index + pt * 3;
  52185. colidx = colorIndex + pt * 4;
  52186. uvidx = uvIndex + pt * 2;
  52187. this._positions32[idx] = 0.0;
  52188. this._positions32[idx + 1] = 0.0;
  52189. this._positions32[idx + 2] = 0.0;
  52190. this._normals32[idx] = 0.0;
  52191. this._normals32[idx + 1] = 0.0;
  52192. this._normals32[idx + 2] = 0.0;
  52193. if (this._computeParticleColor && this._particle.color) {
  52194. this._colors32[colidx] = this._particle.color.r;
  52195. this._colors32[colidx + 1] = this._particle.color.g;
  52196. this._colors32[colidx + 2] = this._particle.color.b;
  52197. this._colors32[colidx + 3] = this._particle.color.a;
  52198. }
  52199. if (this._computeParticleTexture) {
  52200. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52201. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52202. }
  52203. }
  52204. }
  52205. // if the particle intersections must be computed : update the bbInfo
  52206. if (this._particlesIntersect) {
  52207. var bInfo = this._particle._boundingInfo;
  52208. var bBox = bInfo.boundingBox;
  52209. var bSphere = bInfo.boundingSphere;
  52210. if (!this._bSphereOnly) {
  52211. // place, scale and rotate the particle bbox within the SPS local system, then update it
  52212. for (var b = 0; b < bBox.vectors.length; b++) {
  52213. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  52214. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  52215. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  52216. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52217. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52218. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52219. 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;
  52220. 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;
  52221. 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;
  52222. }
  52223. bBox._update(this.mesh._worldMatrix);
  52224. }
  52225. // place and scale the particle bouding sphere in the SPS local system, then update it
  52226. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  52227. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  52228. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  52229. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  52230. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  52231. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52232. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52233. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52234. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52235. 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));
  52236. bSphere._update(this.mesh._worldMatrix);
  52237. }
  52238. // increment indexes for the next particle
  52239. index = idx + 3;
  52240. colorIndex = colidx + 4;
  52241. uvIndex = uvidx + 2;
  52242. }
  52243. // if the VBO must be updated
  52244. if (update) {
  52245. if (this._computeParticleColor) {
  52246. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  52247. }
  52248. if (this._computeParticleTexture) {
  52249. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  52250. }
  52251. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52252. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  52253. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52254. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52255. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52256. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  52257. for (var i = 0; i < this._normals32.length; i++) {
  52258. this._fixedNormal32[i] = this._normals32[i];
  52259. }
  52260. }
  52261. if (!this.mesh.areNormalsFrozen) {
  52262. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  52263. }
  52264. }
  52265. if (this._depthSort && this._depthSortParticles) {
  52266. this.depthSortedParticles.sort(this._depthSortFunction);
  52267. var dspl = this.depthSortedParticles.length;
  52268. var sorted = 0;
  52269. var lind = 0;
  52270. var sind = 0;
  52271. var sid = 0;
  52272. for (sorted = 0; sorted < dspl; sorted++) {
  52273. lind = this.depthSortedParticles[sorted].indicesLength;
  52274. sind = this.depthSortedParticles[sorted].ind;
  52275. for (var i = 0; i < lind; i++) {
  52276. this._indices32[sid] = this._indices[sind + i];
  52277. sid++;
  52278. }
  52279. }
  52280. this.mesh.updateIndices(this._indices32);
  52281. }
  52282. }
  52283. if (this._computeBoundingBox) {
  52284. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  52285. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  52286. }
  52287. this.afterUpdateParticles(start, end, update);
  52288. return this;
  52289. };
  52290. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  52291. this._halfroll = this._roll * 0.5;
  52292. this._halfpitch = this._pitch * 0.5;
  52293. this._halfyaw = this._yaw * 0.5;
  52294. this._sinRoll = Math.sin(this._halfroll);
  52295. this._cosRoll = Math.cos(this._halfroll);
  52296. this._sinPitch = Math.sin(this._halfpitch);
  52297. this._cosPitch = Math.cos(this._halfpitch);
  52298. this._sinYaw = Math.sin(this._halfyaw);
  52299. this._cosYaw = Math.cos(this._halfyaw);
  52300. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  52301. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  52302. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  52303. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  52304. };
  52305. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  52306. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  52307. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  52308. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  52309. this._rotMatrix.m[3] = 0;
  52310. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  52311. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  52312. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  52313. this._rotMatrix.m[7] = 0;
  52314. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  52315. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  52316. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  52317. this._rotMatrix.m[11] = 0;
  52318. this._rotMatrix.m[12] = 0;
  52319. this._rotMatrix.m[13] = 0;
  52320. this._rotMatrix.m[14] = 0;
  52321. this._rotMatrix.m[15] = 1.0;
  52322. };
  52323. /**
  52324. * Disposes the SPS.
  52325. */
  52326. SolidParticleSystem.prototype.dispose = function () {
  52327. this.mesh.dispose();
  52328. this.vars = null;
  52329. // drop references to internal big arrays for the GC
  52330. this._positions = null;
  52331. this._indices = null;
  52332. this._normals = null;
  52333. this._uvs = null;
  52334. this._colors = null;
  52335. this._indices32 = null;
  52336. this._positions32 = null;
  52337. this._normals32 = null;
  52338. this._fixedNormal32 = null;
  52339. this._uvs32 = null;
  52340. this._colors32 = null;
  52341. this.pickedParticles = null;
  52342. };
  52343. /**
  52344. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  52345. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52346. * @returns the SPS.
  52347. */
  52348. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  52349. if (!this._isVisibilityBoxLocked) {
  52350. this.mesh.refreshBoundingInfo();
  52351. }
  52352. return this;
  52353. };
  52354. /**
  52355. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  52356. * @param size the size (float) of the visibility box
  52357. * note : this doesn't lock the SPS mesh bounding box.
  52358. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52359. */
  52360. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  52361. var vis = size / 2;
  52362. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  52363. };
  52364. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  52365. /**
  52366. * Gets whether the SPS as always visible or not
  52367. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52368. */
  52369. get: function () {
  52370. return this._alwaysVisible;
  52371. },
  52372. /**
  52373. * Sets the SPS as always visible or not
  52374. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52375. */
  52376. set: function (val) {
  52377. this._alwaysVisible = val;
  52378. this.mesh.alwaysSelectAsActiveMesh = val;
  52379. },
  52380. enumerable: true,
  52381. configurable: true
  52382. });
  52383. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  52384. /**
  52385. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52386. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52387. */
  52388. get: function () {
  52389. return this._isVisibilityBoxLocked;
  52390. },
  52391. /**
  52392. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52393. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52394. */
  52395. set: function (val) {
  52396. this._isVisibilityBoxLocked = val;
  52397. var boundingInfo = this.mesh.getBoundingInfo();
  52398. boundingInfo.isLocked = val;
  52399. },
  52400. enumerable: true,
  52401. configurable: true
  52402. });
  52403. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  52404. /**
  52405. * Gets if `setParticles()` computes the particle rotations or not.
  52406. * Default value : true. The SPS is faster when it's set to false.
  52407. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52408. */
  52409. get: function () {
  52410. return this._computeParticleRotation;
  52411. },
  52412. /**
  52413. * Tells to `setParticles()` to compute the particle rotations or not.
  52414. * Default value : true. The SPS is faster when it's set to false.
  52415. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52416. */
  52417. set: function (val) {
  52418. this._computeParticleRotation = val;
  52419. },
  52420. enumerable: true,
  52421. configurable: true
  52422. });
  52423. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  52424. /**
  52425. * Gets if `setParticles()` computes the particle colors or not.
  52426. * Default value : true. The SPS is faster when it's set to false.
  52427. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52428. */
  52429. get: function () {
  52430. return this._computeParticleColor;
  52431. },
  52432. /**
  52433. * Tells to `setParticles()` to compute the particle colors or not.
  52434. * Default value : true. The SPS is faster when it's set to false.
  52435. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52436. */
  52437. set: function (val) {
  52438. this._computeParticleColor = val;
  52439. },
  52440. enumerable: true,
  52441. configurable: true
  52442. });
  52443. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  52444. /**
  52445. * Gets if `setParticles()` computes the particle textures or not.
  52446. * Default value : true. The SPS is faster when it's set to false.
  52447. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  52448. */
  52449. get: function () {
  52450. return this._computeParticleTexture;
  52451. },
  52452. set: function (val) {
  52453. this._computeParticleTexture = val;
  52454. },
  52455. enumerable: true,
  52456. configurable: true
  52457. });
  52458. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  52459. /**
  52460. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  52461. * Default value : false. The SPS is faster when it's set to false.
  52462. * Note : the particle custom vertex positions aren't stored values.
  52463. */
  52464. get: function () {
  52465. return this._computeParticleVertex;
  52466. },
  52467. /**
  52468. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  52469. * Default value : false. The SPS is faster when it's set to false.
  52470. * Note : the particle custom vertex positions aren't stored values.
  52471. */
  52472. set: function (val) {
  52473. this._computeParticleVertex = val;
  52474. },
  52475. enumerable: true,
  52476. configurable: true
  52477. });
  52478. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  52479. /**
  52480. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  52481. */
  52482. get: function () {
  52483. return this._computeBoundingBox;
  52484. },
  52485. /**
  52486. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  52487. */
  52488. set: function (val) {
  52489. this._computeBoundingBox = val;
  52490. },
  52491. enumerable: true,
  52492. configurable: true
  52493. });
  52494. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  52495. /**
  52496. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  52497. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52498. * Default : `true`
  52499. */
  52500. get: function () {
  52501. return this._depthSortParticles;
  52502. },
  52503. /**
  52504. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  52505. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52506. * Default : `true`
  52507. */
  52508. set: function (val) {
  52509. this._depthSortParticles = val;
  52510. },
  52511. enumerable: true,
  52512. configurable: true
  52513. });
  52514. // =======================================================================
  52515. // Particle behavior logic
  52516. // these following methods may be overwritten by the user to fit his needs
  52517. /**
  52518. * This function does nothing. It may be overwritten to set all the particle first values.
  52519. * The SPS doesn't call this function, you may have to call it by your own.
  52520. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52521. */
  52522. SolidParticleSystem.prototype.initParticles = function () {
  52523. };
  52524. /**
  52525. * This function does nothing. It may be overwritten to recycle a particle.
  52526. * The SPS doesn't call this function, you may have to call it by your own.
  52527. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52528. * @param particle The particle to recycle
  52529. * @returns the recycled particle
  52530. */
  52531. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  52532. return particle;
  52533. };
  52534. /**
  52535. * Updates a particle : this function should be overwritten by the user.
  52536. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  52537. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52538. * @example : just set a particle position or velocity and recycle conditions
  52539. * @param particle The particle to update
  52540. * @returns the updated particle
  52541. */
  52542. SolidParticleSystem.prototype.updateParticle = function (particle) {
  52543. return particle;
  52544. };
  52545. /**
  52546. * Updates a vertex of a particle : it can be overwritten by the user.
  52547. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  52548. * @param particle the current particle
  52549. * @param vertex the current index of the current particle
  52550. * @param pt the index of the current vertex in the particle shape
  52551. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  52552. * @example : just set a vertex particle position
  52553. * @returns the updated vertex
  52554. */
  52555. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  52556. return vertex;
  52557. };
  52558. /**
  52559. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  52560. * This does nothing and may be overwritten by the user.
  52561. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52562. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52563. * @param update the boolean update value actually passed to setParticles()
  52564. */
  52565. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  52566. };
  52567. /**
  52568. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  52569. * This will be passed three parameters.
  52570. * This does nothing and may be overwritten by the user.
  52571. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52572. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52573. * @param update the boolean update value actually passed to setParticles()
  52574. */
  52575. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  52576. };
  52577. return SolidParticleSystem;
  52578. }());
  52579. BABYLON.SolidParticleSystem = SolidParticleSystem;
  52580. })(BABYLON || (BABYLON = {}));
  52581. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  52582. var BABYLON;
  52583. (function (BABYLON) {
  52584. var ShaderMaterial = /** @class */ (function (_super) {
  52585. __extends(ShaderMaterial, _super);
  52586. function ShaderMaterial(name, scene, shaderPath, options) {
  52587. var _this = _super.call(this, name, scene) || this;
  52588. _this._textures = {};
  52589. _this._textureArrays = {};
  52590. _this._floats = {};
  52591. _this._ints = {};
  52592. _this._floatsArrays = {};
  52593. _this._colors3 = {};
  52594. _this._colors3Arrays = {};
  52595. _this._colors4 = {};
  52596. _this._vectors2 = {};
  52597. _this._vectors3 = {};
  52598. _this._vectors4 = {};
  52599. _this._matrices = {};
  52600. _this._matrices3x3 = {};
  52601. _this._matrices2x2 = {};
  52602. _this._vectors2Arrays = {};
  52603. _this._vectors3Arrays = {};
  52604. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  52605. _this._shaderPath = shaderPath;
  52606. options.needAlphaBlending = options.needAlphaBlending || false;
  52607. options.needAlphaTesting = options.needAlphaTesting || false;
  52608. options.attributes = options.attributes || ["position", "normal", "uv"];
  52609. options.uniforms = options.uniforms || ["worldViewProjection"];
  52610. options.uniformBuffers = options.uniformBuffers || [];
  52611. options.samplers = options.samplers || [];
  52612. options.defines = options.defines || [];
  52613. _this._options = options;
  52614. return _this;
  52615. }
  52616. ShaderMaterial.prototype.getClassName = function () {
  52617. return "ShaderMaterial";
  52618. };
  52619. ShaderMaterial.prototype.needAlphaBlending = function () {
  52620. return this._options.needAlphaBlending;
  52621. };
  52622. ShaderMaterial.prototype.needAlphaTesting = function () {
  52623. return this._options.needAlphaTesting;
  52624. };
  52625. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  52626. if (this._options.uniforms.indexOf(uniformName) === -1) {
  52627. this._options.uniforms.push(uniformName);
  52628. }
  52629. };
  52630. ShaderMaterial.prototype.setTexture = function (name, texture) {
  52631. if (this._options.samplers.indexOf(name) === -1) {
  52632. this._options.samplers.push(name);
  52633. }
  52634. this._textures[name] = texture;
  52635. return this;
  52636. };
  52637. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  52638. if (this._options.samplers.indexOf(name) === -1) {
  52639. this._options.samplers.push(name);
  52640. }
  52641. this._checkUniform(name);
  52642. this._textureArrays[name] = textures;
  52643. return this;
  52644. };
  52645. ShaderMaterial.prototype.setFloat = function (name, value) {
  52646. this._checkUniform(name);
  52647. this._floats[name] = value;
  52648. return this;
  52649. };
  52650. ShaderMaterial.prototype.setInt = function (name, value) {
  52651. this._checkUniform(name);
  52652. this._ints[name] = value;
  52653. return this;
  52654. };
  52655. ShaderMaterial.prototype.setFloats = function (name, value) {
  52656. this._checkUniform(name);
  52657. this._floatsArrays[name] = value;
  52658. return this;
  52659. };
  52660. ShaderMaterial.prototype.setColor3 = function (name, value) {
  52661. this._checkUniform(name);
  52662. this._colors3[name] = value;
  52663. return this;
  52664. };
  52665. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  52666. this._checkUniform(name);
  52667. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  52668. color.toArray(arr, arr.length);
  52669. return arr;
  52670. }, []);
  52671. return this;
  52672. };
  52673. ShaderMaterial.prototype.setColor4 = function (name, value) {
  52674. this._checkUniform(name);
  52675. this._colors4[name] = value;
  52676. return this;
  52677. };
  52678. ShaderMaterial.prototype.setVector2 = function (name, value) {
  52679. this._checkUniform(name);
  52680. this._vectors2[name] = value;
  52681. return this;
  52682. };
  52683. ShaderMaterial.prototype.setVector3 = function (name, value) {
  52684. this._checkUniform(name);
  52685. this._vectors3[name] = value;
  52686. return this;
  52687. };
  52688. ShaderMaterial.prototype.setVector4 = function (name, value) {
  52689. this._checkUniform(name);
  52690. this._vectors4[name] = value;
  52691. return this;
  52692. };
  52693. ShaderMaterial.prototype.setMatrix = function (name, value) {
  52694. this._checkUniform(name);
  52695. this._matrices[name] = value;
  52696. return this;
  52697. };
  52698. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  52699. this._checkUniform(name);
  52700. this._matrices3x3[name] = value;
  52701. return this;
  52702. };
  52703. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  52704. this._checkUniform(name);
  52705. this._matrices2x2[name] = value;
  52706. return this;
  52707. };
  52708. ShaderMaterial.prototype.setArray2 = function (name, value) {
  52709. this._checkUniform(name);
  52710. this._vectors2Arrays[name] = value;
  52711. return this;
  52712. };
  52713. ShaderMaterial.prototype.setArray3 = function (name, value) {
  52714. this._checkUniform(name);
  52715. this._vectors3Arrays[name] = value;
  52716. return this;
  52717. };
  52718. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  52719. if (!mesh) {
  52720. return true;
  52721. }
  52722. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  52723. return false;
  52724. }
  52725. return false;
  52726. };
  52727. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  52728. var scene = this.getScene();
  52729. var engine = scene.getEngine();
  52730. if (!this.checkReadyOnEveryCall) {
  52731. if (this._renderId === scene.getRenderId()) {
  52732. if (this._checkCache(scene, mesh, useInstances)) {
  52733. return true;
  52734. }
  52735. }
  52736. }
  52737. // Instances
  52738. var defines = [];
  52739. var attribs = [];
  52740. var fallbacks = new BABYLON.EffectFallbacks();
  52741. if (useInstances) {
  52742. defines.push("#define INSTANCES");
  52743. }
  52744. for (var index = 0; index < this._options.defines.length; index++) {
  52745. defines.push(this._options.defines[index]);
  52746. }
  52747. for (var index = 0; index < this._options.attributes.length; index++) {
  52748. attribs.push(this._options.attributes[index]);
  52749. }
  52750. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  52751. attribs.push(BABYLON.VertexBuffer.ColorKind);
  52752. defines.push("#define VERTEXCOLOR");
  52753. }
  52754. // Bones
  52755. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  52756. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52757. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52758. if (mesh.numBoneInfluencers > 4) {
  52759. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52760. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52761. }
  52762. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52763. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52764. fallbacks.addCPUSkinningFallback(0, mesh);
  52765. if (this._options.uniforms.indexOf("mBones") === -1) {
  52766. this._options.uniforms.push("mBones");
  52767. }
  52768. }
  52769. else {
  52770. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52771. }
  52772. // Textures
  52773. for (var name in this._textures) {
  52774. if (!this._textures[name].isReady()) {
  52775. return false;
  52776. }
  52777. }
  52778. // Alpha test
  52779. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  52780. defines.push("#define ALPHATEST");
  52781. }
  52782. var previousEffect = this._effect;
  52783. var join = defines.join("\n");
  52784. this._effect = engine.createEffect(this._shaderPath, {
  52785. attributes: attribs,
  52786. uniformsNames: this._options.uniforms,
  52787. uniformBuffersNames: this._options.uniformBuffers,
  52788. samplers: this._options.samplers,
  52789. defines: join,
  52790. fallbacks: fallbacks,
  52791. onCompiled: this.onCompiled,
  52792. onError: this.onError
  52793. }, engine);
  52794. if (!this._effect.isReady()) {
  52795. return false;
  52796. }
  52797. if (previousEffect !== this._effect) {
  52798. scene.resetCachedMaterial();
  52799. }
  52800. this._renderId = scene.getRenderId();
  52801. return true;
  52802. };
  52803. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  52804. var scene = this.getScene();
  52805. if (!this._effect) {
  52806. return;
  52807. }
  52808. if (this._options.uniforms.indexOf("world") !== -1) {
  52809. this._effect.setMatrix("world", world);
  52810. }
  52811. if (this._options.uniforms.indexOf("worldView") !== -1) {
  52812. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  52813. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  52814. }
  52815. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  52816. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  52817. }
  52818. };
  52819. ShaderMaterial.prototype.bind = function (world, mesh) {
  52820. // Std values
  52821. this.bindOnlyWorldMatrix(world);
  52822. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  52823. if (this._options.uniforms.indexOf("view") !== -1) {
  52824. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  52825. }
  52826. if (this._options.uniforms.indexOf("projection") !== -1) {
  52827. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  52828. }
  52829. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  52830. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  52831. }
  52832. // Bones
  52833. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  52834. var name;
  52835. // Texture
  52836. for (name in this._textures) {
  52837. this._effect.setTexture(name, this._textures[name]);
  52838. }
  52839. // Texture arrays
  52840. for (name in this._textureArrays) {
  52841. this._effect.setTextureArray(name, this._textureArrays[name]);
  52842. }
  52843. // Int
  52844. for (name in this._ints) {
  52845. this._effect.setInt(name, this._ints[name]);
  52846. }
  52847. // Float
  52848. for (name in this._floats) {
  52849. this._effect.setFloat(name, this._floats[name]);
  52850. }
  52851. // Floats
  52852. for (name in this._floatsArrays) {
  52853. this._effect.setArray(name, this._floatsArrays[name]);
  52854. }
  52855. // Color3
  52856. for (name in this._colors3) {
  52857. this._effect.setColor3(name, this._colors3[name]);
  52858. }
  52859. for (name in this._colors3Arrays) {
  52860. this._effect.setArray3(name, this._colors3Arrays[name]);
  52861. }
  52862. // Color4
  52863. for (name in this._colors4) {
  52864. var color = this._colors4[name];
  52865. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  52866. }
  52867. // Vector2
  52868. for (name in this._vectors2) {
  52869. this._effect.setVector2(name, this._vectors2[name]);
  52870. }
  52871. // Vector3
  52872. for (name in this._vectors3) {
  52873. this._effect.setVector3(name, this._vectors3[name]);
  52874. }
  52875. // Vector4
  52876. for (name in this._vectors4) {
  52877. this._effect.setVector4(name, this._vectors4[name]);
  52878. }
  52879. // Matrix
  52880. for (name in this._matrices) {
  52881. this._effect.setMatrix(name, this._matrices[name]);
  52882. }
  52883. // Matrix 3x3
  52884. for (name in this._matrices3x3) {
  52885. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  52886. }
  52887. // Matrix 2x2
  52888. for (name in this._matrices2x2) {
  52889. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  52890. }
  52891. // Vector2Array
  52892. for (name in this._vectors2Arrays) {
  52893. this._effect.setArray2(name, this._vectors2Arrays[name]);
  52894. }
  52895. // Vector3Array
  52896. for (name in this._vectors3Arrays) {
  52897. this._effect.setArray3(name, this._vectors3Arrays[name]);
  52898. }
  52899. }
  52900. this._afterBind(mesh);
  52901. };
  52902. ShaderMaterial.prototype.getActiveTextures = function () {
  52903. var activeTextures = _super.prototype.getActiveTextures.call(this);
  52904. for (var name in this._textures) {
  52905. activeTextures.push(this._textures[name]);
  52906. }
  52907. for (var name in this._textureArrays) {
  52908. var array = this._textureArrays[name];
  52909. for (var index = 0; index < array.length; index++) {
  52910. activeTextures.push(array[index]);
  52911. }
  52912. }
  52913. return activeTextures;
  52914. };
  52915. ShaderMaterial.prototype.hasTexture = function (texture) {
  52916. if (_super.prototype.hasTexture.call(this, texture)) {
  52917. return true;
  52918. }
  52919. for (var name in this._textures) {
  52920. if (this._textures[name] === texture) {
  52921. return true;
  52922. }
  52923. }
  52924. for (var name in this._textureArrays) {
  52925. var array = this._textureArrays[name];
  52926. for (var index = 0; index < array.length; index++) {
  52927. if (array[index] === texture) {
  52928. return true;
  52929. }
  52930. }
  52931. }
  52932. return false;
  52933. };
  52934. ShaderMaterial.prototype.clone = function (name) {
  52935. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  52936. return newShaderMaterial;
  52937. };
  52938. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  52939. if (forceDisposeTextures) {
  52940. var name;
  52941. for (name in this._textures) {
  52942. this._textures[name].dispose();
  52943. }
  52944. for (name in this._textureArrays) {
  52945. var array = this._textureArrays[name];
  52946. for (var index = 0; index < array.length; index++) {
  52947. array[index].dispose();
  52948. }
  52949. }
  52950. }
  52951. this._textures = {};
  52952. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  52953. };
  52954. ShaderMaterial.prototype.serialize = function () {
  52955. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  52956. serializationObject.customType = "BABYLON.ShaderMaterial";
  52957. serializationObject.options = this._options;
  52958. serializationObject.shaderPath = this._shaderPath;
  52959. var name;
  52960. // Texture
  52961. serializationObject.textures = {};
  52962. for (name in this._textures) {
  52963. serializationObject.textures[name] = this._textures[name].serialize();
  52964. }
  52965. // Texture arrays
  52966. serializationObject.textureArrays = {};
  52967. for (name in this._textureArrays) {
  52968. serializationObject.textureArrays[name] = [];
  52969. var array = this._textureArrays[name];
  52970. for (var index = 0; index < array.length; index++) {
  52971. serializationObject.textureArrays[name].push(array[index].serialize());
  52972. }
  52973. }
  52974. // Float
  52975. serializationObject.floats = {};
  52976. for (name in this._floats) {
  52977. serializationObject.floats[name] = this._floats[name];
  52978. }
  52979. // Float s
  52980. serializationObject.FloatArrays = {};
  52981. for (name in this._floatsArrays) {
  52982. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  52983. }
  52984. // Color3
  52985. serializationObject.colors3 = {};
  52986. for (name in this._colors3) {
  52987. serializationObject.colors3[name] = this._colors3[name].asArray();
  52988. }
  52989. // Color3 array
  52990. serializationObject.colors3Arrays = {};
  52991. for (name in this._colors3Arrays) {
  52992. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  52993. }
  52994. // Color4
  52995. serializationObject.colors4 = {};
  52996. for (name in this._colors4) {
  52997. serializationObject.colors4[name] = this._colors4[name].asArray();
  52998. }
  52999. // Vector2
  53000. serializationObject.vectors2 = {};
  53001. for (name in this._vectors2) {
  53002. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  53003. }
  53004. // Vector3
  53005. serializationObject.vectors3 = {};
  53006. for (name in this._vectors3) {
  53007. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  53008. }
  53009. // Vector4
  53010. serializationObject.vectors4 = {};
  53011. for (name in this._vectors4) {
  53012. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  53013. }
  53014. // Matrix
  53015. serializationObject.matrices = {};
  53016. for (name in this._matrices) {
  53017. serializationObject.matrices[name] = this._matrices[name].asArray();
  53018. }
  53019. // Matrix 3x3
  53020. serializationObject.matrices3x3 = {};
  53021. for (name in this._matrices3x3) {
  53022. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  53023. }
  53024. // Matrix 2x2
  53025. serializationObject.matrices2x2 = {};
  53026. for (name in this._matrices2x2) {
  53027. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  53028. }
  53029. // Vector2Array
  53030. serializationObject.vectors2Arrays = {};
  53031. for (name in this._vectors2Arrays) {
  53032. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  53033. }
  53034. // Vector3Array
  53035. serializationObject.vectors3Arrays = {};
  53036. for (name in this._vectors3Arrays) {
  53037. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  53038. }
  53039. return serializationObject;
  53040. };
  53041. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  53042. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  53043. var name;
  53044. // Texture
  53045. for (name in source.textures) {
  53046. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  53047. }
  53048. // Texture arrays
  53049. for (name in source.textureArrays) {
  53050. var array = source.textureArrays[name];
  53051. var textureArray = new Array();
  53052. for (var index = 0; index < array.length; index++) {
  53053. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  53054. }
  53055. material.setTextureArray(name, textureArray);
  53056. }
  53057. // Float
  53058. for (name in source.floats) {
  53059. material.setFloat(name, source.floats[name]);
  53060. }
  53061. // Float s
  53062. for (name in source.floatsArrays) {
  53063. material.setFloats(name, source.floatsArrays[name]);
  53064. }
  53065. // Color3
  53066. for (name in source.colors3) {
  53067. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  53068. }
  53069. // Color3 arrays
  53070. for (name in source.colors3Arrays) {
  53071. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  53072. if (i % 3 === 0) {
  53073. arr.push([num]);
  53074. }
  53075. else {
  53076. arr[arr.length - 1].push(num);
  53077. }
  53078. return arr;
  53079. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  53080. material.setColor3Array(name, colors);
  53081. }
  53082. // Color4
  53083. for (name in source.colors4) {
  53084. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  53085. }
  53086. // Vector2
  53087. for (name in source.vectors2) {
  53088. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  53089. }
  53090. // Vector3
  53091. for (name in source.vectors3) {
  53092. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  53093. }
  53094. // Vector4
  53095. for (name in source.vectors4) {
  53096. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  53097. }
  53098. // Matrix
  53099. for (name in source.matrices) {
  53100. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  53101. }
  53102. // Matrix 3x3
  53103. for (name in source.matrices3x3) {
  53104. material.setMatrix3x3(name, source.matrices3x3[name]);
  53105. }
  53106. // Matrix 2x2
  53107. for (name in source.matrices2x2) {
  53108. material.setMatrix2x2(name, source.matrices2x2[name]);
  53109. }
  53110. // Vector2Array
  53111. for (name in source.vectors2Arrays) {
  53112. material.setArray2(name, source.vectors2Arrays[name]);
  53113. }
  53114. // Vector3Array
  53115. for (name in source.vectors3Arrays) {
  53116. material.setArray3(name, source.vectors3Arrays[name]);
  53117. }
  53118. return material;
  53119. };
  53120. return ShaderMaterial;
  53121. }(BABYLON.Material));
  53122. BABYLON.ShaderMaterial = ShaderMaterial;
  53123. })(BABYLON || (BABYLON = {}));
  53124. //# sourceMappingURL=babylon.shaderMaterial.js.map
  53125. var BABYLON;
  53126. (function (BABYLON) {
  53127. var GroundMesh = /** @class */ (function (_super) {
  53128. __extends(GroundMesh, _super);
  53129. function GroundMesh(name, scene) {
  53130. var _this = _super.call(this, name, scene) || this;
  53131. _this.generateOctree = false;
  53132. return _this;
  53133. }
  53134. GroundMesh.prototype.getClassName = function () {
  53135. return "GroundMesh";
  53136. };
  53137. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  53138. get: function () {
  53139. return Math.min(this._subdivisionsX, this._subdivisionsY);
  53140. },
  53141. enumerable: true,
  53142. configurable: true
  53143. });
  53144. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  53145. get: function () {
  53146. return this._subdivisionsX;
  53147. },
  53148. enumerable: true,
  53149. configurable: true
  53150. });
  53151. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  53152. get: function () {
  53153. return this._subdivisionsY;
  53154. },
  53155. enumerable: true,
  53156. configurable: true
  53157. });
  53158. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  53159. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  53160. this._subdivisionsX = chunksCount;
  53161. this._subdivisionsY = chunksCount;
  53162. this.subdivide(chunksCount);
  53163. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  53164. };
  53165. /**
  53166. * Returns a height (y) value in the Worl system :
  53167. * the ground altitude at the coordinates (x, z) expressed in the World system.
  53168. * Returns the ground y position if (x, z) are outside the ground surface.
  53169. */
  53170. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  53171. var world = this.getWorldMatrix();
  53172. var invMat = BABYLON.Tmp.Matrix[5];
  53173. world.invertToRef(invMat);
  53174. var tmpVect = BABYLON.Tmp.Vector3[8];
  53175. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  53176. x = tmpVect.x;
  53177. z = tmpVect.z;
  53178. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53179. return this.position.y;
  53180. }
  53181. if (!this._heightQuads || this._heightQuads.length == 0) {
  53182. this._initHeightQuads();
  53183. this._computeHeightQuads();
  53184. }
  53185. var facet = this._getFacetAt(x, z);
  53186. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  53187. // return y in the World system
  53188. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  53189. return tmpVect.y;
  53190. };
  53191. /**
  53192. * Returns a normalized vector (Vector3) orthogonal to the ground
  53193. * at the ground coordinates (x, z) expressed in the World system.
  53194. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  53195. */
  53196. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  53197. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  53198. this.getNormalAtCoordinatesToRef(x, z, normal);
  53199. return normal;
  53200. };
  53201. /**
  53202. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  53203. * at the ground coordinates (x, z) expressed in the World system.
  53204. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  53205. * Returns the GroundMesh.
  53206. */
  53207. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  53208. var world = this.getWorldMatrix();
  53209. var tmpMat = BABYLON.Tmp.Matrix[5];
  53210. world.invertToRef(tmpMat);
  53211. var tmpVect = BABYLON.Tmp.Vector3[8];
  53212. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  53213. x = tmpVect.x;
  53214. z = tmpVect.z;
  53215. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53216. return this;
  53217. }
  53218. if (!this._heightQuads || this._heightQuads.length == 0) {
  53219. this._initHeightQuads();
  53220. this._computeHeightQuads();
  53221. }
  53222. var facet = this._getFacetAt(x, z);
  53223. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  53224. return this;
  53225. };
  53226. /**
  53227. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  53228. * if the ground has been updated.
  53229. * This can be used in the render loop.
  53230. * Returns the GroundMesh.
  53231. */
  53232. GroundMesh.prototype.updateCoordinateHeights = function () {
  53233. if (!this._heightQuads || this._heightQuads.length == 0) {
  53234. this._initHeightQuads();
  53235. }
  53236. this._computeHeightQuads();
  53237. return this;
  53238. };
  53239. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  53240. GroundMesh.prototype._getFacetAt = function (x, z) {
  53241. // retrieve col and row from x, z coordinates in the ground local system
  53242. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  53243. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  53244. var quad = this._heightQuads[row * this._subdivisionsX + col];
  53245. var facet;
  53246. if (z < quad.slope.x * x + quad.slope.y) {
  53247. facet = quad.facet1;
  53248. }
  53249. else {
  53250. facet = quad.facet2;
  53251. }
  53252. return facet;
  53253. };
  53254. // Creates and populates the heightMap array with "facet" elements :
  53255. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  53256. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53257. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53258. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53259. // Returns the GroundMesh.
  53260. GroundMesh.prototype._initHeightQuads = function () {
  53261. var subdivisionsX = this._subdivisionsX;
  53262. var subdivisionsY = this._subdivisionsY;
  53263. this._heightQuads = new Array();
  53264. for (var row = 0; row < subdivisionsY; row++) {
  53265. for (var col = 0; col < subdivisionsX; col++) {
  53266. 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) };
  53267. this._heightQuads[row * subdivisionsX + col] = quad;
  53268. }
  53269. }
  53270. return this;
  53271. };
  53272. // Compute each quad element values and update the the heightMap array :
  53273. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53274. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53275. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53276. // Returns the GroundMesh.
  53277. GroundMesh.prototype._computeHeightQuads = function () {
  53278. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53279. if (!positions) {
  53280. return this;
  53281. }
  53282. var v1 = BABYLON.Tmp.Vector3[3];
  53283. var v2 = BABYLON.Tmp.Vector3[2];
  53284. var v3 = BABYLON.Tmp.Vector3[1];
  53285. var v4 = BABYLON.Tmp.Vector3[0];
  53286. var v1v2 = BABYLON.Tmp.Vector3[4];
  53287. var v1v3 = BABYLON.Tmp.Vector3[5];
  53288. var v1v4 = BABYLON.Tmp.Vector3[6];
  53289. var norm1 = BABYLON.Tmp.Vector3[7];
  53290. var norm2 = BABYLON.Tmp.Vector3[8];
  53291. var i = 0;
  53292. var j = 0;
  53293. var k = 0;
  53294. var cd = 0; // 2D slope coefficient : z = cd * x + h
  53295. var h = 0;
  53296. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  53297. var d2 = 0;
  53298. var subdivisionsX = this._subdivisionsX;
  53299. var subdivisionsY = this._subdivisionsY;
  53300. for (var row = 0; row < subdivisionsY; row++) {
  53301. for (var col = 0; col < subdivisionsX; col++) {
  53302. i = col * 3;
  53303. j = row * (subdivisionsX + 1) * 3;
  53304. k = (row + 1) * (subdivisionsX + 1) * 3;
  53305. v1.x = positions[j + i];
  53306. v1.y = positions[j + i + 1];
  53307. v1.z = positions[j + i + 2];
  53308. v2.x = positions[j + i + 3];
  53309. v2.y = positions[j + i + 4];
  53310. v2.z = positions[j + i + 5];
  53311. v3.x = positions[k + i];
  53312. v3.y = positions[k + i + 1];
  53313. v3.z = positions[k + i + 2];
  53314. v4.x = positions[k + i + 3];
  53315. v4.y = positions[k + i + 4];
  53316. v4.z = positions[k + i + 5];
  53317. // 2D slope V1V4
  53318. cd = (v4.z - v1.z) / (v4.x - v1.x);
  53319. h = v1.z - cd * v1.x; // v1 belongs to the slope
  53320. // facet equations :
  53321. // we compute each facet normal vector
  53322. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  53323. // we compute the value d by applying the equation to v1 which belongs to the plane
  53324. // then we store the facet equation in a Vector4
  53325. v2.subtractToRef(v1, v1v2);
  53326. v3.subtractToRef(v1, v1v3);
  53327. v4.subtractToRef(v1, v1v4);
  53328. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  53329. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  53330. norm1.normalize();
  53331. norm2.normalize();
  53332. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  53333. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  53334. var quad = this._heightQuads[row * subdivisionsX + col];
  53335. quad.slope.copyFromFloats(cd, h);
  53336. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  53337. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  53338. }
  53339. }
  53340. return this;
  53341. };
  53342. GroundMesh.prototype.serialize = function (serializationObject) {
  53343. _super.prototype.serialize.call(this, serializationObject);
  53344. serializationObject.subdivisionsX = this._subdivisionsX;
  53345. serializationObject.subdivisionsY = this._subdivisionsY;
  53346. serializationObject.minX = this._minX;
  53347. serializationObject.maxX = this._maxX;
  53348. serializationObject.minZ = this._minZ;
  53349. serializationObject.maxZ = this._maxZ;
  53350. serializationObject.width = this._width;
  53351. serializationObject.height = this._height;
  53352. };
  53353. GroundMesh.Parse = function (parsedMesh, scene) {
  53354. var result = new GroundMesh(parsedMesh.name, scene);
  53355. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  53356. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  53357. result._minX = parsedMesh.minX;
  53358. result._maxX = parsedMesh.maxX;
  53359. result._minZ = parsedMesh.minZ;
  53360. result._maxZ = parsedMesh.maxZ;
  53361. result._width = parsedMesh.width;
  53362. result._height = parsedMesh.height;
  53363. return result;
  53364. };
  53365. return GroundMesh;
  53366. }(BABYLON.Mesh));
  53367. BABYLON.GroundMesh = GroundMesh;
  53368. })(BABYLON || (BABYLON = {}));
  53369. //# sourceMappingURL=babylon.groundMesh.js.map
  53370. var BABYLON;
  53371. (function (BABYLON) {
  53372. /**
  53373. * Creates an instance based on a source mesh.
  53374. */
  53375. var InstancedMesh = /** @class */ (function (_super) {
  53376. __extends(InstancedMesh, _super);
  53377. function InstancedMesh(name, source) {
  53378. var _this = _super.call(this, name, source.getScene()) || this;
  53379. source.instances.push(_this);
  53380. _this._sourceMesh = source;
  53381. _this.position.copyFrom(source.position);
  53382. _this.rotation.copyFrom(source.rotation);
  53383. _this.scaling.copyFrom(source.scaling);
  53384. if (source.rotationQuaternion) {
  53385. _this.rotationQuaternion = source.rotationQuaternion.clone();
  53386. }
  53387. _this.infiniteDistance = source.infiniteDistance;
  53388. _this.setPivotMatrix(source.getPivotMatrix());
  53389. _this.refreshBoundingInfo();
  53390. _this._syncSubMeshes();
  53391. return _this;
  53392. }
  53393. /**
  53394. * Returns the string "InstancedMesh".
  53395. */
  53396. InstancedMesh.prototype.getClassName = function () {
  53397. return "InstancedMesh";
  53398. };
  53399. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  53400. // Methods
  53401. get: function () {
  53402. return this._sourceMesh.receiveShadows;
  53403. },
  53404. enumerable: true,
  53405. configurable: true
  53406. });
  53407. Object.defineProperty(InstancedMesh.prototype, "material", {
  53408. get: function () {
  53409. return this._sourceMesh.material;
  53410. },
  53411. enumerable: true,
  53412. configurable: true
  53413. });
  53414. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  53415. get: function () {
  53416. return this._sourceMesh.visibility;
  53417. },
  53418. enumerable: true,
  53419. configurable: true
  53420. });
  53421. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  53422. get: function () {
  53423. return this._sourceMesh.skeleton;
  53424. },
  53425. enumerable: true,
  53426. configurable: true
  53427. });
  53428. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  53429. get: function () {
  53430. return this._sourceMesh.renderingGroupId;
  53431. },
  53432. enumerable: true,
  53433. configurable: true
  53434. });
  53435. /**
  53436. * Returns the total number of vertices (integer).
  53437. */
  53438. InstancedMesh.prototype.getTotalVertices = function () {
  53439. return this._sourceMesh.getTotalVertices();
  53440. };
  53441. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  53442. get: function () {
  53443. return this._sourceMesh;
  53444. },
  53445. enumerable: true,
  53446. configurable: true
  53447. });
  53448. /**
  53449. * Is this node ready to be used/rendered
  53450. * @return {boolean} is it ready
  53451. */
  53452. InstancedMesh.prototype.isReady = function () {
  53453. return this._sourceMesh.isReady(true);
  53454. };
  53455. /**
  53456. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  53457. */
  53458. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  53459. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  53460. };
  53461. /**
  53462. * Sets the vertex data of the mesh geometry for the requested `kind`.
  53463. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  53464. * The `data` are either a numeric array either a Float32Array.
  53465. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  53466. * 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).
  53467. * Note that a new underlying VertexBuffer object is created each call.
  53468. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  53469. *
  53470. * Possible `kind` values :
  53471. * - BABYLON.VertexBuffer.PositionKind
  53472. * - BABYLON.VertexBuffer.UVKind
  53473. * - BABYLON.VertexBuffer.UV2Kind
  53474. * - BABYLON.VertexBuffer.UV3Kind
  53475. * - BABYLON.VertexBuffer.UV4Kind
  53476. * - BABYLON.VertexBuffer.UV5Kind
  53477. * - BABYLON.VertexBuffer.UV6Kind
  53478. * - BABYLON.VertexBuffer.ColorKind
  53479. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53480. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53481. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53482. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53483. *
  53484. * Returns the Mesh.
  53485. */
  53486. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  53487. if (this.sourceMesh) {
  53488. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  53489. }
  53490. return this.sourceMesh;
  53491. };
  53492. /**
  53493. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  53494. * If the mesh has no geometry, it is simply returned as it is.
  53495. * The `data` are either a numeric array either a Float32Array.
  53496. * No new underlying VertexBuffer object is created.
  53497. * 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.
  53498. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  53499. *
  53500. * Possible `kind` values :
  53501. * - BABYLON.VertexBuffer.PositionKind
  53502. * - BABYLON.VertexBuffer.UVKind
  53503. * - BABYLON.VertexBuffer.UV2Kind
  53504. * - BABYLON.VertexBuffer.UV3Kind
  53505. * - BABYLON.VertexBuffer.UV4Kind
  53506. * - BABYLON.VertexBuffer.UV5Kind
  53507. * - BABYLON.VertexBuffer.UV6Kind
  53508. * - BABYLON.VertexBuffer.ColorKind
  53509. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53510. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53511. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53512. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53513. *
  53514. * Returns the Mesh.
  53515. */
  53516. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  53517. if (this.sourceMesh) {
  53518. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  53519. }
  53520. return this.sourceMesh;
  53521. };
  53522. /**
  53523. * Sets the mesh indices.
  53524. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  53525. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  53526. * This method creates a new index buffer each call.
  53527. * Returns the Mesh.
  53528. */
  53529. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  53530. if (totalVertices === void 0) { totalVertices = null; }
  53531. if (this.sourceMesh) {
  53532. this.sourceMesh.setIndices(indices, totalVertices);
  53533. }
  53534. return this.sourceMesh;
  53535. };
  53536. /**
  53537. * Boolean : True if the mesh owns the requested kind of data.
  53538. */
  53539. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  53540. return this._sourceMesh.isVerticesDataPresent(kind);
  53541. };
  53542. /**
  53543. * Returns an array of indices (IndicesArray).
  53544. */
  53545. InstancedMesh.prototype.getIndices = function () {
  53546. return this._sourceMesh.getIndices();
  53547. };
  53548. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  53549. get: function () {
  53550. return this._sourceMesh._positions;
  53551. },
  53552. enumerable: true,
  53553. configurable: true
  53554. });
  53555. /**
  53556. * Sets a new updated BoundingInfo to the mesh.
  53557. * Returns the mesh.
  53558. */
  53559. InstancedMesh.prototype.refreshBoundingInfo = function () {
  53560. var meshBB = this._sourceMesh.getBoundingInfo();
  53561. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  53562. this._updateBoundingInfo();
  53563. return this;
  53564. };
  53565. InstancedMesh.prototype._preActivate = function () {
  53566. if (this._currentLOD) {
  53567. this._currentLOD._preActivate();
  53568. }
  53569. return this;
  53570. };
  53571. InstancedMesh.prototype._activate = function (renderId) {
  53572. if (this._currentLOD) {
  53573. this._currentLOD._registerInstanceForRenderId(this, renderId);
  53574. }
  53575. return this;
  53576. };
  53577. /**
  53578. * Returns the current associated LOD AbstractMesh.
  53579. */
  53580. InstancedMesh.prototype.getLOD = function (camera) {
  53581. if (!camera) {
  53582. return this;
  53583. }
  53584. var boundingInfo = this.getBoundingInfo();
  53585. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  53586. if (this._currentLOD === this.sourceMesh) {
  53587. return this;
  53588. }
  53589. return this._currentLOD;
  53590. };
  53591. InstancedMesh.prototype._syncSubMeshes = function () {
  53592. this.releaseSubMeshes();
  53593. if (this._sourceMesh.subMeshes) {
  53594. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  53595. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  53596. }
  53597. }
  53598. return this;
  53599. };
  53600. InstancedMesh.prototype._generatePointsArray = function () {
  53601. return this._sourceMesh._generatePointsArray();
  53602. };
  53603. /**
  53604. * Creates a new InstancedMesh from the current mesh.
  53605. * - name (string) : the cloned mesh name
  53606. * - newParent (optional Node) : the optional Node to parent the clone to.
  53607. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  53608. *
  53609. * Returns the clone.
  53610. */
  53611. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53612. var result = this._sourceMesh.createInstance(name);
  53613. // Deep copy
  53614. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  53615. // Bounding info
  53616. this.refreshBoundingInfo();
  53617. // Parent
  53618. if (newParent) {
  53619. result.parent = newParent;
  53620. }
  53621. if (!doNotCloneChildren) {
  53622. // Children
  53623. for (var index = 0; index < this.getScene().meshes.length; index++) {
  53624. var mesh = this.getScene().meshes[index];
  53625. if (mesh.parent === this) {
  53626. mesh.clone(mesh.name, result);
  53627. }
  53628. }
  53629. }
  53630. result.computeWorldMatrix(true);
  53631. return result;
  53632. };
  53633. /**
  53634. * Disposes the InstancedMesh.
  53635. * Returns nothing.
  53636. */
  53637. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  53638. // Remove from mesh
  53639. var index = this._sourceMesh.instances.indexOf(this);
  53640. this._sourceMesh.instances.splice(index, 1);
  53641. _super.prototype.dispose.call(this, doNotRecurse);
  53642. };
  53643. return InstancedMesh;
  53644. }(BABYLON.AbstractMesh));
  53645. BABYLON.InstancedMesh = InstancedMesh;
  53646. })(BABYLON || (BABYLON = {}));
  53647. //# sourceMappingURL=babylon.instancedMesh.js.map
  53648. var BABYLON;
  53649. (function (BABYLON) {
  53650. var LinesMesh = /** @class */ (function (_super) {
  53651. __extends(LinesMesh, _super);
  53652. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  53653. if (scene === void 0) { scene = null; }
  53654. if (parent === void 0) { parent = null; }
  53655. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  53656. _this.useVertexColor = useVertexColor;
  53657. _this.useVertexAlpha = useVertexAlpha;
  53658. _this.color = new BABYLON.Color3(1, 1, 1);
  53659. _this.alpha = 1;
  53660. if (source) {
  53661. _this.color = source.color.clone();
  53662. _this.alpha = source.alpha;
  53663. _this.useVertexColor = source.useVertexColor;
  53664. _this.useVertexAlpha = source.useVertexAlpha;
  53665. }
  53666. _this._intersectionThreshold = 0.1;
  53667. var defines = [];
  53668. var options = {
  53669. attributes: [BABYLON.VertexBuffer.PositionKind],
  53670. uniforms: ["world", "viewProjection"],
  53671. needAlphaBlending: true,
  53672. defines: defines
  53673. };
  53674. if (useVertexAlpha === false) {
  53675. options.needAlphaBlending = false;
  53676. }
  53677. if (!useVertexColor) {
  53678. options.uniforms.push("color");
  53679. }
  53680. else {
  53681. options.defines.push("#define VERTEXCOLOR");
  53682. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  53683. }
  53684. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  53685. return _this;
  53686. }
  53687. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  53688. /**
  53689. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53690. * This margin is expressed in world space coordinates, so its value may vary.
  53691. * Default value is 0.1
  53692. * @returns the intersection Threshold value.
  53693. */
  53694. get: function () {
  53695. return this._intersectionThreshold;
  53696. },
  53697. /**
  53698. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53699. * This margin is expressed in world space coordinates, so its value may vary.
  53700. * @param value the new threshold to apply
  53701. */
  53702. set: function (value) {
  53703. if (this._intersectionThreshold === value) {
  53704. return;
  53705. }
  53706. this._intersectionThreshold = value;
  53707. if (this.geometry) {
  53708. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  53709. }
  53710. },
  53711. enumerable: true,
  53712. configurable: true
  53713. });
  53714. /**
  53715. * Returns the string "LineMesh"
  53716. */
  53717. LinesMesh.prototype.getClassName = function () {
  53718. return "LinesMesh";
  53719. };
  53720. Object.defineProperty(LinesMesh.prototype, "material", {
  53721. get: function () {
  53722. return this._colorShader;
  53723. },
  53724. set: function (value) {
  53725. // Do nothing
  53726. },
  53727. enumerable: true,
  53728. configurable: true
  53729. });
  53730. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  53731. get: function () {
  53732. return false;
  53733. },
  53734. enumerable: true,
  53735. configurable: true
  53736. });
  53737. LinesMesh.prototype.createInstance = function (name) {
  53738. throw new Error("LinesMeshes do not support createInstance.");
  53739. };
  53740. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  53741. if (!this._geometry) {
  53742. return this;
  53743. }
  53744. // VBOs
  53745. this._geometry._bind(this._colorShader.getEffect());
  53746. // Color
  53747. if (!this.useVertexColor) {
  53748. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  53749. }
  53750. return this;
  53751. };
  53752. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  53753. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  53754. return this;
  53755. }
  53756. var engine = this.getScene().getEngine();
  53757. // Draw order
  53758. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  53759. return this;
  53760. };
  53761. LinesMesh.prototype.dispose = function (doNotRecurse) {
  53762. this._colorShader.dispose();
  53763. _super.prototype.dispose.call(this, doNotRecurse);
  53764. };
  53765. /**
  53766. * Returns a new LineMesh object cloned from the current one.
  53767. */
  53768. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53769. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  53770. };
  53771. return LinesMesh;
  53772. }(BABYLON.Mesh));
  53773. BABYLON.LinesMesh = LinesMesh;
  53774. })(BABYLON || (BABYLON = {}));
  53775. //# sourceMappingURL=babylon.linesMesh.js.map
  53776. var BABYLON;
  53777. (function (BABYLON) {
  53778. var MeshBuilder = /** @class */ (function () {
  53779. function MeshBuilder() {
  53780. }
  53781. MeshBuilder.updateSideOrientation = function (orientation) {
  53782. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  53783. return BABYLON.Mesh.DOUBLESIDE;
  53784. }
  53785. if (orientation === undefined || orientation === null) {
  53786. return BABYLON.Mesh.FRONTSIDE;
  53787. }
  53788. return orientation;
  53789. };
  53790. /**
  53791. * Creates a box mesh.
  53792. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  53793. * The parameter `size` sets the size (float) of each box side (default 1).
  53794. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  53795. * 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).
  53796. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  53797. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53798. * 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).
  53799. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53800. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53801. */
  53802. MeshBuilder.CreateBox = function (name, options, scene) {
  53803. if (scene === void 0) { scene = null; }
  53804. var box = new BABYLON.Mesh(name, scene);
  53805. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53806. box._originalBuilderSideOrientation = options.sideOrientation;
  53807. var vertexData = BABYLON.VertexData.CreateBox(options);
  53808. vertexData.applyToMesh(box, options.updatable);
  53809. return box;
  53810. };
  53811. /**
  53812. * Creates a sphere mesh.
  53813. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  53814. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  53815. * 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`).
  53816. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  53817. * 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
  53818. * 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).
  53819. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53820. * 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).
  53821. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53822. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53823. */
  53824. MeshBuilder.CreateSphere = function (name, options, scene) {
  53825. var sphere = new BABYLON.Mesh(name, scene);
  53826. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53827. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53828. var vertexData = BABYLON.VertexData.CreateSphere(options);
  53829. vertexData.applyToMesh(sphere, options.updatable);
  53830. return sphere;
  53831. };
  53832. /**
  53833. * Creates a plane polygonal mesh. By default, this is a disc.
  53834. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  53835. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  53836. * 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.
  53837. * 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
  53838. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53839. * 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).
  53840. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53841. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53842. */
  53843. MeshBuilder.CreateDisc = function (name, options, scene) {
  53844. if (scene === void 0) { scene = null; }
  53845. var disc = new BABYLON.Mesh(name, scene);
  53846. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53847. disc._originalBuilderSideOrientation = options.sideOrientation;
  53848. var vertexData = BABYLON.VertexData.CreateDisc(options);
  53849. vertexData.applyToMesh(disc, options.updatable);
  53850. return disc;
  53851. };
  53852. /**
  53853. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  53854. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  53855. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  53856. * 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`).
  53857. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  53858. * 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.
  53859. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53860. * 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).
  53861. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53862. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53863. */
  53864. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  53865. var sphere = new BABYLON.Mesh(name, scene);
  53866. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53867. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53868. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  53869. vertexData.applyToMesh(sphere, options.updatable);
  53870. return sphere;
  53871. };
  53872. ;
  53873. /**
  53874. * Creates a ribbon mesh.
  53875. * 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.
  53876. *
  53877. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  53878. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  53879. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  53880. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  53881. * 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.
  53882. * 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.
  53883. * 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
  53884. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53885. * 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).
  53886. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53887. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  53888. * 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.
  53889. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  53890. * 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
  53891. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  53892. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  53893. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53894. */
  53895. MeshBuilder.CreateRibbon = function (name, options, scene) {
  53896. if (scene === void 0) { scene = null; }
  53897. var pathArray = options.pathArray;
  53898. var closeArray = options.closeArray;
  53899. var closePath = options.closePath;
  53900. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53901. var instance = options.instance;
  53902. var updatable = options.updatable;
  53903. if (instance) {
  53904. // positionFunction : ribbon case
  53905. // only pathArray and sideOrientation parameters are taken into account for positions update
  53906. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  53907. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  53908. var positionFunction = function (positions) {
  53909. var minlg = pathArray[0].length;
  53910. var i = 0;
  53911. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  53912. for (var si = 1; si <= ns; si++) {
  53913. for (var p = 0; p < pathArray.length; p++) {
  53914. var path = pathArray[p];
  53915. var l = path.length;
  53916. minlg = (minlg < l) ? minlg : l;
  53917. var j = 0;
  53918. while (j < minlg) {
  53919. positions[i] = path[j].x;
  53920. positions[i + 1] = path[j].y;
  53921. positions[i + 2] = path[j].z;
  53922. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  53923. BABYLON.Tmp.Vector3[0].x = path[j].x;
  53924. }
  53925. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  53926. BABYLON.Tmp.Vector3[1].x = path[j].x;
  53927. }
  53928. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  53929. BABYLON.Tmp.Vector3[0].y = path[j].y;
  53930. }
  53931. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  53932. BABYLON.Tmp.Vector3[1].y = path[j].y;
  53933. }
  53934. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  53935. BABYLON.Tmp.Vector3[0].z = path[j].z;
  53936. }
  53937. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  53938. BABYLON.Tmp.Vector3[1].z = path[j].z;
  53939. }
  53940. j++;
  53941. i += 3;
  53942. }
  53943. if (instance._closePath) {
  53944. positions[i] = path[0].x;
  53945. positions[i + 1] = path[0].y;
  53946. positions[i + 2] = path[0].z;
  53947. i += 3;
  53948. }
  53949. }
  53950. }
  53951. };
  53952. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53953. positionFunction(positions);
  53954. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  53955. instance._boundingInfo.update(instance._worldMatrix);
  53956. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  53957. if (options.colors) {
  53958. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53959. for (var c = 0; c < options.colors.length; c++) {
  53960. colors[c * 4] = options.colors[c].r;
  53961. colors[c * 4 + 1] = options.colors[c].g;
  53962. colors[c * 4 + 2] = options.colors[c].b;
  53963. colors[c * 4 + 3] = options.colors[c].a;
  53964. }
  53965. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  53966. }
  53967. if (options.uvs) {
  53968. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53969. for (var i = 0; i < options.uvs.length; i++) {
  53970. uvs[i * 2] = options.uvs[i].x;
  53971. uvs[i * 2 + 1] = options.uvs[i].y;
  53972. }
  53973. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  53974. }
  53975. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  53976. var indices = instance.getIndices();
  53977. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53978. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  53979. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  53980. if (instance._closePath) {
  53981. var indexFirst = 0;
  53982. var indexLast = 0;
  53983. for (var p = 0; p < pathArray.length; p++) {
  53984. indexFirst = instance._idx[p] * 3;
  53985. if (p + 1 < pathArray.length) {
  53986. indexLast = (instance._idx[p + 1] - 1) * 3;
  53987. }
  53988. else {
  53989. indexLast = normals.length - 3;
  53990. }
  53991. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  53992. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  53993. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  53994. normals[indexLast] = normals[indexFirst];
  53995. normals[indexLast + 1] = normals[indexFirst + 1];
  53996. normals[indexLast + 2] = normals[indexFirst + 2];
  53997. }
  53998. }
  53999. if (!(instance.areNormalsFrozen)) {
  54000. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  54001. }
  54002. }
  54003. return instance;
  54004. }
  54005. else {
  54006. var ribbon = new BABYLON.Mesh(name, scene);
  54007. ribbon._originalBuilderSideOrientation = sideOrientation;
  54008. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  54009. if (closePath) {
  54010. ribbon._idx = vertexData._idx;
  54011. }
  54012. ribbon._closePath = closePath;
  54013. ribbon._closeArray = closeArray;
  54014. vertexData.applyToMesh(ribbon, updatable);
  54015. return ribbon;
  54016. }
  54017. };
  54018. /**
  54019. * Creates a cylinder or a cone mesh.
  54020. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  54021. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  54022. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  54023. * 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.
  54024. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  54025. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  54026. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  54027. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  54028. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  54029. * 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).
  54030. * 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
  54031. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  54032. * 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
  54033. * 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.
  54034. * If `enclose` is false, a ring surface is one element.
  54035. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  54036. * 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
  54037. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54038. * 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).
  54039. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54040. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54041. */
  54042. MeshBuilder.CreateCylinder = function (name, options, scene) {
  54043. var cylinder = new BABYLON.Mesh(name, scene);
  54044. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54045. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  54046. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  54047. vertexData.applyToMesh(cylinder, options.updatable);
  54048. return cylinder;
  54049. };
  54050. /**
  54051. * Creates a torus mesh.
  54052. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  54053. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  54054. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  54055. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  54056. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54057. * 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).
  54058. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54059. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54060. */
  54061. MeshBuilder.CreateTorus = function (name, options, scene) {
  54062. var torus = new BABYLON.Mesh(name, scene);
  54063. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54064. torus._originalBuilderSideOrientation = options.sideOrientation;
  54065. var vertexData = BABYLON.VertexData.CreateTorus(options);
  54066. vertexData.applyToMesh(torus, options.updatable);
  54067. return torus;
  54068. };
  54069. /**
  54070. * Creates a torus knot mesh.
  54071. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  54072. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  54073. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  54074. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  54075. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  54076. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54077. * 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).
  54078. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54079. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54080. */
  54081. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  54082. var torusKnot = new BABYLON.Mesh(name, scene);
  54083. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54084. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  54085. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  54086. vertexData.applyToMesh(torusKnot, options.updatable);
  54087. return torusKnot;
  54088. };
  54089. /**
  54090. * Creates a line system mesh.
  54091. * A line system is a pool of many lines gathered in a single mesh.
  54092. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  54093. * 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.
  54094. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  54095. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  54096. * 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
  54097. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  54098. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  54099. * 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
  54100. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  54101. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54102. */
  54103. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  54104. var instance = options.instance;
  54105. var lines = options.lines;
  54106. var colors = options.colors;
  54107. if (instance) {
  54108. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54109. var vertexColor;
  54110. var lineColors;
  54111. if (colors) {
  54112. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54113. }
  54114. var i = 0;
  54115. var c = 0;
  54116. for (var l = 0; l < lines.length; l++) {
  54117. var points = lines[l];
  54118. for (var p = 0; p < points.length; p++) {
  54119. positions[i] = points[p].x;
  54120. positions[i + 1] = points[p].y;
  54121. positions[i + 2] = points[p].z;
  54122. if (colors && vertexColor) {
  54123. lineColors = colors[l];
  54124. vertexColor[c] = lineColors[p].r;
  54125. vertexColor[c + 1] = lineColors[p].g;
  54126. vertexColor[c + 2] = lineColors[p].b;
  54127. vertexColor[c + 3] = lineColors[p].a;
  54128. c += 4;
  54129. }
  54130. i += 3;
  54131. }
  54132. }
  54133. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54134. if (colors && vertexColor) {
  54135. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  54136. }
  54137. return instance;
  54138. }
  54139. // line system creation
  54140. var useVertexColor = (colors) ? true : false;
  54141. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  54142. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  54143. vertexData.applyToMesh(lineSystem, options.updatable);
  54144. return lineSystem;
  54145. };
  54146. /**
  54147. * Creates a line mesh.
  54148. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  54149. * 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.
  54150. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54151. * The parameter `points` is an array successive Vector3.
  54152. * 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
  54153. * The optional parameter `colors` is an array of successive Color4, one per line point.
  54154. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  54155. * When updating an instance, remember that only point positions can change, not the number of points.
  54156. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54157. */
  54158. MeshBuilder.CreateLines = function (name, options, scene) {
  54159. if (scene === void 0) { scene = null; }
  54160. var colors = (options.colors) ? [options.colors] : null;
  54161. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  54162. return lines;
  54163. };
  54164. /**
  54165. * Creates a dashed line mesh.
  54166. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  54167. * 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.
  54168. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54169. * The parameter `points` is an array successive Vector3.
  54170. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  54171. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  54172. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  54173. * 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
  54174. * When updating an instance, remember that only point positions can change, not the number of points.
  54175. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54176. */
  54177. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  54178. if (scene === void 0) { scene = null; }
  54179. var points = options.points;
  54180. var instance = options.instance;
  54181. var gapSize = options.gapSize || 1;
  54182. var dashSize = options.dashSize || 3;
  54183. if (instance) {
  54184. var positionFunction = function (positions) {
  54185. var curvect = BABYLON.Vector3.Zero();
  54186. var nbSeg = positions.length / 6;
  54187. var lg = 0;
  54188. var nb = 0;
  54189. var shft = 0;
  54190. var dashshft = 0;
  54191. var curshft = 0;
  54192. var p = 0;
  54193. var i = 0;
  54194. var j = 0;
  54195. for (i = 0; i < points.length - 1; i++) {
  54196. points[i + 1].subtractToRef(points[i], curvect);
  54197. lg += curvect.length();
  54198. }
  54199. shft = lg / nbSeg;
  54200. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  54201. for (i = 0; i < points.length - 1; i++) {
  54202. points[i + 1].subtractToRef(points[i], curvect);
  54203. nb = Math.floor(curvect.length() / shft);
  54204. curvect.normalize();
  54205. j = 0;
  54206. while (j < nb && p < positions.length) {
  54207. curshft = shft * j;
  54208. positions[p] = points[i].x + curshft * curvect.x;
  54209. positions[p + 1] = points[i].y + curshft * curvect.y;
  54210. positions[p + 2] = points[i].z + curshft * curvect.z;
  54211. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  54212. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  54213. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  54214. p += 6;
  54215. j++;
  54216. }
  54217. }
  54218. while (p < positions.length) {
  54219. positions[p] = points[i].x;
  54220. positions[p + 1] = points[i].y;
  54221. positions[p + 2] = points[i].z;
  54222. p += 3;
  54223. }
  54224. };
  54225. instance.updateMeshPositions(positionFunction, false);
  54226. return instance;
  54227. }
  54228. // dashed lines creation
  54229. var dashedLines = new BABYLON.LinesMesh(name, scene);
  54230. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  54231. vertexData.applyToMesh(dashedLines, options.updatable);
  54232. dashedLines.dashSize = dashSize;
  54233. dashedLines.gapSize = gapSize;
  54234. return dashedLines;
  54235. };
  54236. /**
  54237. * Creates an extruded shape mesh.
  54238. * 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.
  54239. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  54240. *
  54241. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54242. * 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
  54243. * extruded along the Z axis.
  54244. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54245. * 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.
  54246. * The parameter `scale` (float, default 1) is the value to scale the shape.
  54247. * 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
  54248. * 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
  54249. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54250. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54251. * 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).
  54252. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54253. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54254. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54255. */
  54256. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  54257. if (scene === void 0) { scene = null; }
  54258. var path = options.path;
  54259. var shape = options.shape;
  54260. var scale = options.scale || 1;
  54261. var rotation = options.rotation || 0;
  54262. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54263. var updatable = options.updatable;
  54264. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54265. var instance = options.instance || null;
  54266. var invertUV = options.invertUV || false;
  54267. 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);
  54268. };
  54269. /**
  54270. * Creates an custom extruded shape mesh.
  54271. * 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.
  54272. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  54273. *
  54274. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54275. * 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
  54276. * extruded along the Z axis.
  54277. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54278. * 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
  54279. * and the distance of this point from the begining of the path :
  54280. * ```javascript
  54281. * var rotationFunction = function(i, distance) {
  54282. * // do things
  54283. * return rotationValue; }
  54284. * ```
  54285. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  54286. * 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
  54287. * and the distance of this point from the begining of the path :
  54288. * ```javascript
  54289. * var scaleFunction = function(i, distance) {
  54290. * // do things
  54291. * return scaleValue;}
  54292. * ```
  54293. * It must returns a float value that will be the scale value applied to the shape on each path point.
  54294. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  54295. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  54296. * 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
  54297. * 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
  54298. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54299. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54300. * 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).
  54301. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54302. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54304. */
  54305. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  54306. var path = options.path;
  54307. var shape = options.shape;
  54308. var scaleFunction = options.scaleFunction || (function () { return 1; });
  54309. var rotationFunction = options.rotationFunction || (function () { return 0; });
  54310. var ribbonCloseArray = options.ribbonCloseArray || false;
  54311. var ribbonClosePath = options.ribbonClosePath || false;
  54312. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54313. var updatable = options.updatable;
  54314. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54315. var instance = options.instance;
  54316. var invertUV = options.invertUV || false;
  54317. 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);
  54318. };
  54319. /**
  54320. * Creates lathe mesh.
  54321. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  54322. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  54323. *
  54324. * 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
  54325. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  54326. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  54327. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  54328. * 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.
  54329. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  54330. * 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
  54331. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54332. * 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).
  54333. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54334. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54335. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54336. */
  54337. MeshBuilder.CreateLathe = function (name, options, scene) {
  54338. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  54339. var closed = (options.closed === undefined) ? true : options.closed;
  54340. var shape = options.shape;
  54341. var radius = options.radius || 1;
  54342. var tessellation = options.tessellation || 64;
  54343. var updatable = options.updatable;
  54344. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54345. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54346. var pi2 = Math.PI * 2;
  54347. var paths = new Array();
  54348. var invertUV = options.invertUV || false;
  54349. var i = 0;
  54350. var p = 0;
  54351. var step = pi2 / tessellation * arc;
  54352. var rotated;
  54353. var path = new Array();
  54354. ;
  54355. for (i = 0; i <= tessellation; i++) {
  54356. var path = [];
  54357. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  54358. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  54359. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  54360. }
  54361. for (p = 0; p < shape.length; p++) {
  54362. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  54363. path.push(rotated);
  54364. }
  54365. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  54366. 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));
  54367. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  54368. }
  54369. paths.push(path);
  54370. }
  54371. // lathe ribbon
  54372. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54373. return lathe;
  54374. };
  54375. /**
  54376. * Creates a plane mesh.
  54377. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54378. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  54379. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  54380. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  54381. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54382. * 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).
  54383. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54384. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54385. */
  54386. MeshBuilder.CreatePlane = function (name, options, scene) {
  54387. var plane = new BABYLON.Mesh(name, scene);
  54388. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54389. plane._originalBuilderSideOrientation = options.sideOrientation;
  54390. var vertexData = BABYLON.VertexData.CreatePlane(options);
  54391. vertexData.applyToMesh(plane, options.updatable);
  54392. if (options.sourcePlane) {
  54393. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  54394. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  54395. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  54396. plane.rotate(vectorProduct, product);
  54397. }
  54398. return plane;
  54399. };
  54400. /**
  54401. * Creates a ground mesh.
  54402. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54403. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  54404. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  54405. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54406. */
  54407. MeshBuilder.CreateGround = function (name, options, scene) {
  54408. var ground = new BABYLON.GroundMesh(name, scene);
  54409. ground._setReady(false);
  54410. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  54411. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  54412. ground._width = options.width || 1;
  54413. ground._height = options.height || 1;
  54414. ground._maxX = ground._width / 2;
  54415. ground._maxZ = ground._height / 2;
  54416. ground._minX = -ground._maxX;
  54417. ground._minZ = -ground._maxZ;
  54418. var vertexData = BABYLON.VertexData.CreateGround(options);
  54419. vertexData.applyToMesh(ground, options.updatable);
  54420. ground._setReady(true);
  54421. return ground;
  54422. };
  54423. /**
  54424. * Creates a tiled ground mesh.
  54425. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  54426. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  54427. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  54428. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  54429. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  54430. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  54431. * numbers of subdivisions on the ground width and height of each tile.
  54432. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54433. */
  54434. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  54435. var tiledGround = new BABYLON.Mesh(name, scene);
  54436. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  54437. vertexData.applyToMesh(tiledGround, options.updatable);
  54438. return tiledGround;
  54439. };
  54440. /**
  54441. * Creates a ground mesh from a height map.
  54442. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  54443. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  54444. * The parameter `url` sets the URL of the height map image resource.
  54445. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  54446. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  54447. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  54448. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  54449. * 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.
  54450. * 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).
  54451. * This function is passed the newly built mesh :
  54452. * ```javascript
  54453. * function(mesh) { // do things
  54454. * return; }
  54455. * ```
  54456. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54457. */
  54458. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  54459. var width = options.width || 10.0;
  54460. var height = options.height || 10.0;
  54461. var subdivisions = options.subdivisions || 1 | 0;
  54462. var minHeight = options.minHeight || 0.0;
  54463. var maxHeight = options.maxHeight || 1.0;
  54464. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  54465. var updatable = options.updatable;
  54466. var onReady = options.onReady;
  54467. var ground = new BABYLON.GroundMesh(name, scene);
  54468. ground._subdivisionsX = subdivisions;
  54469. ground._subdivisionsY = subdivisions;
  54470. ground._width = width;
  54471. ground._height = height;
  54472. ground._maxX = ground._width / 2.0;
  54473. ground._maxZ = ground._height / 2.0;
  54474. ground._minX = -ground._maxX;
  54475. ground._minZ = -ground._maxZ;
  54476. ground._setReady(false);
  54477. var onload = function (img) {
  54478. // Getting height map data
  54479. var canvas = document.createElement("canvas");
  54480. var context = canvas.getContext("2d");
  54481. if (!context) {
  54482. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  54483. }
  54484. if (scene.isDisposed) {
  54485. return;
  54486. }
  54487. var bufferWidth = img.width;
  54488. var bufferHeight = img.height;
  54489. canvas.width = bufferWidth;
  54490. canvas.height = bufferHeight;
  54491. context.drawImage(img, 0, 0);
  54492. // Create VertexData from map data
  54493. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  54494. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  54495. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  54496. width: width, height: height,
  54497. subdivisions: subdivisions,
  54498. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  54499. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  54500. });
  54501. vertexData.applyToMesh(ground, updatable);
  54502. ground._setReady(true);
  54503. //execute ready callback, if set
  54504. if (onReady) {
  54505. onReady(ground);
  54506. }
  54507. };
  54508. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  54509. return ground;
  54510. };
  54511. /**
  54512. * Creates a polygon mesh.
  54513. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  54514. * 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.
  54515. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54516. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54517. * 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).
  54518. * Remember you can only change the shape positions, not their number when updating a polygon.
  54519. */
  54520. MeshBuilder.CreatePolygon = function (name, options, scene) {
  54521. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54522. var shape = options.shape;
  54523. var holes = options.holes || [];
  54524. var depth = options.depth || 0;
  54525. var contours = [];
  54526. var hole = [];
  54527. for (var i = 0; i < shape.length; i++) {
  54528. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  54529. }
  54530. var epsilon = 0.00000001;
  54531. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  54532. contours.pop();
  54533. }
  54534. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  54535. for (var hNb = 0; hNb < holes.length; hNb++) {
  54536. hole = [];
  54537. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  54538. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  54539. }
  54540. polygonTriangulation.addHole(hole);
  54541. }
  54542. var polygon = polygonTriangulation.build(options.updatable, depth);
  54543. polygon._originalBuilderSideOrientation = options.sideOrientation;
  54544. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  54545. vertexData.applyToMesh(polygon, options.updatable);
  54546. return polygon;
  54547. };
  54548. ;
  54549. /**
  54550. * Creates an extruded polygon mesh, with depth in the Y direction.
  54551. * 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).
  54552. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54553. */
  54554. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  54555. return MeshBuilder.CreatePolygon(name, options, scene);
  54556. };
  54557. ;
  54558. /**
  54559. * Creates a tube mesh.
  54560. * 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.
  54561. *
  54562. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  54563. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  54564. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  54565. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  54566. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  54567. * 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.
  54568. * It must return a radius value (positive float) :
  54569. * ```javascript
  54570. * var radiusFunction = function(i, distance) {
  54571. * // do things
  54572. * return radius; }
  54573. * ```
  54574. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  54575. * 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
  54576. * 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
  54577. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54578. * 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).
  54579. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54580. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54581. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54582. */
  54583. MeshBuilder.CreateTube = function (name, options, scene) {
  54584. var path = options.path;
  54585. var instance = options.instance;
  54586. var radius = 1.0;
  54587. if (instance) {
  54588. radius = instance.radius;
  54589. }
  54590. if (options.radius !== undefined) {
  54591. radius = options.radius;
  54592. }
  54593. ;
  54594. var tessellation = options.tessellation || 64 | 0;
  54595. var radiusFunction = options.radiusFunction || null;
  54596. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54597. var invertUV = options.invertUV || false;
  54598. var updatable = options.updatable;
  54599. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54600. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  54601. // tube geometry
  54602. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  54603. var tangents = path3D.getTangents();
  54604. var normals = path3D.getNormals();
  54605. var distances = path3D.getDistances();
  54606. var pi2 = Math.PI * 2;
  54607. var step = pi2 / tessellation * arc;
  54608. var returnRadius = function () { return radius; };
  54609. var radiusFunctionFinal = radiusFunction || returnRadius;
  54610. var circlePath;
  54611. var rad;
  54612. var normal;
  54613. var rotated;
  54614. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54615. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54616. for (var i = 0; i < path.length; i++) {
  54617. rad = radiusFunctionFinal(i, distances[i]); // current radius
  54618. circlePath = Array(); // current circle array
  54619. normal = normals[i]; // current normal
  54620. for (var t = 0; t < tessellation; t++) {
  54621. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  54622. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  54623. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  54624. rotated.scaleInPlace(rad).addInPlace(path[i]);
  54625. circlePath[t] = rotated;
  54626. }
  54627. circlePaths[index] = circlePath;
  54628. index++;
  54629. }
  54630. // cap
  54631. var capPath = function (nbPoints, pathIndex) {
  54632. var pointCap = Array();
  54633. for (var i = 0; i < nbPoints; i++) {
  54634. pointCap.push(path[pathIndex]);
  54635. }
  54636. return pointCap;
  54637. };
  54638. switch (cap) {
  54639. case BABYLON.Mesh.NO_CAP:
  54640. break;
  54641. case BABYLON.Mesh.CAP_START:
  54642. circlePaths[0] = capPath(tessellation, 0);
  54643. circlePaths[1] = circlePaths[2].slice(0);
  54644. break;
  54645. case BABYLON.Mesh.CAP_END:
  54646. circlePaths[index] = circlePaths[index - 1].slice(0);
  54647. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54648. break;
  54649. case BABYLON.Mesh.CAP_ALL:
  54650. circlePaths[0] = capPath(tessellation, 0);
  54651. circlePaths[1] = circlePaths[2].slice(0);
  54652. circlePaths[index] = circlePaths[index - 1].slice(0);
  54653. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54654. break;
  54655. default:
  54656. break;
  54657. }
  54658. return circlePaths;
  54659. };
  54660. var path3D;
  54661. var pathArray;
  54662. if (instance) {
  54663. var arc = options.arc || instance.arc;
  54664. path3D = (instance.path3D).update(path);
  54665. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  54666. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  54667. instance.path3D = path3D;
  54668. instance.pathArray = pathArray;
  54669. instance.arc = arc;
  54670. instance.radius = radius;
  54671. return instance;
  54672. }
  54673. // tube creation
  54674. path3D = new BABYLON.Path3D(path);
  54675. var newPathArray = new Array();
  54676. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54677. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  54678. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54679. tube.pathArray = pathArray;
  54680. tube.path3D = path3D;
  54681. tube.tessellation = tessellation;
  54682. tube.cap = cap;
  54683. tube.arc = options.arc;
  54684. tube.radius = radius;
  54685. return tube;
  54686. };
  54687. /**
  54688. * Creates a polyhedron mesh.
  54689. *
  54690. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  54691. * 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
  54692. * to choose the wanted type.
  54693. * The parameter `size` (positive float, default 1) sets the polygon size.
  54694. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  54695. * 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`.
  54696. * 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
  54697. * 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)`).
  54698. * 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
  54699. * 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.
  54700. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54701. * 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).
  54702. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54703. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54704. */
  54705. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  54706. var polyhedron = new BABYLON.Mesh(name, scene);
  54707. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54708. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  54709. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  54710. vertexData.applyToMesh(polyhedron, options.updatable);
  54711. return polyhedron;
  54712. };
  54713. /**
  54714. * Creates a decal mesh.
  54715. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  54716. * 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.
  54717. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  54718. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  54719. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  54720. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  54721. */
  54722. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  54723. var indices = sourceMesh.getIndices();
  54724. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54725. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54726. var position = options.position || BABYLON.Vector3.Zero();
  54727. var normal = options.normal || BABYLON.Vector3.Up();
  54728. var size = options.size || BABYLON.Vector3.One();
  54729. var angle = options.angle || 0;
  54730. // Getting correct rotation
  54731. if (!normal) {
  54732. var target = new BABYLON.Vector3(0, 0, 1);
  54733. var camera = sourceMesh.getScene().activeCamera;
  54734. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  54735. normal = camera.globalPosition.subtract(cameraWorldTarget);
  54736. }
  54737. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  54738. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  54739. var pitch = Math.atan2(normal.y, len);
  54740. // Matrix
  54741. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  54742. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  54743. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  54744. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  54745. var vertexData = new BABYLON.VertexData();
  54746. vertexData.indices = [];
  54747. vertexData.positions = [];
  54748. vertexData.normals = [];
  54749. vertexData.uvs = [];
  54750. var currentVertexDataIndex = 0;
  54751. var extractDecalVector3 = function (indexId) {
  54752. var result = new BABYLON.PositionNormalVertex();
  54753. if (!indices || !positions || !normals) {
  54754. return result;
  54755. }
  54756. var vertexId = indices[indexId];
  54757. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  54758. // Send vector to decal local world
  54759. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  54760. // Get normal
  54761. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  54762. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  54763. return result;
  54764. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  54765. var clip = function (vertices, axis) {
  54766. if (vertices.length === 0) {
  54767. return vertices;
  54768. }
  54769. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  54770. var clipVertices = function (v0, v1) {
  54771. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  54772. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  54773. };
  54774. var result = new Array();
  54775. for (var index = 0; index < vertices.length; index += 3) {
  54776. var v1Out;
  54777. var v2Out;
  54778. var v3Out;
  54779. var total = 0;
  54780. var nV1 = null;
  54781. var nV2 = null;
  54782. var nV3 = null;
  54783. var nV4 = null;
  54784. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  54785. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  54786. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  54787. v1Out = d1 > 0;
  54788. v2Out = d2 > 0;
  54789. v3Out = d3 > 0;
  54790. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  54791. switch (total) {
  54792. case 0:
  54793. result.push(vertices[index]);
  54794. result.push(vertices[index + 1]);
  54795. result.push(vertices[index + 2]);
  54796. break;
  54797. case 1:
  54798. if (v1Out) {
  54799. nV1 = vertices[index + 1];
  54800. nV2 = vertices[index + 2];
  54801. nV3 = clipVertices(vertices[index], nV1);
  54802. nV4 = clipVertices(vertices[index], nV2);
  54803. }
  54804. if (v2Out) {
  54805. nV1 = vertices[index];
  54806. nV2 = vertices[index + 2];
  54807. nV3 = clipVertices(vertices[index + 1], nV1);
  54808. nV4 = clipVertices(vertices[index + 1], nV2);
  54809. result.push(nV3);
  54810. result.push(nV2.clone());
  54811. result.push(nV1.clone());
  54812. result.push(nV2.clone());
  54813. result.push(nV3.clone());
  54814. result.push(nV4);
  54815. break;
  54816. }
  54817. if (v3Out) {
  54818. nV1 = vertices[index];
  54819. nV2 = vertices[index + 1];
  54820. nV3 = clipVertices(vertices[index + 2], nV1);
  54821. nV4 = clipVertices(vertices[index + 2], nV2);
  54822. }
  54823. if (nV1 && nV2 && nV3 && nV4) {
  54824. result.push(nV1.clone());
  54825. result.push(nV2.clone());
  54826. result.push(nV3);
  54827. result.push(nV4);
  54828. result.push(nV3.clone());
  54829. result.push(nV2.clone());
  54830. }
  54831. break;
  54832. case 2:
  54833. if (!v1Out) {
  54834. nV1 = vertices[index].clone();
  54835. nV2 = clipVertices(nV1, vertices[index + 1]);
  54836. nV3 = clipVertices(nV1, vertices[index + 2]);
  54837. result.push(nV1);
  54838. result.push(nV2);
  54839. result.push(nV3);
  54840. }
  54841. if (!v2Out) {
  54842. nV1 = vertices[index + 1].clone();
  54843. nV2 = clipVertices(nV1, vertices[index + 2]);
  54844. nV3 = clipVertices(nV1, vertices[index]);
  54845. result.push(nV1);
  54846. result.push(nV2);
  54847. result.push(nV3);
  54848. }
  54849. if (!v3Out) {
  54850. nV1 = vertices[index + 2].clone();
  54851. nV2 = clipVertices(nV1, vertices[index]);
  54852. nV3 = clipVertices(nV1, vertices[index + 1]);
  54853. result.push(nV1);
  54854. result.push(nV2);
  54855. result.push(nV3);
  54856. }
  54857. break;
  54858. case 3:
  54859. break;
  54860. }
  54861. }
  54862. return result;
  54863. };
  54864. for (var index = 0; index < indices.length; index += 3) {
  54865. var faceVertices = new Array();
  54866. faceVertices.push(extractDecalVector3(index));
  54867. faceVertices.push(extractDecalVector3(index + 1));
  54868. faceVertices.push(extractDecalVector3(index + 2));
  54869. // Clip
  54870. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  54871. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  54872. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  54873. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  54874. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  54875. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  54876. if (faceVertices.length === 0) {
  54877. continue;
  54878. }
  54879. // Add UVs and get back to world
  54880. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  54881. var vertex = faceVertices[vIndex];
  54882. //TODO check for Int32Array | Uint32Array | Uint16Array
  54883. vertexData.indices.push(currentVertexDataIndex);
  54884. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  54885. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  54886. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  54887. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  54888. currentVertexDataIndex++;
  54889. }
  54890. }
  54891. // Return mesh
  54892. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  54893. vertexData.applyToMesh(decal);
  54894. decal.position = position.clone();
  54895. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  54896. return decal;
  54897. };
  54898. // Privates
  54899. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  54900. // extrusion geometry
  54901. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  54902. var tangents = path3D.getTangents();
  54903. var normals = path3D.getNormals();
  54904. var binormals = path3D.getBinormals();
  54905. var distances = path3D.getDistances();
  54906. var angle = 0;
  54907. var returnScale = function () { return scale !== null ? scale : 1; };
  54908. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  54909. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  54910. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  54911. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54912. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54913. for (var i = 0; i < curve.length; i++) {
  54914. var shapePath = new Array();
  54915. var angleStep = rotate(i, distances[i]);
  54916. var scaleRatio = scl(i, distances[i]);
  54917. for (var p = 0; p < shape.length; p++) {
  54918. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  54919. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  54920. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  54921. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  54922. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  54923. shapePath[p] = rotated;
  54924. }
  54925. shapePaths[index] = shapePath;
  54926. angle += angleStep;
  54927. index++;
  54928. }
  54929. // cap
  54930. var capPath = function (shapePath) {
  54931. var pointCap = Array();
  54932. var barycenter = BABYLON.Vector3.Zero();
  54933. var i;
  54934. for (i = 0; i < shapePath.length; i++) {
  54935. barycenter.addInPlace(shapePath[i]);
  54936. }
  54937. barycenter.scaleInPlace(1.0 / shapePath.length);
  54938. for (i = 0; i < shapePath.length; i++) {
  54939. pointCap.push(barycenter);
  54940. }
  54941. return pointCap;
  54942. };
  54943. switch (cap) {
  54944. case BABYLON.Mesh.NO_CAP:
  54945. break;
  54946. case BABYLON.Mesh.CAP_START:
  54947. shapePaths[0] = capPath(shapePaths[2]);
  54948. shapePaths[1] = shapePaths[2];
  54949. break;
  54950. case BABYLON.Mesh.CAP_END:
  54951. shapePaths[index] = shapePaths[index - 1];
  54952. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54953. break;
  54954. case BABYLON.Mesh.CAP_ALL:
  54955. shapePaths[0] = capPath(shapePaths[2]);
  54956. shapePaths[1] = shapePaths[2];
  54957. shapePaths[index] = shapePaths[index - 1];
  54958. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54959. break;
  54960. default:
  54961. break;
  54962. }
  54963. return shapePaths;
  54964. };
  54965. var path3D;
  54966. var pathArray;
  54967. if (instance) {
  54968. path3D = (instance.path3D).update(curve);
  54969. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  54970. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  54971. return instance;
  54972. }
  54973. // extruded shape creation
  54974. path3D = new BABYLON.Path3D(curve);
  54975. var newShapePaths = new Array();
  54976. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54977. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  54978. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  54979. extrudedGeneric.pathArray = pathArray;
  54980. extrudedGeneric.path3D = path3D;
  54981. extrudedGeneric.cap = cap;
  54982. return extrudedGeneric;
  54983. };
  54984. return MeshBuilder;
  54985. }());
  54986. BABYLON.MeshBuilder = MeshBuilder;
  54987. })(BABYLON || (BABYLON = {}));
  54988. //# sourceMappingURL=babylon.meshBuilder.js.map
  54989. var BABYLON;
  54990. (function (BABYLON) {
  54991. var AudioEngine = /** @class */ (function () {
  54992. function AudioEngine() {
  54993. this._audioContext = null;
  54994. this._audioContextInitialized = false;
  54995. this.canUseWebAudio = false;
  54996. this.WarnedWebAudioUnsupported = false;
  54997. this.unlocked = false;
  54998. this.isMP3supported = false;
  54999. this.isOGGsupported = false;
  55000. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  55001. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  55002. this.canUseWebAudio = true;
  55003. }
  55004. var audioElem = document.createElement('audio');
  55005. try {
  55006. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  55007. this.isMP3supported = true;
  55008. }
  55009. }
  55010. catch (e) {
  55011. // protect error during capability check.
  55012. }
  55013. try {
  55014. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  55015. this.isOGGsupported = true;
  55016. }
  55017. }
  55018. catch (e) {
  55019. // protect error during capability check.
  55020. }
  55021. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  55022. this._unlockiOSaudio();
  55023. }
  55024. else {
  55025. this.unlocked = true;
  55026. }
  55027. }
  55028. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  55029. get: function () {
  55030. if (!this._audioContextInitialized) {
  55031. this._initializeAudioContext();
  55032. }
  55033. return this._audioContext;
  55034. },
  55035. enumerable: true,
  55036. configurable: true
  55037. });
  55038. AudioEngine.prototype._unlockiOSaudio = function () {
  55039. var _this = this;
  55040. var unlockaudio = function () {
  55041. if (!_this.audioContext) {
  55042. return;
  55043. }
  55044. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  55045. var source = _this.audioContext.createBufferSource();
  55046. source.buffer = buffer;
  55047. source.connect(_this.audioContext.destination);
  55048. source.start(0);
  55049. setTimeout(function () {
  55050. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  55051. _this.unlocked = true;
  55052. window.removeEventListener('touchend', unlockaudio, false);
  55053. if (_this.onAudioUnlocked) {
  55054. _this.onAudioUnlocked();
  55055. }
  55056. }
  55057. }, 0);
  55058. };
  55059. window.addEventListener('touchend', unlockaudio, false);
  55060. };
  55061. AudioEngine.prototype._initializeAudioContext = function () {
  55062. try {
  55063. if (this.canUseWebAudio) {
  55064. this._audioContext = new AudioContext();
  55065. // create a global volume gain node
  55066. this.masterGain = this._audioContext.createGain();
  55067. this.masterGain.gain.value = 1;
  55068. this.masterGain.connect(this._audioContext.destination);
  55069. this._audioContextInitialized = true;
  55070. }
  55071. }
  55072. catch (e) {
  55073. this.canUseWebAudio = false;
  55074. BABYLON.Tools.Error("Web Audio: " + e.message);
  55075. }
  55076. };
  55077. AudioEngine.prototype.dispose = function () {
  55078. if (this.canUseWebAudio && this._audioContextInitialized) {
  55079. if (this._connectedAnalyser && this._audioContext) {
  55080. this._connectedAnalyser.stopDebugCanvas();
  55081. this._connectedAnalyser.dispose();
  55082. this.masterGain.disconnect();
  55083. this.masterGain.connect(this._audioContext.destination);
  55084. this._connectedAnalyser = null;
  55085. }
  55086. this.masterGain.gain.value = 1;
  55087. }
  55088. this.WarnedWebAudioUnsupported = false;
  55089. };
  55090. AudioEngine.prototype.getGlobalVolume = function () {
  55091. if (this.canUseWebAudio && this._audioContextInitialized) {
  55092. return this.masterGain.gain.value;
  55093. }
  55094. else {
  55095. return -1;
  55096. }
  55097. };
  55098. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  55099. if (this.canUseWebAudio && this._audioContextInitialized) {
  55100. this.masterGain.gain.value = newVolume;
  55101. }
  55102. };
  55103. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  55104. if (this._connectedAnalyser) {
  55105. this._connectedAnalyser.stopDebugCanvas();
  55106. }
  55107. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  55108. this._connectedAnalyser = analyser;
  55109. this.masterGain.disconnect();
  55110. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  55111. }
  55112. };
  55113. return AudioEngine;
  55114. }());
  55115. BABYLON.AudioEngine = AudioEngine;
  55116. })(BABYLON || (BABYLON = {}));
  55117. //# sourceMappingURL=babylon.audioEngine.js.map
  55118. var BABYLON;
  55119. (function (BABYLON) {
  55120. var Sound = /** @class */ (function () {
  55121. /**
  55122. * Create a sound and attach it to a scene
  55123. * @param name Name of your sound
  55124. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  55125. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  55126. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  55127. */
  55128. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  55129. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  55130. var _this = this;
  55131. this.autoplay = false;
  55132. this.loop = false;
  55133. this.useCustomAttenuation = false;
  55134. this.spatialSound = false;
  55135. this.refDistance = 1;
  55136. this.rolloffFactor = 1;
  55137. this.maxDistance = 100;
  55138. this.distanceModel = "linear";
  55139. this._panningModel = "equalpower";
  55140. this._playbackRate = 1;
  55141. this._streaming = false;
  55142. this._startTime = 0;
  55143. this._startOffset = 0;
  55144. this._position = BABYLON.Vector3.Zero();
  55145. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  55146. this._volume = 1;
  55147. this._isReadyToPlay = false;
  55148. this.isPlaying = false;
  55149. this.isPaused = false;
  55150. this._isDirectional = false;
  55151. // Used if you'd like to create a directional sound.
  55152. // If not set, the sound will be omnidirectional
  55153. this._coneInnerAngle = 360;
  55154. this._coneOuterAngle = 360;
  55155. this._coneOuterGain = 0;
  55156. this._isOutputConnected = false;
  55157. this._urlType = "Unknown";
  55158. this.name = name;
  55159. this._scene = scene;
  55160. this._readyToPlayCallback = readyToPlayCallback;
  55161. // Default custom attenuation function is a linear attenuation
  55162. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  55163. if (currentDistance < maxDistance) {
  55164. return currentVolume * (1 - currentDistance / maxDistance);
  55165. }
  55166. else {
  55167. return 0;
  55168. }
  55169. };
  55170. if (options) {
  55171. this.autoplay = options.autoplay || false;
  55172. this.loop = options.loop || false;
  55173. // if volume === 0, we need another way to check this option
  55174. if (options.volume !== undefined) {
  55175. this._volume = options.volume;
  55176. }
  55177. this.spatialSound = options.spatialSound || false;
  55178. this.maxDistance = options.maxDistance || 100;
  55179. this.useCustomAttenuation = options.useCustomAttenuation || false;
  55180. this.rolloffFactor = options.rolloffFactor || 1;
  55181. this.refDistance = options.refDistance || 1;
  55182. this.distanceModel = options.distanceModel || "linear";
  55183. this._playbackRate = options.playbackRate || 1;
  55184. this._streaming = options.streaming || false;
  55185. }
  55186. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55187. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  55188. this._soundGain.gain.value = this._volume;
  55189. this._inputAudioNode = this._soundGain;
  55190. this._ouputAudioNode = this._soundGain;
  55191. if (this.spatialSound) {
  55192. this._createSpatialParameters();
  55193. }
  55194. this._scene.mainSoundTrack.AddSound(this);
  55195. var validParameter = true;
  55196. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  55197. if (urlOrArrayBuffer) {
  55198. if (typeof (urlOrArrayBuffer) === "string")
  55199. this._urlType = "String";
  55200. if (Array.isArray(urlOrArrayBuffer))
  55201. this._urlType = "Array";
  55202. if (urlOrArrayBuffer instanceof ArrayBuffer)
  55203. this._urlType = "ArrayBuffer";
  55204. var urls = [];
  55205. var codecSupportedFound = false;
  55206. switch (this._urlType) {
  55207. case "ArrayBuffer":
  55208. if (urlOrArrayBuffer.byteLength > 0) {
  55209. codecSupportedFound = true;
  55210. this._soundLoaded(urlOrArrayBuffer);
  55211. }
  55212. break;
  55213. case "String":
  55214. urls.push(urlOrArrayBuffer);
  55215. case "Array":
  55216. if (urls.length === 0)
  55217. urls = urlOrArrayBuffer;
  55218. // If we found a supported format, we load it immediately and stop the loop
  55219. for (var i = 0; i < urls.length; i++) {
  55220. var url = urls[i];
  55221. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  55222. codecSupportedFound = true;
  55223. }
  55224. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  55225. codecSupportedFound = true;
  55226. }
  55227. if (url.indexOf(".wav", url.length - 4) !== -1) {
  55228. codecSupportedFound = true;
  55229. }
  55230. if (url.indexOf("blob:") !== -1) {
  55231. codecSupportedFound = true;
  55232. }
  55233. if (codecSupportedFound) {
  55234. // Loading sound using XHR2
  55235. if (!this._streaming) {
  55236. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  55237. }
  55238. else {
  55239. this._htmlAudioElement = new Audio(url);
  55240. this._htmlAudioElement.controls = false;
  55241. this._htmlAudioElement.loop = this.loop;
  55242. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  55243. this._htmlAudioElement.preload = "auto";
  55244. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  55245. _this._isReadyToPlay = true;
  55246. if (_this.autoplay) {
  55247. _this.play();
  55248. }
  55249. if (_this._readyToPlayCallback) {
  55250. _this._readyToPlayCallback();
  55251. }
  55252. });
  55253. document.body.appendChild(this._htmlAudioElement);
  55254. }
  55255. break;
  55256. }
  55257. }
  55258. break;
  55259. default:
  55260. validParameter = false;
  55261. break;
  55262. }
  55263. if (!validParameter) {
  55264. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  55265. }
  55266. else {
  55267. if (!codecSupportedFound) {
  55268. this._isReadyToPlay = true;
  55269. // Simulating a ready to play event to avoid breaking code path
  55270. if (this._readyToPlayCallback) {
  55271. window.setTimeout(function () {
  55272. if (_this._readyToPlayCallback) {
  55273. _this._readyToPlayCallback();
  55274. }
  55275. }, 1000);
  55276. }
  55277. }
  55278. }
  55279. }
  55280. }
  55281. else {
  55282. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  55283. this._scene.mainSoundTrack.AddSound(this);
  55284. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  55285. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  55286. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  55287. }
  55288. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  55289. if (this._readyToPlayCallback) {
  55290. window.setTimeout(function () {
  55291. if (_this._readyToPlayCallback) {
  55292. _this._readyToPlayCallback();
  55293. }
  55294. }, 1000);
  55295. }
  55296. }
  55297. }
  55298. Sound.prototype.dispose = function () {
  55299. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  55300. if (this.isPlaying) {
  55301. this.stop();
  55302. }
  55303. this._isReadyToPlay = false;
  55304. if (this.soundTrackId === -1) {
  55305. this._scene.mainSoundTrack.RemoveSound(this);
  55306. }
  55307. else {
  55308. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  55309. }
  55310. if (this._soundGain) {
  55311. this._soundGain.disconnect();
  55312. this._soundGain = null;
  55313. }
  55314. if (this._soundPanner) {
  55315. this._soundPanner.disconnect();
  55316. this._soundPanner = null;
  55317. }
  55318. if (this._soundSource) {
  55319. this._soundSource.disconnect();
  55320. this._soundSource = null;
  55321. }
  55322. this._audioBuffer = null;
  55323. if (this._htmlAudioElement) {
  55324. this._htmlAudioElement.pause();
  55325. this._htmlAudioElement.src = "";
  55326. document.body.removeChild(this._htmlAudioElement);
  55327. }
  55328. if (this._connectedMesh && this._registerFunc) {
  55329. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55330. this._connectedMesh = null;
  55331. }
  55332. }
  55333. };
  55334. Sound.prototype.isReady = function () {
  55335. return this._isReadyToPlay;
  55336. };
  55337. Sound.prototype._soundLoaded = function (audioData) {
  55338. var _this = this;
  55339. if (!BABYLON.Engine.audioEngine.audioContext) {
  55340. return;
  55341. }
  55342. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  55343. _this._audioBuffer = buffer;
  55344. _this._isReadyToPlay = true;
  55345. if (_this.autoplay) {
  55346. _this.play();
  55347. }
  55348. if (_this._readyToPlayCallback) {
  55349. _this._readyToPlayCallback();
  55350. }
  55351. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  55352. };
  55353. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  55354. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55355. this._audioBuffer = audioBuffer;
  55356. this._isReadyToPlay = true;
  55357. }
  55358. };
  55359. Sound.prototype.updateOptions = function (options) {
  55360. if (options) {
  55361. this.loop = options.loop || this.loop;
  55362. this.maxDistance = options.maxDistance || this.maxDistance;
  55363. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  55364. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  55365. this.refDistance = options.refDistance || this.refDistance;
  55366. this.distanceModel = options.distanceModel || this.distanceModel;
  55367. this._playbackRate = options.playbackRate || this._playbackRate;
  55368. this._updateSpatialParameters();
  55369. if (this.isPlaying) {
  55370. if (this._streaming) {
  55371. this._htmlAudioElement.playbackRate = this._playbackRate;
  55372. }
  55373. else {
  55374. if (this._soundSource) {
  55375. this._soundSource.playbackRate.value = this._playbackRate;
  55376. }
  55377. }
  55378. }
  55379. }
  55380. };
  55381. Sound.prototype._createSpatialParameters = function () {
  55382. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55383. if (this._scene.headphone) {
  55384. this._panningModel = "HRTF";
  55385. }
  55386. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  55387. this._updateSpatialParameters();
  55388. this._soundPanner.connect(this._ouputAudioNode);
  55389. this._inputAudioNode = this._soundPanner;
  55390. }
  55391. };
  55392. Sound.prototype._updateSpatialParameters = function () {
  55393. if (this.spatialSound && this._soundPanner) {
  55394. if (this.useCustomAttenuation) {
  55395. // Tricks to disable in a way embedded Web Audio attenuation
  55396. this._soundPanner.distanceModel = "linear";
  55397. this._soundPanner.maxDistance = Number.MAX_VALUE;
  55398. this._soundPanner.refDistance = 1;
  55399. this._soundPanner.rolloffFactor = 1;
  55400. this._soundPanner.panningModel = this._panningModel;
  55401. }
  55402. else {
  55403. this._soundPanner.distanceModel = this.distanceModel;
  55404. this._soundPanner.maxDistance = this.maxDistance;
  55405. this._soundPanner.refDistance = this.refDistance;
  55406. this._soundPanner.rolloffFactor = this.rolloffFactor;
  55407. this._soundPanner.panningModel = this._panningModel;
  55408. }
  55409. }
  55410. };
  55411. Sound.prototype.switchPanningModelToHRTF = function () {
  55412. this._panningModel = "HRTF";
  55413. this._switchPanningModel();
  55414. };
  55415. Sound.prototype.switchPanningModelToEqualPower = function () {
  55416. this._panningModel = "equalpower";
  55417. this._switchPanningModel();
  55418. };
  55419. Sound.prototype._switchPanningModel = function () {
  55420. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55421. this._soundPanner.panningModel = this._panningModel;
  55422. }
  55423. };
  55424. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  55425. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55426. if (this._isOutputConnected) {
  55427. this._ouputAudioNode.disconnect();
  55428. }
  55429. this._ouputAudioNode.connect(soundTrackAudioNode);
  55430. this._isOutputConnected = true;
  55431. }
  55432. };
  55433. /**
  55434. * Transform this sound into a directional source
  55435. * @param coneInnerAngle Size of the inner cone in degree
  55436. * @param coneOuterAngle Size of the outer cone in degree
  55437. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  55438. */
  55439. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  55440. if (coneOuterAngle < coneInnerAngle) {
  55441. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  55442. return;
  55443. }
  55444. this._coneInnerAngle = coneInnerAngle;
  55445. this._coneOuterAngle = coneOuterAngle;
  55446. this._coneOuterGain = coneOuterGain;
  55447. this._isDirectional = true;
  55448. if (this.isPlaying && this.loop) {
  55449. this.stop();
  55450. this.play();
  55451. }
  55452. };
  55453. Sound.prototype.setPosition = function (newPosition) {
  55454. this._position = newPosition;
  55455. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55456. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55457. }
  55458. };
  55459. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  55460. this._localDirection = newLocalDirection;
  55461. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  55462. this._updateDirection();
  55463. }
  55464. };
  55465. Sound.prototype._updateDirection = function () {
  55466. if (!this._connectedMesh || !this._soundPanner) {
  55467. return;
  55468. }
  55469. var mat = this._connectedMesh.getWorldMatrix();
  55470. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  55471. direction.normalize();
  55472. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  55473. };
  55474. Sound.prototype.updateDistanceFromListener = function () {
  55475. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  55476. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  55477. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  55478. }
  55479. };
  55480. Sound.prototype.setAttenuationFunction = function (callback) {
  55481. this._customAttenuationFunction = callback;
  55482. };
  55483. /**
  55484. * Play the sound
  55485. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  55486. * @param offset (optional) Start the sound setting it at a specific time
  55487. */
  55488. Sound.prototype.play = function (time, offset) {
  55489. var _this = this;
  55490. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  55491. try {
  55492. if (this._startOffset < 0) {
  55493. time = -this._startOffset;
  55494. this._startOffset = 0;
  55495. }
  55496. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55497. if (!this._soundSource || !this._streamingSource) {
  55498. if (this.spatialSound && this._soundPanner) {
  55499. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55500. if (this._isDirectional) {
  55501. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  55502. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  55503. this._soundPanner.coneOuterGain = this._coneOuterGain;
  55504. if (this._connectedMesh) {
  55505. this._updateDirection();
  55506. }
  55507. else {
  55508. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  55509. }
  55510. }
  55511. }
  55512. }
  55513. if (this._streaming) {
  55514. if (!this._streamingSource) {
  55515. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  55516. this._htmlAudioElement.onended = function () { _this._onended(); };
  55517. this._htmlAudioElement.playbackRate = this._playbackRate;
  55518. }
  55519. this._streamingSource.disconnect();
  55520. this._streamingSource.connect(this._inputAudioNode);
  55521. this._htmlAudioElement.play();
  55522. }
  55523. else {
  55524. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  55525. this._soundSource.buffer = this._audioBuffer;
  55526. this._soundSource.connect(this._inputAudioNode);
  55527. this._soundSource.loop = this.loop;
  55528. this._soundSource.playbackRate.value = this._playbackRate;
  55529. this._soundSource.onended = function () { _this._onended(); };
  55530. if (this._soundSource.buffer) {
  55531. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  55532. }
  55533. }
  55534. this._startTime = startTime;
  55535. this.isPlaying = true;
  55536. this.isPaused = false;
  55537. }
  55538. catch (ex) {
  55539. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  55540. }
  55541. }
  55542. };
  55543. Sound.prototype._onended = function () {
  55544. this.isPlaying = false;
  55545. if (this.onended) {
  55546. this.onended();
  55547. }
  55548. };
  55549. /**
  55550. * Stop the sound
  55551. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  55552. */
  55553. Sound.prototype.stop = function (time) {
  55554. if (this.isPlaying) {
  55555. if (this._streaming) {
  55556. this._htmlAudioElement.pause();
  55557. // Test needed for Firefox or it will generate an Invalid State Error
  55558. if (this._htmlAudioElement.currentTime > 0) {
  55559. this._htmlAudioElement.currentTime = 0;
  55560. }
  55561. }
  55562. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  55563. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55564. this._soundSource.stop(stopTime);
  55565. this._soundSource.onended = function () { };
  55566. if (!this.isPaused) {
  55567. this._startOffset = 0;
  55568. }
  55569. }
  55570. this.isPlaying = false;
  55571. }
  55572. };
  55573. Sound.prototype.pause = function () {
  55574. if (this.isPlaying) {
  55575. this.isPaused = true;
  55576. if (this._streaming) {
  55577. this._htmlAudioElement.pause();
  55578. }
  55579. else if (BABYLON.Engine.audioEngine.audioContext) {
  55580. this.stop(0);
  55581. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  55582. }
  55583. }
  55584. };
  55585. Sound.prototype.setVolume = function (newVolume, time) {
  55586. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  55587. if (time && BABYLON.Engine.audioEngine.audioContext) {
  55588. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  55589. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  55590. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  55591. }
  55592. else {
  55593. this._soundGain.gain.value = newVolume;
  55594. }
  55595. }
  55596. this._volume = newVolume;
  55597. };
  55598. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  55599. this._playbackRate = newPlaybackRate;
  55600. if (this.isPlaying) {
  55601. if (this._streaming) {
  55602. this._htmlAudioElement.playbackRate = this._playbackRate;
  55603. }
  55604. else if (this._soundSource) {
  55605. this._soundSource.playbackRate.value = this._playbackRate;
  55606. }
  55607. }
  55608. };
  55609. Sound.prototype.getVolume = function () {
  55610. return this._volume;
  55611. };
  55612. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  55613. var _this = this;
  55614. if (this._connectedMesh && this._registerFunc) {
  55615. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55616. this._registerFunc = null;
  55617. }
  55618. this._connectedMesh = meshToConnectTo;
  55619. if (!this.spatialSound) {
  55620. this.spatialSound = true;
  55621. this._createSpatialParameters();
  55622. if (this.isPlaying && this.loop) {
  55623. this.stop();
  55624. this.play();
  55625. }
  55626. }
  55627. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  55628. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  55629. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  55630. };
  55631. Sound.prototype.detachFromMesh = function () {
  55632. if (this._connectedMesh && this._registerFunc) {
  55633. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55634. this._registerFunc = null;
  55635. this._connectedMesh = null;
  55636. }
  55637. };
  55638. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  55639. if (!node.getBoundingInfo) {
  55640. return;
  55641. }
  55642. var mesh = node;
  55643. var boundingInfo = mesh.getBoundingInfo();
  55644. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  55645. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  55646. this._updateDirection();
  55647. }
  55648. };
  55649. Sound.prototype.clone = function () {
  55650. var _this = this;
  55651. if (!this._streaming) {
  55652. var setBufferAndRun = function () {
  55653. if (_this._isReadyToPlay) {
  55654. clonedSound._audioBuffer = _this.getAudioBuffer();
  55655. clonedSound._isReadyToPlay = true;
  55656. if (clonedSound.autoplay) {
  55657. clonedSound.play();
  55658. }
  55659. }
  55660. else {
  55661. window.setTimeout(setBufferAndRun, 300);
  55662. }
  55663. };
  55664. var currentOptions = {
  55665. autoplay: this.autoplay, loop: this.loop,
  55666. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  55667. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  55668. refDistance: this.refDistance, distanceModel: this.distanceModel
  55669. };
  55670. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  55671. if (this.useCustomAttenuation) {
  55672. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  55673. }
  55674. clonedSound.setPosition(this._position);
  55675. clonedSound.setPlaybackRate(this._playbackRate);
  55676. setBufferAndRun();
  55677. return clonedSound;
  55678. }
  55679. else {
  55680. return null;
  55681. }
  55682. };
  55683. Sound.prototype.getAudioBuffer = function () {
  55684. return this._audioBuffer;
  55685. };
  55686. Sound.prototype.serialize = function () {
  55687. var serializationObject = {
  55688. name: this.name,
  55689. url: this.name,
  55690. autoplay: this.autoplay,
  55691. loop: this.loop,
  55692. volume: this._volume,
  55693. spatialSound: this.spatialSound,
  55694. maxDistance: this.maxDistance,
  55695. rolloffFactor: this.rolloffFactor,
  55696. refDistance: this.refDistance,
  55697. distanceModel: this.distanceModel,
  55698. playbackRate: this._playbackRate,
  55699. panningModel: this._panningModel,
  55700. soundTrackId: this.soundTrackId
  55701. };
  55702. if (this.spatialSound) {
  55703. if (this._connectedMesh)
  55704. serializationObject.connectedMeshId = this._connectedMesh.id;
  55705. serializationObject.position = this._position.asArray();
  55706. serializationObject.refDistance = this.refDistance;
  55707. serializationObject.distanceModel = this.distanceModel;
  55708. serializationObject.isDirectional = this._isDirectional;
  55709. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  55710. serializationObject.coneInnerAngle = this._coneInnerAngle;
  55711. serializationObject.coneOuterAngle = this._coneOuterAngle;
  55712. serializationObject.coneOuterGain = this._coneOuterGain;
  55713. }
  55714. return serializationObject;
  55715. };
  55716. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  55717. var soundName = parsedSound.name;
  55718. var soundUrl;
  55719. if (parsedSound.url) {
  55720. soundUrl = rootUrl + parsedSound.url;
  55721. }
  55722. else {
  55723. soundUrl = rootUrl + soundName;
  55724. }
  55725. var options = {
  55726. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  55727. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  55728. rolloffFactor: parsedSound.rolloffFactor,
  55729. refDistance: parsedSound.refDistance,
  55730. distanceModel: parsedSound.distanceModel,
  55731. playbackRate: parsedSound.playbackRate
  55732. };
  55733. var newSound;
  55734. if (!sourceSound) {
  55735. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  55736. scene._addPendingData(newSound);
  55737. }
  55738. else {
  55739. var setBufferAndRun = function () {
  55740. if (sourceSound._isReadyToPlay) {
  55741. newSound._audioBuffer = sourceSound.getAudioBuffer();
  55742. newSound._isReadyToPlay = true;
  55743. if (newSound.autoplay) {
  55744. newSound.play();
  55745. }
  55746. }
  55747. else {
  55748. window.setTimeout(setBufferAndRun, 300);
  55749. }
  55750. };
  55751. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  55752. setBufferAndRun();
  55753. }
  55754. if (parsedSound.position) {
  55755. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  55756. newSound.setPosition(soundPosition);
  55757. }
  55758. if (parsedSound.isDirectional) {
  55759. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  55760. if (parsedSound.localDirectionToMesh) {
  55761. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  55762. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  55763. }
  55764. }
  55765. if (parsedSound.connectedMeshId) {
  55766. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  55767. if (connectedMesh) {
  55768. newSound.attachToMesh(connectedMesh);
  55769. }
  55770. }
  55771. return newSound;
  55772. };
  55773. return Sound;
  55774. }());
  55775. BABYLON.Sound = Sound;
  55776. })(BABYLON || (BABYLON = {}));
  55777. //# sourceMappingURL=babylon.sound.js.map
  55778. var BABYLON;
  55779. (function (BABYLON) {
  55780. var SoundTrack = /** @class */ (function () {
  55781. function SoundTrack(scene, options) {
  55782. this.id = -1;
  55783. this._isMainTrack = false;
  55784. this._isInitialized = false;
  55785. this._scene = scene;
  55786. this.soundCollection = new Array();
  55787. this._options = options;
  55788. if (!this._isMainTrack) {
  55789. this._scene.soundTracks.push(this);
  55790. this.id = this._scene.soundTracks.length - 1;
  55791. }
  55792. }
  55793. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  55794. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55795. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  55796. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  55797. if (this._options) {
  55798. if (this._options.volume) {
  55799. this._outputAudioNode.gain.value = this._options.volume;
  55800. }
  55801. if (this._options.mainTrack) {
  55802. this._isMainTrack = this._options.mainTrack;
  55803. }
  55804. }
  55805. this._isInitialized = true;
  55806. }
  55807. };
  55808. SoundTrack.prototype.dispose = function () {
  55809. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  55810. if (this._connectedAnalyser) {
  55811. this._connectedAnalyser.stopDebugCanvas();
  55812. }
  55813. while (this.soundCollection.length) {
  55814. this.soundCollection[0].dispose();
  55815. }
  55816. if (this._outputAudioNode) {
  55817. this._outputAudioNode.disconnect();
  55818. }
  55819. this._outputAudioNode = null;
  55820. }
  55821. };
  55822. SoundTrack.prototype.AddSound = function (sound) {
  55823. if (!this._isInitialized) {
  55824. this._initializeSoundTrackAudioGraph();
  55825. }
  55826. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55827. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  55828. }
  55829. if (sound.soundTrackId) {
  55830. if (sound.soundTrackId === -1) {
  55831. this._scene.mainSoundTrack.RemoveSound(sound);
  55832. }
  55833. else {
  55834. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  55835. }
  55836. }
  55837. this.soundCollection.push(sound);
  55838. sound.soundTrackId = this.id;
  55839. };
  55840. SoundTrack.prototype.RemoveSound = function (sound) {
  55841. var index = this.soundCollection.indexOf(sound);
  55842. if (index !== -1) {
  55843. this.soundCollection.splice(index, 1);
  55844. }
  55845. };
  55846. SoundTrack.prototype.setVolume = function (newVolume) {
  55847. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55848. this._outputAudioNode.gain.value = newVolume;
  55849. }
  55850. };
  55851. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  55852. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55853. for (var i = 0; i < this.soundCollection.length; i++) {
  55854. this.soundCollection[i].switchPanningModelToHRTF();
  55855. }
  55856. }
  55857. };
  55858. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  55859. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55860. for (var i = 0; i < this.soundCollection.length; i++) {
  55861. this.soundCollection[i].switchPanningModelToEqualPower();
  55862. }
  55863. }
  55864. };
  55865. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  55866. if (this._connectedAnalyser) {
  55867. this._connectedAnalyser.stopDebugCanvas();
  55868. }
  55869. this._connectedAnalyser = analyser;
  55870. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55871. this._outputAudioNode.disconnect();
  55872. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  55873. }
  55874. };
  55875. return SoundTrack;
  55876. }());
  55877. BABYLON.SoundTrack = SoundTrack;
  55878. })(BABYLON || (BABYLON = {}));
  55879. //# sourceMappingURL=babylon.soundtrack.js.map
  55880. var BABYLON;
  55881. (function (BABYLON) {
  55882. var Analyser = /** @class */ (function () {
  55883. function Analyser(scene) {
  55884. this.SMOOTHING = 0.75;
  55885. this.FFT_SIZE = 512;
  55886. this.BARGRAPHAMPLITUDE = 256;
  55887. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  55888. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  55889. this._scene = scene;
  55890. this._audioEngine = BABYLON.Engine.audioEngine;
  55891. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  55892. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  55893. this._webAudioAnalyser.minDecibels = -140;
  55894. this._webAudioAnalyser.maxDecibels = 0;
  55895. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55896. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55897. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  55898. }
  55899. }
  55900. Analyser.prototype.getFrequencyBinCount = function () {
  55901. if (this._audioEngine.canUseWebAudio) {
  55902. return this._webAudioAnalyser.frequencyBinCount;
  55903. }
  55904. else {
  55905. return 0;
  55906. }
  55907. };
  55908. Analyser.prototype.getByteFrequencyData = function () {
  55909. if (this._audioEngine.canUseWebAudio) {
  55910. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55911. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55912. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  55913. }
  55914. return this._byteFreqs;
  55915. };
  55916. Analyser.prototype.getByteTimeDomainData = function () {
  55917. if (this._audioEngine.canUseWebAudio) {
  55918. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55919. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55920. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  55921. }
  55922. return this._byteTime;
  55923. };
  55924. Analyser.prototype.getFloatFrequencyData = function () {
  55925. if (this._audioEngine.canUseWebAudio) {
  55926. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55927. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55928. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  55929. }
  55930. return this._floatFreqs;
  55931. };
  55932. Analyser.prototype.drawDebugCanvas = function () {
  55933. var _this = this;
  55934. if (this._audioEngine.canUseWebAudio) {
  55935. if (!this._debugCanvas) {
  55936. this._debugCanvas = document.createElement("canvas");
  55937. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  55938. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  55939. this._debugCanvas.style.position = "absolute";
  55940. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  55941. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  55942. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  55943. document.body.appendChild(this._debugCanvas);
  55944. this._registerFunc = function () {
  55945. _this.drawDebugCanvas();
  55946. };
  55947. this._scene.registerBeforeRender(this._registerFunc);
  55948. }
  55949. if (this._registerFunc && this._debugCanvasContext) {
  55950. var workingArray = this.getByteFrequencyData();
  55951. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  55952. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  55953. // Draw the frequency domain chart.
  55954. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  55955. var value = workingArray[i];
  55956. var percent = value / this.BARGRAPHAMPLITUDE;
  55957. var height = this.DEBUGCANVASSIZE.height * percent;
  55958. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  55959. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  55960. var hue = i / this.getFrequencyBinCount() * 360;
  55961. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  55962. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  55963. }
  55964. }
  55965. }
  55966. };
  55967. Analyser.prototype.stopDebugCanvas = function () {
  55968. if (this._debugCanvas) {
  55969. if (this._registerFunc) {
  55970. this._scene.unregisterBeforeRender(this._registerFunc);
  55971. this._registerFunc = null;
  55972. }
  55973. document.body.removeChild(this._debugCanvas);
  55974. this._debugCanvas = null;
  55975. this._debugCanvasContext = null;
  55976. }
  55977. };
  55978. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  55979. if (this._audioEngine.canUseWebAudio) {
  55980. inputAudioNode.connect(this._webAudioAnalyser);
  55981. this._webAudioAnalyser.connect(outputAudioNode);
  55982. }
  55983. };
  55984. Analyser.prototype.dispose = function () {
  55985. if (this._audioEngine.canUseWebAudio) {
  55986. this._webAudioAnalyser.disconnect();
  55987. }
  55988. };
  55989. return Analyser;
  55990. }());
  55991. BABYLON.Analyser = Analyser;
  55992. })(BABYLON || (BABYLON = {}));
  55993. //# sourceMappingURL=babylon.analyser.js.map
  55994. var BABYLON;
  55995. (function (BABYLON) {
  55996. var CubeTexture = /** @class */ (function (_super) {
  55997. __extends(CubeTexture, _super);
  55998. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  55999. if (extensions === void 0) { extensions = null; }
  56000. if (noMipmap === void 0) { noMipmap = false; }
  56001. if (files === void 0) { files = null; }
  56002. if (onLoad === void 0) { onLoad = null; }
  56003. if (onError === void 0) { onError = null; }
  56004. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  56005. if (prefiltered === void 0) { prefiltered = false; }
  56006. if (forcedExtension === void 0) { forcedExtension = null; }
  56007. var _this = _super.call(this, scene) || this;
  56008. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56009. /**
  56010. * Gets or sets the center of the bounding box associated with the cube texture
  56011. * It must define where the camera used to render the texture was set
  56012. */
  56013. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56014. _this.name = rootUrl;
  56015. _this.url = rootUrl;
  56016. _this._noMipmap = noMipmap;
  56017. _this.hasAlpha = false;
  56018. _this._format = format;
  56019. _this._prefiltered = prefiltered;
  56020. _this.isCube = true;
  56021. _this._textureMatrix = BABYLON.Matrix.Identity();
  56022. if (prefiltered) {
  56023. _this.gammaSpace = false;
  56024. }
  56025. if (!rootUrl && !files) {
  56026. return _this;
  56027. }
  56028. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  56029. var lastDot = rootUrl.lastIndexOf(".");
  56030. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  56031. var isDDS = (extension === ".dds");
  56032. if (!files) {
  56033. if (!isDDS && !extensions) {
  56034. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  56035. }
  56036. files = [];
  56037. if (extensions) {
  56038. for (var index = 0; index < extensions.length; index++) {
  56039. files.push(rootUrl + extensions[index]);
  56040. }
  56041. }
  56042. }
  56043. _this._files = files;
  56044. if (!_this._texture) {
  56045. if (!scene.useDelayedTextureLoading) {
  56046. if (prefiltered) {
  56047. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  56048. }
  56049. else {
  56050. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  56051. }
  56052. }
  56053. else {
  56054. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56055. }
  56056. }
  56057. else if (onLoad) {
  56058. if (_this._texture.isReady) {
  56059. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  56060. }
  56061. else {
  56062. _this._texture.onLoadedObservable.add(onLoad);
  56063. }
  56064. }
  56065. return _this;
  56066. }
  56067. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  56068. get: function () {
  56069. return this._boundingBoxSize;
  56070. },
  56071. /**
  56072. * Gets or sets the size of the bounding box associated with the cube texture
  56073. * When defined, the cubemap will switch to local mode
  56074. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56075. * @example https://www.babylonjs-playground.com/#RNASML
  56076. */
  56077. set: function (value) {
  56078. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56079. return;
  56080. }
  56081. this._boundingBoxSize = value;
  56082. var scene = this.getScene();
  56083. if (scene) {
  56084. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56085. }
  56086. },
  56087. enumerable: true,
  56088. configurable: true
  56089. });
  56090. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  56091. return new CubeTexture("", scene, null, noMipmap, files);
  56092. };
  56093. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  56094. if (forcedExtension === void 0) { forcedExtension = null; }
  56095. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  56096. };
  56097. // Methods
  56098. CubeTexture.prototype.delayLoad = function () {
  56099. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56100. return;
  56101. }
  56102. var scene = this.getScene();
  56103. if (!scene) {
  56104. return;
  56105. }
  56106. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56107. this._texture = this._getFromCache(this.url, this._noMipmap);
  56108. if (!this._texture) {
  56109. if (this._prefiltered) {
  56110. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  56111. }
  56112. else {
  56113. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  56114. }
  56115. }
  56116. };
  56117. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  56118. return this._textureMatrix;
  56119. };
  56120. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  56121. this._textureMatrix = value;
  56122. };
  56123. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56124. var texture = BABYLON.SerializationHelper.Parse(function () {
  56125. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  56126. }, parsedTexture, scene);
  56127. // Animations
  56128. if (parsedTexture.animations) {
  56129. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  56130. var parsedAnimation = parsedTexture.animations[animationIndex];
  56131. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56132. }
  56133. }
  56134. return texture;
  56135. };
  56136. CubeTexture.prototype.clone = function () {
  56137. var _this = this;
  56138. return BABYLON.SerializationHelper.Clone(function () {
  56139. var scene = _this.getScene();
  56140. if (!scene) {
  56141. return _this;
  56142. }
  56143. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  56144. }, this);
  56145. };
  56146. return CubeTexture;
  56147. }(BABYLON.BaseTexture));
  56148. BABYLON.CubeTexture = CubeTexture;
  56149. })(BABYLON || (BABYLON = {}));
  56150. //# sourceMappingURL=babylon.cubeTexture.js.map
  56151. var BABYLON;
  56152. (function (BABYLON) {
  56153. var RenderTargetTexture = /** @class */ (function (_super) {
  56154. __extends(RenderTargetTexture, _super);
  56155. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  56156. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  56157. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56158. if (isCube === void 0) { isCube = false; }
  56159. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56160. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56161. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  56162. if (isMulti === void 0) { isMulti = false; }
  56163. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  56164. _this.isCube = isCube;
  56165. /**
  56166. * Use this list to define the list of mesh you want to render.
  56167. */
  56168. _this.renderList = new Array();
  56169. _this.renderParticles = true;
  56170. _this.renderSprites = false;
  56171. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  56172. _this.ignoreCameraViewport = false;
  56173. // Events
  56174. /**
  56175. * An event triggered when the texture is unbind.
  56176. * @type {BABYLON.Observable}
  56177. */
  56178. _this.onBeforeBindObservable = new BABYLON.Observable();
  56179. /**
  56180. * An event triggered when the texture is unbind.
  56181. * @type {BABYLON.Observable}
  56182. */
  56183. _this.onAfterUnbindObservable = new BABYLON.Observable();
  56184. /**
  56185. * An event triggered before rendering the texture
  56186. * @type {BABYLON.Observable}
  56187. */
  56188. _this.onBeforeRenderObservable = new BABYLON.Observable();
  56189. /**
  56190. * An event triggered after rendering the texture
  56191. * @type {BABYLON.Observable}
  56192. */
  56193. _this.onAfterRenderObservable = new BABYLON.Observable();
  56194. /**
  56195. * An event triggered after the texture clear
  56196. * @type {BABYLON.Observable}
  56197. */
  56198. _this.onClearObservable = new BABYLON.Observable();
  56199. _this._currentRefreshId = -1;
  56200. _this._refreshRate = 1;
  56201. _this._samples = 1;
  56202. /**
  56203. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  56204. * It must define where the camera used to render the texture is set
  56205. */
  56206. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56207. scene = _this.getScene();
  56208. if (!scene) {
  56209. return _this;
  56210. }
  56211. _this._engine = scene.getEngine();
  56212. _this.name = name;
  56213. _this.isRenderTarget = true;
  56214. _this._initialSizeParameter = size;
  56215. _this._processSizeParameter(size);
  56216. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  56217. });
  56218. _this._generateMipMaps = generateMipMaps ? true : false;
  56219. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  56220. // Rendering groups
  56221. _this._renderingManager = new BABYLON.RenderingManager(scene);
  56222. if (isMulti) {
  56223. return _this;
  56224. }
  56225. _this._renderTargetOptions = {
  56226. generateMipMaps: generateMipMaps,
  56227. type: type,
  56228. samplingMode: samplingMode,
  56229. generateDepthBuffer: generateDepthBuffer,
  56230. generateStencilBuffer: generateStencilBuffer
  56231. };
  56232. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  56233. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56234. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56235. }
  56236. if (isCube) {
  56237. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  56238. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  56239. _this._textureMatrix = BABYLON.Matrix.Identity();
  56240. }
  56241. else {
  56242. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  56243. }
  56244. return _this;
  56245. }
  56246. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  56247. get: function () {
  56248. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  56249. },
  56250. enumerable: true,
  56251. configurable: true
  56252. });
  56253. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  56254. get: function () {
  56255. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  56256. },
  56257. enumerable: true,
  56258. configurable: true
  56259. });
  56260. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  56261. get: function () {
  56262. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  56263. },
  56264. enumerable: true,
  56265. configurable: true
  56266. });
  56267. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  56268. set: function (callback) {
  56269. if (this._onAfterUnbindObserver) {
  56270. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  56271. }
  56272. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  56273. },
  56274. enumerable: true,
  56275. configurable: true
  56276. });
  56277. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  56278. set: function (callback) {
  56279. if (this._onBeforeRenderObserver) {
  56280. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  56281. }
  56282. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  56283. },
  56284. enumerable: true,
  56285. configurable: true
  56286. });
  56287. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  56288. set: function (callback) {
  56289. if (this._onAfterRenderObserver) {
  56290. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  56291. }
  56292. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  56293. },
  56294. enumerable: true,
  56295. configurable: true
  56296. });
  56297. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  56298. set: function (callback) {
  56299. if (this._onClearObserver) {
  56300. this.onClearObservable.remove(this._onClearObserver);
  56301. }
  56302. this._onClearObserver = this.onClearObservable.add(callback);
  56303. },
  56304. enumerable: true,
  56305. configurable: true
  56306. });
  56307. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  56308. get: function () {
  56309. return this._renderTargetOptions;
  56310. },
  56311. enumerable: true,
  56312. configurable: true
  56313. });
  56314. RenderTargetTexture.prototype._onRatioRescale = function () {
  56315. if (this._sizeRatio) {
  56316. this.resize(this._initialSizeParameter);
  56317. }
  56318. };
  56319. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  56320. get: function () {
  56321. return this._boundingBoxSize;
  56322. },
  56323. /**
  56324. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  56325. * When defined, the cubemap will switch to local mode
  56326. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56327. * @example https://www.babylonjs-playground.com/#RNASML
  56328. */
  56329. set: function (value) {
  56330. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56331. return;
  56332. }
  56333. this._boundingBoxSize = value;
  56334. var scene = this.getScene();
  56335. if (scene) {
  56336. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56337. }
  56338. },
  56339. enumerable: true,
  56340. configurable: true
  56341. });
  56342. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  56343. if (size.ratio) {
  56344. this._sizeRatio = size.ratio;
  56345. this._size = {
  56346. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  56347. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  56348. };
  56349. }
  56350. else {
  56351. this._size = size;
  56352. }
  56353. };
  56354. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  56355. get: function () {
  56356. return this._samples;
  56357. },
  56358. set: function (value) {
  56359. if (this._samples === value) {
  56360. return;
  56361. }
  56362. var scene = this.getScene();
  56363. if (!scene) {
  56364. return;
  56365. }
  56366. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  56367. },
  56368. enumerable: true,
  56369. configurable: true
  56370. });
  56371. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  56372. this._currentRefreshId = -1;
  56373. };
  56374. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  56375. get: function () {
  56376. return this._refreshRate;
  56377. },
  56378. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  56379. set: function (value) {
  56380. this._refreshRate = value;
  56381. this.resetRefreshCounter();
  56382. },
  56383. enumerable: true,
  56384. configurable: true
  56385. });
  56386. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  56387. if (!this._postProcessManager) {
  56388. var scene = this.getScene();
  56389. if (!scene) {
  56390. return;
  56391. }
  56392. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  56393. this._postProcesses = new Array();
  56394. }
  56395. this._postProcesses.push(postProcess);
  56396. this._postProcesses[0].autoClear = false;
  56397. };
  56398. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  56399. if (!this._postProcesses) {
  56400. return;
  56401. }
  56402. if (dispose) {
  56403. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  56404. var postProcess = _a[_i];
  56405. postProcess.dispose();
  56406. }
  56407. }
  56408. this._postProcesses = [];
  56409. };
  56410. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  56411. if (!this._postProcesses) {
  56412. return;
  56413. }
  56414. var index = this._postProcesses.indexOf(postProcess);
  56415. if (index === -1) {
  56416. return;
  56417. }
  56418. this._postProcesses.splice(index, 1);
  56419. if (this._postProcesses.length > 0) {
  56420. this._postProcesses[0].autoClear = false;
  56421. }
  56422. };
  56423. RenderTargetTexture.prototype._shouldRender = function () {
  56424. if (this._currentRefreshId === -1) {
  56425. this._currentRefreshId = 1;
  56426. return true;
  56427. }
  56428. if (this.refreshRate === this._currentRefreshId) {
  56429. this._currentRefreshId = 1;
  56430. return true;
  56431. }
  56432. this._currentRefreshId++;
  56433. return false;
  56434. };
  56435. RenderTargetTexture.prototype.getRenderSize = function () {
  56436. if (this._size.width) {
  56437. return this._size.width;
  56438. }
  56439. return this._size;
  56440. };
  56441. RenderTargetTexture.prototype.getRenderWidth = function () {
  56442. if (this._size.width) {
  56443. return this._size.width;
  56444. }
  56445. return this._size;
  56446. };
  56447. RenderTargetTexture.prototype.getRenderHeight = function () {
  56448. if (this._size.width) {
  56449. return this._size.height;
  56450. }
  56451. return this._size;
  56452. };
  56453. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  56454. get: function () {
  56455. return true;
  56456. },
  56457. enumerable: true,
  56458. configurable: true
  56459. });
  56460. RenderTargetTexture.prototype.scale = function (ratio) {
  56461. var newSize = this.getRenderSize() * ratio;
  56462. this.resize(newSize);
  56463. };
  56464. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  56465. if (this.isCube) {
  56466. return this._textureMatrix;
  56467. }
  56468. return _super.prototype.getReflectionTextureMatrix.call(this);
  56469. };
  56470. RenderTargetTexture.prototype.resize = function (size) {
  56471. this.releaseInternalTexture();
  56472. var scene = this.getScene();
  56473. if (!scene) {
  56474. return;
  56475. }
  56476. this._processSizeParameter(size);
  56477. if (this.isCube) {
  56478. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  56479. }
  56480. else {
  56481. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  56482. }
  56483. };
  56484. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  56485. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  56486. if (dumpForDebug === void 0) { dumpForDebug = false; }
  56487. var scene = this.getScene();
  56488. if (!scene) {
  56489. return;
  56490. }
  56491. var engine = scene.getEngine();
  56492. if (this.useCameraPostProcesses !== undefined) {
  56493. useCameraPostProcess = this.useCameraPostProcesses;
  56494. }
  56495. if (this._waitingRenderList) {
  56496. this.renderList = [];
  56497. for (var index = 0; index < this._waitingRenderList.length; index++) {
  56498. var id = this._waitingRenderList[index];
  56499. var mesh_1 = scene.getMeshByID(id);
  56500. if (mesh_1) {
  56501. this.renderList.push(mesh_1);
  56502. }
  56503. }
  56504. delete this._waitingRenderList;
  56505. }
  56506. // Is predicate defined?
  56507. if (this.renderListPredicate) {
  56508. if (this.renderList) {
  56509. this.renderList.splice(0); // Clear previous renderList
  56510. }
  56511. else {
  56512. this.renderList = [];
  56513. }
  56514. var scene = this.getScene();
  56515. if (!scene) {
  56516. return;
  56517. }
  56518. var sceneMeshes = scene.meshes;
  56519. for (var index = 0; index < sceneMeshes.length; index++) {
  56520. var mesh = sceneMeshes[index];
  56521. if (this.renderListPredicate(mesh)) {
  56522. this.renderList.push(mesh);
  56523. }
  56524. }
  56525. }
  56526. this.onBeforeBindObservable.notifyObservers(this);
  56527. // Set custom projection.
  56528. // Needs to be before binding to prevent changing the aspect ratio.
  56529. var camera;
  56530. if (this.activeCamera) {
  56531. camera = this.activeCamera;
  56532. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56533. if (this.activeCamera !== scene.activeCamera) {
  56534. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  56535. }
  56536. }
  56537. else {
  56538. camera = scene.activeCamera;
  56539. if (camera) {
  56540. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56541. }
  56542. }
  56543. // Prepare renderingManager
  56544. this._renderingManager.reset();
  56545. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  56546. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  56547. var sceneRenderId = scene.getRenderId();
  56548. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  56549. var mesh = currentRenderList[meshIndex];
  56550. if (mesh) {
  56551. if (!mesh.isReady()) {
  56552. // Reset _currentRefreshId
  56553. this.resetRefreshCounter();
  56554. continue;
  56555. }
  56556. mesh._preActivateForIntermediateRendering(sceneRenderId);
  56557. var isMasked = void 0;
  56558. if (!this.renderList && camera) {
  56559. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  56560. }
  56561. else {
  56562. isMasked = false;
  56563. }
  56564. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  56565. mesh._activate(sceneRenderId);
  56566. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  56567. var subMesh = mesh.subMeshes[subIndex];
  56568. scene._activeIndices.addCount(subMesh.indexCount, false);
  56569. this._renderingManager.dispatch(subMesh, mesh);
  56570. }
  56571. }
  56572. }
  56573. }
  56574. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  56575. var particleSystem = scene.particleSystems[particleIndex];
  56576. var emitter = particleSystem.emitter;
  56577. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  56578. continue;
  56579. }
  56580. if (currentRenderList.indexOf(emitter) >= 0) {
  56581. this._renderingManager.dispatchParticles(particleSystem);
  56582. }
  56583. }
  56584. if (this.isCube) {
  56585. for (var face = 0; face < 6; face++) {
  56586. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56587. scene.incrementRenderId();
  56588. scene.resetCachedMaterial();
  56589. }
  56590. }
  56591. else {
  56592. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56593. }
  56594. this.onAfterUnbindObservable.notifyObservers(this);
  56595. if (scene.activeCamera) {
  56596. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  56597. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  56598. }
  56599. engine.setViewport(scene.activeCamera.viewport);
  56600. }
  56601. scene.resetCachedMaterial();
  56602. };
  56603. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  56604. var minimum = 128;
  56605. var x = renderDimension * scale;
  56606. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  56607. // Ensure we don't exceed the render dimension (while staying POT)
  56608. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  56609. };
  56610. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56611. var _this = this;
  56612. if (!this._texture) {
  56613. return;
  56614. }
  56615. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  56616. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56617. });
  56618. };
  56619. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  56620. var scene = this.getScene();
  56621. if (!scene) {
  56622. return;
  56623. }
  56624. var engine = scene.getEngine();
  56625. if (!this._texture) {
  56626. return;
  56627. }
  56628. // Bind
  56629. if (this._postProcessManager) {
  56630. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  56631. }
  56632. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  56633. if (this._texture) {
  56634. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  56635. }
  56636. }
  56637. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  56638. // Clear
  56639. if (this.onClearObservable.hasObservers()) {
  56640. this.onClearObservable.notifyObservers(engine);
  56641. }
  56642. else {
  56643. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  56644. }
  56645. if (!this._doNotChangeAspectRatio) {
  56646. scene.updateTransformMatrix(true);
  56647. }
  56648. // Render
  56649. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  56650. if (this._postProcessManager) {
  56651. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  56652. }
  56653. else if (useCameraPostProcess) {
  56654. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  56655. }
  56656. if (!this._doNotChangeAspectRatio) {
  56657. scene.updateTransformMatrix(true);
  56658. }
  56659. // Dump ?
  56660. if (dumpForDebug) {
  56661. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  56662. }
  56663. // Unbind
  56664. if (!this.isCube || faceIndex === 5) {
  56665. if (this.isCube) {
  56666. if (faceIndex === 5) {
  56667. engine.generateMipMapsForCubemap(this._texture);
  56668. }
  56669. }
  56670. this.unbindFrameBuffer(engine, faceIndex);
  56671. }
  56672. else {
  56673. this.onAfterRenderObservable.notifyObservers(faceIndex);
  56674. }
  56675. };
  56676. /**
  56677. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  56678. * This allowed control for front to back rendering or reversly depending of the special needs.
  56679. *
  56680. * @param renderingGroupId The rendering group id corresponding to its index
  56681. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  56682. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  56683. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  56684. */
  56685. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  56686. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  56687. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  56688. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  56689. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  56690. };
  56691. /**
  56692. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  56693. *
  56694. * @param renderingGroupId The rendering group id corresponding to its index
  56695. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  56696. */
  56697. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  56698. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  56699. };
  56700. RenderTargetTexture.prototype.clone = function () {
  56701. var textureSize = this.getSize();
  56702. 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);
  56703. // Base texture
  56704. newTexture.hasAlpha = this.hasAlpha;
  56705. newTexture.level = this.level;
  56706. // RenderTarget Texture
  56707. newTexture.coordinatesMode = this.coordinatesMode;
  56708. if (this.renderList) {
  56709. newTexture.renderList = this.renderList.slice(0);
  56710. }
  56711. return newTexture;
  56712. };
  56713. RenderTargetTexture.prototype.serialize = function () {
  56714. if (!this.name) {
  56715. return null;
  56716. }
  56717. var serializationObject = _super.prototype.serialize.call(this);
  56718. serializationObject.renderTargetSize = this.getRenderSize();
  56719. serializationObject.renderList = [];
  56720. if (this.renderList) {
  56721. for (var index = 0; index < this.renderList.length; index++) {
  56722. serializationObject.renderList.push(this.renderList[index].id);
  56723. }
  56724. }
  56725. return serializationObject;
  56726. };
  56727. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  56728. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  56729. var objBuffer = this.getInternalTexture();
  56730. var scene = this.getScene();
  56731. if (objBuffer && scene) {
  56732. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  56733. }
  56734. };
  56735. RenderTargetTexture.prototype.dispose = function () {
  56736. if (this._postProcessManager) {
  56737. this._postProcessManager.dispose();
  56738. this._postProcessManager = null;
  56739. }
  56740. this.clearPostProcesses(true);
  56741. if (this._resizeObserver) {
  56742. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  56743. this._resizeObserver = null;
  56744. }
  56745. this.renderList = null;
  56746. // Remove from custom render targets
  56747. var scene = this.getScene();
  56748. if (!scene) {
  56749. return;
  56750. }
  56751. var index = scene.customRenderTargets.indexOf(this);
  56752. if (index >= 0) {
  56753. scene.customRenderTargets.splice(index, 1);
  56754. }
  56755. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  56756. var camera = _a[_i];
  56757. index = camera.customRenderTargets.indexOf(this);
  56758. if (index >= 0) {
  56759. camera.customRenderTargets.splice(index, 1);
  56760. }
  56761. }
  56762. _super.prototype.dispose.call(this);
  56763. };
  56764. RenderTargetTexture.prototype._rebuild = function () {
  56765. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  56766. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  56767. }
  56768. if (this._postProcessManager) {
  56769. this._postProcessManager._rebuild();
  56770. }
  56771. };
  56772. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  56773. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  56774. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  56775. return RenderTargetTexture;
  56776. }(BABYLON.Texture));
  56777. BABYLON.RenderTargetTexture = RenderTargetTexture;
  56778. })(BABYLON || (BABYLON = {}));
  56779. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  56780. var BABYLON;
  56781. (function (BABYLON) {
  56782. ;
  56783. var MultiRenderTarget = /** @class */ (function (_super) {
  56784. __extends(MultiRenderTarget, _super);
  56785. function MultiRenderTarget(name, size, count, scene, options) {
  56786. var _this = this;
  56787. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  56788. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  56789. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  56790. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  56791. _this._engine = scene.getEngine();
  56792. if (!_this.isSupported) {
  56793. _this.dispose();
  56794. return;
  56795. }
  56796. var types = [];
  56797. var samplingModes = [];
  56798. for (var i = 0; i < count; i++) {
  56799. if (options && options.types && options.types[i] !== undefined) {
  56800. types.push(options.types[i]);
  56801. }
  56802. else {
  56803. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56804. }
  56805. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  56806. samplingModes.push(options.samplingModes[i]);
  56807. }
  56808. else {
  56809. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56810. }
  56811. }
  56812. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  56813. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  56814. _this._size = size;
  56815. _this._multiRenderTargetOptions = {
  56816. samplingModes: samplingModes,
  56817. generateMipMaps: generateMipMaps,
  56818. generateDepthBuffer: generateDepthBuffer,
  56819. generateStencilBuffer: generateStencilBuffer,
  56820. generateDepthTexture: generateDepthTexture,
  56821. types: types,
  56822. textureCount: count
  56823. };
  56824. _this._createInternalTextures();
  56825. _this._createTextures();
  56826. return _this;
  56827. }
  56828. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  56829. get: function () {
  56830. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  56831. },
  56832. enumerable: true,
  56833. configurable: true
  56834. });
  56835. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  56836. get: function () {
  56837. return this._textures;
  56838. },
  56839. enumerable: true,
  56840. configurable: true
  56841. });
  56842. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  56843. get: function () {
  56844. return this._textures[this._textures.length - 1];
  56845. },
  56846. enumerable: true,
  56847. configurable: true
  56848. });
  56849. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  56850. set: function (wrap) {
  56851. if (this._textures) {
  56852. for (var i = 0; i < this._textures.length; i++) {
  56853. this._textures[i].wrapU = wrap;
  56854. }
  56855. }
  56856. },
  56857. enumerable: true,
  56858. configurable: true
  56859. });
  56860. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  56861. set: function (wrap) {
  56862. if (this._textures) {
  56863. for (var i = 0; i < this._textures.length; i++) {
  56864. this._textures[i].wrapV = wrap;
  56865. }
  56866. }
  56867. },
  56868. enumerable: true,
  56869. configurable: true
  56870. });
  56871. MultiRenderTarget.prototype._rebuild = function () {
  56872. this.releaseInternalTextures();
  56873. this._createInternalTextures();
  56874. for (var i = 0; i < this._internalTextures.length; i++) {
  56875. var texture = this._textures[i];
  56876. texture._texture = this._internalTextures[i];
  56877. }
  56878. // Keeps references to frame buffer and stencil/depth buffer
  56879. this._texture = this._internalTextures[0];
  56880. };
  56881. MultiRenderTarget.prototype._createInternalTextures = function () {
  56882. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  56883. };
  56884. MultiRenderTarget.prototype._createTextures = function () {
  56885. this._textures = [];
  56886. for (var i = 0; i < this._internalTextures.length; i++) {
  56887. var texture = new BABYLON.Texture(null, this.getScene());
  56888. texture._texture = this._internalTextures[i];
  56889. this._textures.push(texture);
  56890. }
  56891. // Keeps references to frame buffer and stencil/depth buffer
  56892. this._texture = this._internalTextures[0];
  56893. };
  56894. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  56895. get: function () {
  56896. return this._samples;
  56897. },
  56898. set: function (value) {
  56899. if (this._samples === value) {
  56900. return;
  56901. }
  56902. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  56903. },
  56904. enumerable: true,
  56905. configurable: true
  56906. });
  56907. MultiRenderTarget.prototype.resize = function (size) {
  56908. this.releaseInternalTextures();
  56909. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  56910. this._createInternalTextures();
  56911. };
  56912. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56913. var _this = this;
  56914. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  56915. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56916. });
  56917. };
  56918. MultiRenderTarget.prototype.dispose = function () {
  56919. this.releaseInternalTextures();
  56920. _super.prototype.dispose.call(this);
  56921. };
  56922. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  56923. if (!this._internalTextures) {
  56924. return;
  56925. }
  56926. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  56927. if (this._internalTextures[i] !== undefined) {
  56928. this._internalTextures[i].dispose();
  56929. this._internalTextures.splice(i, 1);
  56930. }
  56931. }
  56932. };
  56933. return MultiRenderTarget;
  56934. }(BABYLON.RenderTargetTexture));
  56935. BABYLON.MultiRenderTarget = MultiRenderTarget;
  56936. })(BABYLON || (BABYLON = {}));
  56937. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  56938. var BABYLON;
  56939. (function (BABYLON) {
  56940. var MirrorTexture = /** @class */ (function (_super) {
  56941. __extends(MirrorTexture, _super);
  56942. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  56943. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56944. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56945. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56946. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  56947. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  56948. _this._transformMatrix = BABYLON.Matrix.Zero();
  56949. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  56950. _this._adaptiveBlurKernel = 0;
  56951. _this._blurKernelX = 0;
  56952. _this._blurKernelY = 0;
  56953. _this._blurRatio = 1.0;
  56954. _this.ignoreCameraViewport = true;
  56955. _this.onBeforeRenderObservable.add(function () {
  56956. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  56957. _this._savedViewMatrix = scene.getViewMatrix();
  56958. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  56959. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  56960. scene.clipPlane = _this.mirrorPlane;
  56961. scene.getEngine().cullBackFaces = false;
  56962. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  56963. });
  56964. _this.onAfterRenderObservable.add(function () {
  56965. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  56966. scene.getEngine().cullBackFaces = true;
  56967. scene._mirroredCameraPosition = null;
  56968. delete scene.clipPlane;
  56969. });
  56970. return _this;
  56971. }
  56972. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  56973. get: function () {
  56974. return this._blurRatio;
  56975. },
  56976. set: function (value) {
  56977. if (this._blurRatio === value) {
  56978. return;
  56979. }
  56980. this._blurRatio = value;
  56981. this._preparePostProcesses();
  56982. },
  56983. enumerable: true,
  56984. configurable: true
  56985. });
  56986. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  56987. set: function (value) {
  56988. this._adaptiveBlurKernel = value;
  56989. this._autoComputeBlurKernel();
  56990. },
  56991. enumerable: true,
  56992. configurable: true
  56993. });
  56994. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  56995. set: function (value) {
  56996. this.blurKernelX = value;
  56997. this.blurKernelY = value;
  56998. },
  56999. enumerable: true,
  57000. configurable: true
  57001. });
  57002. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  57003. get: function () {
  57004. return this._blurKernelX;
  57005. },
  57006. set: function (value) {
  57007. if (this._blurKernelX === value) {
  57008. return;
  57009. }
  57010. this._blurKernelX = value;
  57011. this._preparePostProcesses();
  57012. },
  57013. enumerable: true,
  57014. configurable: true
  57015. });
  57016. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  57017. get: function () {
  57018. return this._blurKernelY;
  57019. },
  57020. set: function (value) {
  57021. if (this._blurKernelY === value) {
  57022. return;
  57023. }
  57024. this._blurKernelY = value;
  57025. this._preparePostProcesses();
  57026. },
  57027. enumerable: true,
  57028. configurable: true
  57029. });
  57030. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  57031. var engine = this.getScene().getEngine();
  57032. var dw = this.getRenderWidth() / engine.getRenderWidth();
  57033. var dh = this.getRenderHeight() / engine.getRenderHeight();
  57034. this.blurKernelX = this._adaptiveBlurKernel * dw;
  57035. this.blurKernelY = this._adaptiveBlurKernel * dh;
  57036. };
  57037. MirrorTexture.prototype._onRatioRescale = function () {
  57038. if (this._sizeRatio) {
  57039. this.resize(this._initialSizeParameter);
  57040. if (!this._adaptiveBlurKernel) {
  57041. this._preparePostProcesses();
  57042. }
  57043. }
  57044. if (this._adaptiveBlurKernel) {
  57045. this._autoComputeBlurKernel();
  57046. }
  57047. };
  57048. MirrorTexture.prototype._preparePostProcesses = function () {
  57049. this.clearPostProcesses(true);
  57050. if (this._blurKernelX && this._blurKernelY) {
  57051. var engine = this.getScene().getEngine();
  57052. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57053. 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);
  57054. this._blurX.autoClear = false;
  57055. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  57056. this._blurX.inputTexture = this._texture;
  57057. }
  57058. else {
  57059. this._blurX.alwaysForcePOT = true;
  57060. }
  57061. 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);
  57062. this._blurY.autoClear = false;
  57063. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  57064. this.addPostProcess(this._blurX);
  57065. this.addPostProcess(this._blurY);
  57066. }
  57067. else {
  57068. if (this._blurY) {
  57069. this.removePostProcess(this._blurY);
  57070. this._blurY.dispose();
  57071. this._blurY = null;
  57072. }
  57073. if (this._blurX) {
  57074. this.removePostProcess(this._blurX);
  57075. this._blurX.dispose();
  57076. this._blurX = null;
  57077. }
  57078. }
  57079. };
  57080. MirrorTexture.prototype.clone = function () {
  57081. var scene = this.getScene();
  57082. if (!scene) {
  57083. return this;
  57084. }
  57085. var textureSize = this.getSize();
  57086. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  57087. // Base texture
  57088. newTexture.hasAlpha = this.hasAlpha;
  57089. newTexture.level = this.level;
  57090. // Mirror Texture
  57091. newTexture.mirrorPlane = this.mirrorPlane.clone();
  57092. if (this.renderList) {
  57093. newTexture.renderList = this.renderList.slice(0);
  57094. }
  57095. return newTexture;
  57096. };
  57097. MirrorTexture.prototype.serialize = function () {
  57098. if (!this.name) {
  57099. return null;
  57100. }
  57101. var serializationObject = _super.prototype.serialize.call(this);
  57102. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  57103. return serializationObject;
  57104. };
  57105. return MirrorTexture;
  57106. }(BABYLON.RenderTargetTexture));
  57107. BABYLON.MirrorTexture = MirrorTexture;
  57108. })(BABYLON || (BABYLON = {}));
  57109. //# sourceMappingURL=babylon.mirrorTexture.js.map
  57110. var BABYLON;
  57111. (function (BABYLON) {
  57112. /**
  57113. * Creates a refraction texture used by refraction channel of the standard material.
  57114. * @param name the texture name
  57115. * @param size size of the underlying texture
  57116. * @param scene root scene
  57117. */
  57118. var RefractionTexture = /** @class */ (function (_super) {
  57119. __extends(RefractionTexture, _super);
  57120. function RefractionTexture(name, size, scene, generateMipMaps) {
  57121. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  57122. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  57123. _this.depth = 2.0;
  57124. _this.onBeforeRenderObservable.add(function () {
  57125. scene.clipPlane = _this.refractionPlane;
  57126. });
  57127. _this.onAfterRenderObservable.add(function () {
  57128. delete scene.clipPlane;
  57129. });
  57130. return _this;
  57131. }
  57132. RefractionTexture.prototype.clone = function () {
  57133. var scene = this.getScene();
  57134. if (!scene) {
  57135. return this;
  57136. }
  57137. var textureSize = this.getSize();
  57138. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  57139. // Base texture
  57140. newTexture.hasAlpha = this.hasAlpha;
  57141. newTexture.level = this.level;
  57142. // Refraction Texture
  57143. newTexture.refractionPlane = this.refractionPlane.clone();
  57144. if (this.renderList) {
  57145. newTexture.renderList = this.renderList.slice(0);
  57146. }
  57147. newTexture.depth = this.depth;
  57148. return newTexture;
  57149. };
  57150. RefractionTexture.prototype.serialize = function () {
  57151. if (!this.name) {
  57152. return null;
  57153. }
  57154. var serializationObject = _super.prototype.serialize.call(this);
  57155. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  57156. serializationObject.depth = this.depth;
  57157. return serializationObject;
  57158. };
  57159. return RefractionTexture;
  57160. }(BABYLON.RenderTargetTexture));
  57161. BABYLON.RefractionTexture = RefractionTexture;
  57162. })(BABYLON || (BABYLON = {}));
  57163. //# sourceMappingURL=babylon.refractionTexture.js.map
  57164. var BABYLON;
  57165. (function (BABYLON) {
  57166. var DynamicTexture = /** @class */ (function (_super) {
  57167. __extends(DynamicTexture, _super);
  57168. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  57169. if (scene === void 0) { scene = null; }
  57170. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57171. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57172. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  57173. _this.name = name;
  57174. _this._engine = _this.getScene().getEngine();
  57175. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57176. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57177. _this._generateMipMaps = generateMipMaps;
  57178. if (options.getContext) {
  57179. _this._canvas = options;
  57180. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57181. }
  57182. else {
  57183. _this._canvas = document.createElement("canvas");
  57184. if (options.width) {
  57185. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57186. }
  57187. else {
  57188. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  57189. }
  57190. }
  57191. var textureSize = _this.getSize();
  57192. _this._canvas.width = textureSize.width;
  57193. _this._canvas.height = textureSize.height;
  57194. _this._context = _this._canvas.getContext("2d");
  57195. return _this;
  57196. }
  57197. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  57198. get: function () {
  57199. return true;
  57200. },
  57201. enumerable: true,
  57202. configurable: true
  57203. });
  57204. DynamicTexture.prototype._recreate = function (textureSize) {
  57205. this._canvas.width = textureSize.width;
  57206. this._canvas.height = textureSize.height;
  57207. this.releaseInternalTexture();
  57208. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  57209. };
  57210. DynamicTexture.prototype.scale = function (ratio) {
  57211. var textureSize = this.getSize();
  57212. textureSize.width *= ratio;
  57213. textureSize.height *= ratio;
  57214. this._recreate(textureSize);
  57215. };
  57216. DynamicTexture.prototype.scaleTo = function (width, height) {
  57217. var textureSize = this.getSize();
  57218. textureSize.width = width;
  57219. textureSize.height = height;
  57220. this._recreate(textureSize);
  57221. };
  57222. DynamicTexture.prototype.getContext = function () {
  57223. return this._context;
  57224. };
  57225. DynamicTexture.prototype.clear = function () {
  57226. var size = this.getSize();
  57227. this._context.fillRect(0, 0, size.width, size.height);
  57228. };
  57229. DynamicTexture.prototype.update = function (invertY) {
  57230. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  57231. };
  57232. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  57233. if (update === void 0) { update = true; }
  57234. var size = this.getSize();
  57235. if (clearColor) {
  57236. this._context.fillStyle = clearColor;
  57237. this._context.fillRect(0, 0, size.width, size.height);
  57238. }
  57239. this._context.font = font;
  57240. if (x === null || x === undefined) {
  57241. var textSize = this._context.measureText(text);
  57242. x = (size.width - textSize.width) / 2;
  57243. }
  57244. if (y === null || y === undefined) {
  57245. var fontSize = parseInt((font.replace(/\D/g, '')));
  57246. ;
  57247. y = (size.height / 2) + (fontSize / 3.65);
  57248. }
  57249. this._context.fillStyle = color;
  57250. this._context.fillText(text, x, y);
  57251. if (update) {
  57252. this.update(invertY);
  57253. }
  57254. };
  57255. DynamicTexture.prototype.clone = function () {
  57256. var scene = this.getScene();
  57257. if (!scene) {
  57258. return this;
  57259. }
  57260. var textureSize = this.getSize();
  57261. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  57262. // Base texture
  57263. newTexture.hasAlpha = this.hasAlpha;
  57264. newTexture.level = this.level;
  57265. // Dynamic Texture
  57266. newTexture.wrapU = this.wrapU;
  57267. newTexture.wrapV = this.wrapV;
  57268. return newTexture;
  57269. };
  57270. DynamicTexture.prototype._rebuild = function () {
  57271. this.update();
  57272. };
  57273. return DynamicTexture;
  57274. }(BABYLON.Texture));
  57275. BABYLON.DynamicTexture = DynamicTexture;
  57276. })(BABYLON || (BABYLON = {}));
  57277. //# sourceMappingURL=babylon.dynamicTexture.js.map
  57278. var BABYLON;
  57279. (function (BABYLON) {
  57280. var VideoTexture = /** @class */ (function (_super) {
  57281. __extends(VideoTexture, _super);
  57282. /**
  57283. * Creates a video texture.
  57284. * Sample : https://doc.babylonjs.com/how_to/video_texture
  57285. * @param {string | null} name optional name, will detect from video source, if not defined
  57286. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  57287. * @param {BABYLON.Scene} scene is obviously the current scene.
  57288. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  57289. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  57290. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  57291. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  57292. */
  57293. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  57294. if (generateMipMaps === void 0) { generateMipMaps = false; }
  57295. if (invertY === void 0) { invertY = false; }
  57296. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57297. if (settings === void 0) { settings = {
  57298. autoPlay: true,
  57299. loop: true,
  57300. autoUpdateTexture: true,
  57301. }; }
  57302. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57303. _this._createInternalTexture = function () {
  57304. if (_this._texture != null) {
  57305. return;
  57306. }
  57307. if (!_this._engine.needPOTTextures ||
  57308. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  57309. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57310. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57311. }
  57312. else {
  57313. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57314. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57315. _this._generateMipMaps = false;
  57316. }
  57317. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  57318. _this._texture.isReady = true;
  57319. _this._updateInternalTexture();
  57320. };
  57321. _this.reset = function () {
  57322. if (_this._texture == null) {
  57323. return;
  57324. }
  57325. _this._texture.dispose();
  57326. _this._texture = null;
  57327. };
  57328. _this._updateInternalTexture = function (e) {
  57329. if (_this._texture == null || !_this._texture.isReady) {
  57330. return;
  57331. }
  57332. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  57333. return;
  57334. }
  57335. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  57336. };
  57337. _this._engine = _this.getScene().getEngine();
  57338. _this._generateMipMaps = generateMipMaps;
  57339. _this._samplingMode = samplingMode;
  57340. _this.autoUpdateTexture = settings.autoUpdateTexture;
  57341. _this.name = name || _this._getName(src);
  57342. _this.video = _this._getVideo(src);
  57343. if (settings.autoPlay !== undefined) {
  57344. _this.video.autoplay = settings.autoPlay;
  57345. }
  57346. if (settings.loop !== undefined) {
  57347. _this.video.loop = settings.loop;
  57348. }
  57349. _this.video.addEventListener("canplay", _this._createInternalTexture);
  57350. _this.video.addEventListener("paused", _this._updateInternalTexture);
  57351. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  57352. _this.video.addEventListener("emptied", _this.reset);
  57353. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  57354. _this._createInternalTexture();
  57355. }
  57356. return _this;
  57357. }
  57358. VideoTexture.prototype._getName = function (src) {
  57359. if (src instanceof HTMLVideoElement) {
  57360. return src.currentSrc;
  57361. }
  57362. if (typeof src === "object") {
  57363. return src.toString();
  57364. }
  57365. return src;
  57366. };
  57367. ;
  57368. VideoTexture.prototype._getVideo = function (src) {
  57369. if (src instanceof HTMLVideoElement) {
  57370. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  57371. return src;
  57372. }
  57373. var video = document.createElement("video");
  57374. if (typeof src === "string") {
  57375. BABYLON.Tools.SetCorsBehavior(src, video);
  57376. video.src = src;
  57377. }
  57378. else {
  57379. BABYLON.Tools.SetCorsBehavior(src[0], video);
  57380. src.forEach(function (url) {
  57381. var source = document.createElement("source");
  57382. source.src = url;
  57383. video.appendChild(source);
  57384. });
  57385. }
  57386. return video;
  57387. };
  57388. ;
  57389. /**
  57390. * Internal method to initiate `update`.
  57391. */
  57392. VideoTexture.prototype._rebuild = function () {
  57393. this.update();
  57394. };
  57395. /**
  57396. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  57397. */
  57398. VideoTexture.prototype.update = function () {
  57399. if (!this.autoUpdateTexture) {
  57400. // Expecting user to call `updateTexture` manually
  57401. return;
  57402. }
  57403. this.updateTexture(true);
  57404. };
  57405. /**
  57406. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  57407. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  57408. */
  57409. VideoTexture.prototype.updateTexture = function (isVisible) {
  57410. if (!isVisible) {
  57411. return;
  57412. }
  57413. if (this.video.paused) {
  57414. return;
  57415. }
  57416. this._updateInternalTexture();
  57417. };
  57418. /**
  57419. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  57420. * @param url New url.
  57421. */
  57422. VideoTexture.prototype.updateURL = function (url) {
  57423. this.video.src = url;
  57424. };
  57425. VideoTexture.prototype.dispose = function () {
  57426. _super.prototype.dispose.call(this);
  57427. this.video.removeEventListener("canplay", this._createInternalTexture);
  57428. this.video.removeEventListener("paused", this._updateInternalTexture);
  57429. this.video.removeEventListener("seeked", this._updateInternalTexture);
  57430. this.video.removeEventListener("emptied", this.reset);
  57431. };
  57432. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  57433. var video = document.createElement("video");
  57434. var constraintsDeviceId;
  57435. if (constraints && constraints.deviceId) {
  57436. constraintsDeviceId = {
  57437. exact: constraints.deviceId,
  57438. };
  57439. }
  57440. navigator.getUserMedia =
  57441. navigator.getUserMedia ||
  57442. navigator.webkitGetUserMedia ||
  57443. navigator.mozGetUserMedia ||
  57444. navigator.msGetUserMedia;
  57445. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  57446. if (navigator.getUserMedia) {
  57447. navigator.getUserMedia({
  57448. video: {
  57449. deviceId: constraintsDeviceId,
  57450. width: {
  57451. min: (constraints && constraints.minWidth) || 256,
  57452. max: (constraints && constraints.maxWidth) || 640,
  57453. },
  57454. height: {
  57455. min: (constraints && constraints.minHeight) || 256,
  57456. max: (constraints && constraints.maxHeight) || 480,
  57457. },
  57458. },
  57459. }, function (stream) {
  57460. if (video.mozSrcObject !== undefined) {
  57461. // hack for Firefox < 19
  57462. video.mozSrcObject = stream;
  57463. }
  57464. else {
  57465. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  57466. }
  57467. video.play();
  57468. if (onReady) {
  57469. onReady(new VideoTexture("video", video, scene, true, true));
  57470. }
  57471. }, function (e) {
  57472. BABYLON.Tools.Error(e.name);
  57473. });
  57474. }
  57475. };
  57476. return VideoTexture;
  57477. }(BABYLON.Texture));
  57478. BABYLON.VideoTexture = VideoTexture;
  57479. })(BABYLON || (BABYLON = {}));
  57480. //# sourceMappingURL=babylon.videoTexture.js.map
  57481. var BABYLON;
  57482. (function (BABYLON) {
  57483. var RawTexture = /** @class */ (function (_super) {
  57484. __extends(RawTexture, _super);
  57485. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  57486. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57487. if (invertY === void 0) { invertY = false; }
  57488. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57489. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57490. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57491. _this.format = format;
  57492. _this._engine = scene.getEngine();
  57493. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  57494. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57495. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57496. return _this;
  57497. }
  57498. RawTexture.prototype.update = function (data) {
  57499. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  57500. };
  57501. // Statics
  57502. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57503. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57504. if (invertY === void 0) { invertY = false; }
  57505. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57506. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  57507. };
  57508. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57509. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57510. if (invertY === void 0) { invertY = false; }
  57511. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57512. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57513. };
  57514. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57515. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57516. if (invertY === void 0) { invertY = false; }
  57517. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57518. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57519. };
  57520. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57521. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57522. if (invertY === void 0) { invertY = false; }
  57523. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57524. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57525. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  57526. };
  57527. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57528. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57529. if (invertY === void 0) { invertY = false; }
  57530. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57531. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57532. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  57533. };
  57534. return RawTexture;
  57535. }(BABYLON.Texture));
  57536. BABYLON.RawTexture = RawTexture;
  57537. })(BABYLON || (BABYLON = {}));
  57538. //# sourceMappingURL=babylon.rawTexture.js.map
  57539. var BABYLON;
  57540. (function (BABYLON) {
  57541. /**
  57542. * PostProcess can be used to apply a shader to a texture after it has been rendered
  57543. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  57544. */
  57545. var PostProcess = /** @class */ (function () {
  57546. /**
  57547. * Creates a new instance of @see PostProcess
  57548. * @param name The name of the PostProcess.
  57549. * @param fragmentUrl The url of the fragment shader to be used.
  57550. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  57551. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  57552. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  57553. * @param camera The camera to apply the render pass to.
  57554. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  57555. * @param engine The engine which the post process will be applied. (default: current engine)
  57556. * @param reusable If the post process can be reused on the same frame. (default: false)
  57557. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  57558. * @param textureType Type of textures used when performing the post process. (default: 0)
  57559. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  57560. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  57561. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  57562. */
  57563. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  57564. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  57565. if (defines === void 0) { defines = null; }
  57566. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57567. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  57568. if (blockCompilation === void 0) { blockCompilation = false; }
  57569. this.name = name;
  57570. /**
  57571. * Width of the texture to apply the post process on
  57572. */
  57573. this.width = -1;
  57574. /**
  57575. * Height of the texture to apply the post process on
  57576. */
  57577. this.height = -1;
  57578. /**
  57579. * If the buffer needs to be cleared before applying the post process. (default: true)
  57580. * Should be set to false if shader will overwrite all previous pixels.
  57581. */
  57582. this.autoClear = true;
  57583. /**
  57584. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  57585. */
  57586. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  57587. /**
  57588. * Animations to be used for the post processing
  57589. */
  57590. this.animations = new Array();
  57591. /**
  57592. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  57593. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  57594. */
  57595. this.enablePixelPerfectMode = false;
  57596. /**
  57597. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  57598. */
  57599. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  57600. /**
  57601. * Force textures to be a power of two (default: false)
  57602. */
  57603. this.alwaysForcePOT = false;
  57604. /**
  57605. * Number of sample textures (default: 1)
  57606. */
  57607. this.samples = 1;
  57608. /**
  57609. * Modify the scale of the post process to be the same as the viewport (default: false)
  57610. */
  57611. this.adaptScaleToCurrentViewport = false;
  57612. this._reusable = false;
  57613. /**
  57614. * Smart array of input and output textures for the post process.
  57615. */
  57616. this._textures = new BABYLON.SmartArray(2);
  57617. /**
  57618. * The index in _textures that corresponds to the output texture.
  57619. */
  57620. this._currentRenderTextureInd = 0;
  57621. this._scaleRatio = new BABYLON.Vector2(1, 1);
  57622. this._texelSize = BABYLON.Vector2.Zero();
  57623. // Events
  57624. /**
  57625. * An event triggered when the postprocess is activated.
  57626. * @type {BABYLON.Observable}
  57627. */
  57628. this.onActivateObservable = new BABYLON.Observable();
  57629. /**
  57630. * An event triggered when the postprocess changes its size.
  57631. * @type {BABYLON.Observable}
  57632. */
  57633. this.onSizeChangedObservable = new BABYLON.Observable();
  57634. /**
  57635. * An event triggered when the postprocess applies its effect.
  57636. * @type {BABYLON.Observable}
  57637. */
  57638. this.onApplyObservable = new BABYLON.Observable();
  57639. /**
  57640. * An event triggered before rendering the postprocess
  57641. * @type {BABYLON.Observable}
  57642. */
  57643. this.onBeforeRenderObservable = new BABYLON.Observable();
  57644. /**
  57645. * An event triggered after rendering the postprocess
  57646. * @type {BABYLON.Observable}
  57647. */
  57648. this.onAfterRenderObservable = new BABYLON.Observable();
  57649. if (camera != null) {
  57650. this._camera = camera;
  57651. this._scene = camera.getScene();
  57652. camera.attachPostProcess(this);
  57653. this._engine = this._scene.getEngine();
  57654. this._scene.postProcesses.push(this);
  57655. }
  57656. else if (engine) {
  57657. this._engine = engine;
  57658. this._engine.postProcesses.push(this);
  57659. }
  57660. this._options = options;
  57661. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  57662. this._reusable = reusable || false;
  57663. this._textureType = textureType;
  57664. this._samplers = samplers || [];
  57665. this._samplers.push("textureSampler");
  57666. this._fragmentUrl = fragmentUrl;
  57667. this._vertexUrl = vertexUrl;
  57668. this._parameters = parameters || [];
  57669. this._parameters.push("scale");
  57670. this._indexParameters = indexParameters;
  57671. if (!blockCompilation) {
  57672. this.updateEffect(defines);
  57673. }
  57674. }
  57675. Object.defineProperty(PostProcess.prototype, "onActivate", {
  57676. /**
  57677. * A function that is added to the onActivateObservable
  57678. */
  57679. set: function (callback) {
  57680. if (this._onActivateObserver) {
  57681. this.onActivateObservable.remove(this._onActivateObserver);
  57682. }
  57683. if (callback) {
  57684. this._onActivateObserver = this.onActivateObservable.add(callback);
  57685. }
  57686. },
  57687. enumerable: true,
  57688. configurable: true
  57689. });
  57690. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  57691. /**
  57692. * A function that is added to the onSizeChangedObservable
  57693. */
  57694. set: function (callback) {
  57695. if (this._onSizeChangedObserver) {
  57696. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  57697. }
  57698. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  57699. },
  57700. enumerable: true,
  57701. configurable: true
  57702. });
  57703. Object.defineProperty(PostProcess.prototype, "onApply", {
  57704. /**
  57705. * A function that is added to the onApplyObservable
  57706. */
  57707. set: function (callback) {
  57708. if (this._onApplyObserver) {
  57709. this.onApplyObservable.remove(this._onApplyObserver);
  57710. }
  57711. this._onApplyObserver = this.onApplyObservable.add(callback);
  57712. },
  57713. enumerable: true,
  57714. configurable: true
  57715. });
  57716. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  57717. /**
  57718. * A function that is added to the onBeforeRenderObservable
  57719. */
  57720. set: function (callback) {
  57721. if (this._onBeforeRenderObserver) {
  57722. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57723. }
  57724. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57725. },
  57726. enumerable: true,
  57727. configurable: true
  57728. });
  57729. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  57730. /**
  57731. * A function that is added to the onAfterRenderObservable
  57732. */
  57733. set: function (callback) {
  57734. if (this._onAfterRenderObserver) {
  57735. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57736. }
  57737. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57738. },
  57739. enumerable: true,
  57740. configurable: true
  57741. });
  57742. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  57743. /**
  57744. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  57745. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  57746. */
  57747. get: function () {
  57748. return this._textures.data[this._currentRenderTextureInd];
  57749. },
  57750. set: function (value) {
  57751. this._forcedOutputTexture = value;
  57752. },
  57753. enumerable: true,
  57754. configurable: true
  57755. });
  57756. /**
  57757. * Gets the camera which post process is applied to.
  57758. * @returns The camera the post process is applied to.
  57759. */
  57760. PostProcess.prototype.getCamera = function () {
  57761. return this._camera;
  57762. };
  57763. Object.defineProperty(PostProcess.prototype, "texelSize", {
  57764. /**
  57765. * Gets the texel size of the postprocess.
  57766. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  57767. */
  57768. get: function () {
  57769. if (this._shareOutputWithPostProcess) {
  57770. return this._shareOutputWithPostProcess.texelSize;
  57771. }
  57772. if (this._forcedOutputTexture) {
  57773. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  57774. }
  57775. return this._texelSize;
  57776. },
  57777. enumerable: true,
  57778. configurable: true
  57779. });
  57780. /**
  57781. * Gets the engine which this post process belongs to.
  57782. * @returns The engine the post process was enabled with.
  57783. */
  57784. PostProcess.prototype.getEngine = function () {
  57785. return this._engine;
  57786. };
  57787. /**
  57788. * The effect that is created when initializing the post process.
  57789. * @returns The created effect corrisponding the the postprocess.
  57790. */
  57791. PostProcess.prototype.getEffect = function () {
  57792. return this._effect;
  57793. };
  57794. /**
  57795. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  57796. * @param postProcess The post process to share the output with.
  57797. * @returns This post process.
  57798. */
  57799. PostProcess.prototype.shareOutputWith = function (postProcess) {
  57800. this._disposeTextures();
  57801. this._shareOutputWithPostProcess = postProcess;
  57802. return this;
  57803. };
  57804. /**
  57805. * Updates the effect with the current post process compile time values and recompiles the shader.
  57806. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  57807. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  57808. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  57809. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  57810. * @param onCompiled Called when the shader has been compiled.
  57811. * @param onError Called if there is an error when compiling a shader.
  57812. */
  57813. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  57814. if (defines === void 0) { defines = null; }
  57815. if (uniforms === void 0) { uniforms = null; }
  57816. if (samplers === void 0) { samplers = null; }
  57817. 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);
  57818. };
  57819. /**
  57820. * The post process is reusable if it can be used multiple times within one frame.
  57821. * @returns If the post process is reusable
  57822. */
  57823. PostProcess.prototype.isReusable = function () {
  57824. return this._reusable;
  57825. };
  57826. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  57827. PostProcess.prototype.markTextureDirty = function () {
  57828. this.width = -1;
  57829. };
  57830. /**
  57831. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  57832. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  57833. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  57834. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  57835. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  57836. */
  57837. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  57838. var _this = this;
  57839. if (sourceTexture === void 0) { sourceTexture = null; }
  57840. camera = camera || this._camera;
  57841. var scene = camera.getScene();
  57842. var engine = scene.getEngine();
  57843. var maxSize = engine.getCaps().maxTextureSize;
  57844. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  57845. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  57846. var desiredWidth = (this._options.width || requiredWidth);
  57847. var desiredHeight = this._options.height || requiredHeight;
  57848. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  57849. if (this.adaptScaleToCurrentViewport) {
  57850. var currentViewport = engine.currentViewport;
  57851. if (currentViewport) {
  57852. desiredWidth *= currentViewport.width;
  57853. desiredHeight *= currentViewport.height;
  57854. }
  57855. }
  57856. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  57857. if (!this._options.width) {
  57858. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  57859. }
  57860. if (!this._options.height) {
  57861. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  57862. }
  57863. }
  57864. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  57865. if (this._textures.length > 0) {
  57866. for (var i = 0; i < this._textures.length; i++) {
  57867. this._engine._releaseTexture(this._textures.data[i]);
  57868. }
  57869. this._textures.reset();
  57870. }
  57871. this.width = desiredWidth;
  57872. this.height = desiredHeight;
  57873. var textureSize = { width: this.width, height: this.height };
  57874. var textureOptions = {
  57875. generateMipMaps: false,
  57876. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  57877. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  57878. samplingMode: this.renderTargetSamplingMode,
  57879. type: this._textureType
  57880. };
  57881. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57882. if (this._reusable) {
  57883. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57884. }
  57885. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  57886. this.onSizeChangedObservable.notifyObservers(this);
  57887. }
  57888. this._textures.forEach(function (texture) {
  57889. if (texture.samples !== _this.samples) {
  57890. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  57891. }
  57892. });
  57893. }
  57894. var target;
  57895. if (this._shareOutputWithPostProcess) {
  57896. target = this._shareOutputWithPostProcess.inputTexture;
  57897. }
  57898. else if (this._forcedOutputTexture) {
  57899. target = this._forcedOutputTexture;
  57900. this.width = this._forcedOutputTexture.width;
  57901. this.height = this._forcedOutputTexture.height;
  57902. }
  57903. else {
  57904. target = this.inputTexture;
  57905. }
  57906. // Bind the input of this post process to be used as the output of the previous post process.
  57907. if (this.enablePixelPerfectMode) {
  57908. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  57909. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  57910. }
  57911. else {
  57912. this._scaleRatio.copyFromFloats(1, 1);
  57913. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  57914. }
  57915. this.onActivateObservable.notifyObservers(camera);
  57916. // Clear
  57917. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  57918. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  57919. }
  57920. if (this._reusable) {
  57921. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  57922. }
  57923. };
  57924. Object.defineProperty(PostProcess.prototype, "isSupported", {
  57925. /**
  57926. * If the post process is supported.
  57927. */
  57928. get: function () {
  57929. return this._effect.isSupported;
  57930. },
  57931. enumerable: true,
  57932. configurable: true
  57933. });
  57934. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  57935. /**
  57936. * The aspect ratio of the output texture.
  57937. */
  57938. get: function () {
  57939. if (this._shareOutputWithPostProcess) {
  57940. return this._shareOutputWithPostProcess.aspectRatio;
  57941. }
  57942. if (this._forcedOutputTexture) {
  57943. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  57944. }
  57945. return this.width / this.height;
  57946. },
  57947. enumerable: true,
  57948. configurable: true
  57949. });
  57950. /**
  57951. * Get a value indicating if the post-process is ready to be used
  57952. * @returns true if the post-process is ready (shader is compiled)
  57953. */
  57954. PostProcess.prototype.isReady = function () {
  57955. return this._effect && this._effect.isReady();
  57956. };
  57957. /**
  57958. * Binds all textures and uniforms to the shader, this will be run on every pass.
  57959. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  57960. */
  57961. PostProcess.prototype.apply = function () {
  57962. // Check
  57963. if (!this._effect || !this._effect.isReady())
  57964. return null;
  57965. // States
  57966. this._engine.enableEffect(this._effect);
  57967. this._engine.setState(false);
  57968. this._engine.setDepthBuffer(false);
  57969. this._engine.setDepthWrite(false);
  57970. // Alpha
  57971. this._engine.setAlphaMode(this.alphaMode);
  57972. if (this.alphaConstants) {
  57973. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  57974. }
  57975. // Bind the output texture of the preivous post process as the input to this post process.
  57976. var source;
  57977. if (this._shareOutputWithPostProcess) {
  57978. source = this._shareOutputWithPostProcess.inputTexture;
  57979. }
  57980. else if (this._forcedOutputTexture) {
  57981. source = this._forcedOutputTexture;
  57982. }
  57983. else {
  57984. source = this.inputTexture;
  57985. }
  57986. this._effect._bindTexture("textureSampler", source);
  57987. // Parameters
  57988. this._effect.setVector2("scale", this._scaleRatio);
  57989. this.onApplyObservable.notifyObservers(this._effect);
  57990. return this._effect;
  57991. };
  57992. PostProcess.prototype._disposeTextures = function () {
  57993. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  57994. return;
  57995. }
  57996. if (this._textures.length > 0) {
  57997. for (var i = 0; i < this._textures.length; i++) {
  57998. this._engine._releaseTexture(this._textures.data[i]);
  57999. }
  58000. }
  58001. this._textures.dispose();
  58002. };
  58003. /**
  58004. * Disposes the post process.
  58005. * @param camera The camera to dispose the post process on.
  58006. */
  58007. PostProcess.prototype.dispose = function (camera) {
  58008. camera = camera || this._camera;
  58009. this._disposeTextures();
  58010. if (this._scene) {
  58011. var index_1 = this._scene.postProcesses.indexOf(this);
  58012. if (index_1 !== -1) {
  58013. this._scene.postProcesses.splice(index_1, 1);
  58014. }
  58015. }
  58016. else {
  58017. var index_2 = this._engine.postProcesses.indexOf(this);
  58018. if (index_2 !== -1) {
  58019. this._engine.postProcesses.splice(index_2, 1);
  58020. }
  58021. }
  58022. if (!camera) {
  58023. return;
  58024. }
  58025. camera.detachPostProcess(this);
  58026. var index = camera._postProcesses.indexOf(this);
  58027. if (index === 0 && camera._postProcesses.length > 0) {
  58028. this._camera._postProcesses[0].markTextureDirty();
  58029. }
  58030. this.onActivateObservable.clear();
  58031. this.onAfterRenderObservable.clear();
  58032. this.onApplyObservable.clear();
  58033. this.onBeforeRenderObservable.clear();
  58034. this.onSizeChangedObservable.clear();
  58035. };
  58036. return PostProcess;
  58037. }());
  58038. BABYLON.PostProcess = PostProcess;
  58039. })(BABYLON || (BABYLON = {}));
  58040. //# sourceMappingURL=babylon.postProcess.js.map
  58041. var BABYLON;
  58042. (function (BABYLON) {
  58043. var PassPostProcess = /** @class */ (function (_super) {
  58044. __extends(PassPostProcess, _super);
  58045. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58046. if (camera === void 0) { camera = null; }
  58047. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58048. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  58049. }
  58050. return PassPostProcess;
  58051. }(BABYLON.PostProcess));
  58052. BABYLON.PassPostProcess = PassPostProcess;
  58053. })(BABYLON || (BABYLON = {}));
  58054. //# sourceMappingURL=babylon.passPostProcess.js.map
  58055. var __assign = (this && this.__assign) || Object.assign || function(t) {
  58056. for (var s, i = 1, n = arguments.length; i < n; i++) {
  58057. s = arguments[i];
  58058. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  58059. t[p] = s[p];
  58060. }
  58061. return t;
  58062. };
  58063. var BABYLON;
  58064. (function (BABYLON) {
  58065. /**
  58066. * Default implementation of @see IShadowGenerator.
  58067. * This is the main object responsible of generating shadows in the framework.
  58068. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  58069. */
  58070. var ShadowGenerator = /** @class */ (function () {
  58071. /**
  58072. * Creates a ShadowGenerator object.
  58073. * A ShadowGenerator is the required tool to use the shadows.
  58074. * Each light casting shadows needs to use its own ShadowGenerator.
  58075. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  58076. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  58077. * @param light The light object generating the shadows.
  58078. * @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.
  58079. */
  58080. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  58081. this._bias = 0.00005;
  58082. this._blurBoxOffset = 1;
  58083. this._blurScale = 2;
  58084. this._blurKernel = 1;
  58085. this._useKernelBlur = false;
  58086. this._filter = ShadowGenerator.FILTER_NONE;
  58087. this._darkness = 0;
  58088. this._transparencyShadow = false;
  58089. /**
  58090. * Controls the extent to which the shadows fade out at the edge of the frustum
  58091. * Used only by directionals and spots
  58092. */
  58093. this.frustumEdgeFalloff = 0;
  58094. /**
  58095. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  58096. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  58097. * It might on the other hand introduce peter panning.
  58098. */
  58099. this.forceBackFacesOnly = false;
  58100. this._lightDirection = BABYLON.Vector3.Zero();
  58101. this._viewMatrix = BABYLON.Matrix.Zero();
  58102. this._projectionMatrix = BABYLON.Matrix.Zero();
  58103. this._transformMatrix = BABYLON.Matrix.Zero();
  58104. this._currentFaceIndex = 0;
  58105. this._currentFaceIndexCache = 0;
  58106. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  58107. this._mapSize = mapSize;
  58108. this._light = light;
  58109. this._scene = light.getScene();
  58110. light._shadowGenerator = this;
  58111. // Texture type fallback from float to int if not supported.
  58112. var caps = this._scene.getEngine().getCaps();
  58113. if (!useFullFloatFirst) {
  58114. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  58115. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58116. }
  58117. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58118. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58119. }
  58120. else {
  58121. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58122. }
  58123. }
  58124. else {
  58125. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58126. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58127. }
  58128. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  58129. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58130. }
  58131. else {
  58132. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58133. }
  58134. }
  58135. this._initializeGenerator();
  58136. }
  58137. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  58138. /**
  58139. * Shadow generator mode None: no filtering applied.
  58140. */
  58141. get: function () {
  58142. return ShadowGenerator._FILTER_NONE;
  58143. },
  58144. enumerable: true,
  58145. configurable: true
  58146. });
  58147. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  58148. /**
  58149. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  58150. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  58151. */
  58152. get: function () {
  58153. return ShadowGenerator._FILTER_POISSONSAMPLING;
  58154. },
  58155. enumerable: true,
  58156. configurable: true
  58157. });
  58158. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  58159. /**
  58160. * Shadow generator mode ESM: Exponential Shadow Mapping.
  58161. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58162. */
  58163. get: function () {
  58164. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  58165. },
  58166. enumerable: true,
  58167. configurable: true
  58168. });
  58169. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  58170. /**
  58171. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  58172. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58173. */
  58174. get: function () {
  58175. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  58176. },
  58177. enumerable: true,
  58178. configurable: true
  58179. });
  58180. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  58181. /**
  58182. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  58183. * edge artifacts on steep falloff.
  58184. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58185. */
  58186. get: function () {
  58187. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58188. },
  58189. enumerable: true,
  58190. configurable: true
  58191. });
  58192. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  58193. /**
  58194. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  58195. * edge artifacts on steep falloff.
  58196. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58197. */
  58198. get: function () {
  58199. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58200. },
  58201. enumerable: true,
  58202. configurable: true
  58203. });
  58204. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  58205. /**
  58206. * Gets the bias: offset applied on the depth preventing acnea.
  58207. */
  58208. get: function () {
  58209. return this._bias;
  58210. },
  58211. /**
  58212. * Sets the bias: offset applied on the depth preventing acnea.
  58213. */
  58214. set: function (bias) {
  58215. this._bias = bias;
  58216. },
  58217. enumerable: true,
  58218. configurable: true
  58219. });
  58220. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  58221. /**
  58222. * Gets the blur box offset: offset applied during the blur pass.
  58223. * Only usefull if useKernelBlur = false
  58224. */
  58225. get: function () {
  58226. return this._blurBoxOffset;
  58227. },
  58228. /**
  58229. * Sets the blur box offset: offset applied during the blur pass.
  58230. * Only usefull if useKernelBlur = false
  58231. */
  58232. set: function (value) {
  58233. if (this._blurBoxOffset === value) {
  58234. return;
  58235. }
  58236. this._blurBoxOffset = value;
  58237. this._disposeBlurPostProcesses();
  58238. },
  58239. enumerable: true,
  58240. configurable: true
  58241. });
  58242. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  58243. /**
  58244. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  58245. * 2 means half of the size.
  58246. */
  58247. get: function () {
  58248. return this._blurScale;
  58249. },
  58250. /**
  58251. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  58252. * 2 means half of the size.
  58253. */
  58254. set: function (value) {
  58255. if (this._blurScale === value) {
  58256. return;
  58257. }
  58258. this._blurScale = value;
  58259. this._disposeBlurPostProcesses();
  58260. },
  58261. enumerable: true,
  58262. configurable: true
  58263. });
  58264. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  58265. /**
  58266. * Gets the blur kernel: kernel size of the blur pass.
  58267. * Only usefull if useKernelBlur = true
  58268. */
  58269. get: function () {
  58270. return this._blurKernel;
  58271. },
  58272. /**
  58273. * Sets the blur kernel: kernel size of the blur pass.
  58274. * Only usefull if useKernelBlur = true
  58275. */
  58276. set: function (value) {
  58277. if (this._blurKernel === value) {
  58278. return;
  58279. }
  58280. this._blurKernel = value;
  58281. this._disposeBlurPostProcesses();
  58282. },
  58283. enumerable: true,
  58284. configurable: true
  58285. });
  58286. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  58287. /**
  58288. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  58289. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58290. */
  58291. get: function () {
  58292. return this._useKernelBlur;
  58293. },
  58294. /**
  58295. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  58296. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58297. */
  58298. set: function (value) {
  58299. if (this._useKernelBlur === value) {
  58300. return;
  58301. }
  58302. this._useKernelBlur = value;
  58303. this._disposeBlurPostProcesses();
  58304. },
  58305. enumerable: true,
  58306. configurable: true
  58307. });
  58308. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  58309. /**
  58310. * Gets the depth scale used in ESM mode.
  58311. */
  58312. get: function () {
  58313. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  58314. },
  58315. /**
  58316. * Sets the depth scale used in ESM mode.
  58317. * This can override the scale stored on the light.
  58318. */
  58319. set: function (value) {
  58320. this._depthScale = value;
  58321. },
  58322. enumerable: true,
  58323. configurable: true
  58324. });
  58325. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  58326. /**
  58327. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  58328. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58329. */
  58330. get: function () {
  58331. return this._filter;
  58332. },
  58333. /**
  58334. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  58335. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58336. */
  58337. set: function (value) {
  58338. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  58339. if (this._light.needCube()) {
  58340. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58341. this.useExponentialShadowMap = true;
  58342. return;
  58343. }
  58344. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58345. this.useCloseExponentialShadowMap = true;
  58346. return;
  58347. }
  58348. }
  58349. if (this._filter === value) {
  58350. return;
  58351. }
  58352. this._filter = value;
  58353. this._disposeBlurPostProcesses();
  58354. this._applyFilterValues();
  58355. this._light._markMeshesAsLightDirty();
  58356. },
  58357. enumerable: true,
  58358. configurable: true
  58359. });
  58360. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  58361. /**
  58362. * Gets if the current filter is set to Poisson Sampling aka PCF.
  58363. */
  58364. get: function () {
  58365. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  58366. },
  58367. /**
  58368. * Sets the current filter to Poisson Sampling aka PCF.
  58369. */
  58370. set: function (value) {
  58371. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  58372. return;
  58373. }
  58374. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  58375. },
  58376. enumerable: true,
  58377. configurable: true
  58378. });
  58379. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  58380. /**
  58381. * Gets if the current filter is set to VSM.
  58382. * DEPRECATED. Should use useExponentialShadowMap instead.
  58383. */
  58384. get: function () {
  58385. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58386. return this.useExponentialShadowMap;
  58387. },
  58388. /**
  58389. * Sets the current filter is to VSM.
  58390. * DEPRECATED. Should use useExponentialShadowMap instead.
  58391. */
  58392. set: function (value) {
  58393. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58394. this.useExponentialShadowMap = value;
  58395. },
  58396. enumerable: true,
  58397. configurable: true
  58398. });
  58399. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  58400. /**
  58401. * Gets if the current filter is set to blurred VSM.
  58402. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58403. */
  58404. get: function () {
  58405. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58406. return this.useBlurExponentialShadowMap;
  58407. },
  58408. /**
  58409. * Sets the current filter is to blurred VSM.
  58410. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58411. */
  58412. set: function (value) {
  58413. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58414. this.useBlurExponentialShadowMap = value;
  58415. },
  58416. enumerable: true,
  58417. configurable: true
  58418. });
  58419. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  58420. /**
  58421. * Gets if the current filter is set to ESM.
  58422. */
  58423. get: function () {
  58424. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  58425. },
  58426. /**
  58427. * Sets the current filter is to ESM.
  58428. */
  58429. set: function (value) {
  58430. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  58431. return;
  58432. }
  58433. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58434. },
  58435. enumerable: true,
  58436. configurable: true
  58437. });
  58438. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  58439. /**
  58440. * Gets if the current filter is set to filtered ESM.
  58441. */
  58442. get: function () {
  58443. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  58444. },
  58445. /**
  58446. * Gets if the current filter is set to filtered ESM.
  58447. */
  58448. set: function (value) {
  58449. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58450. return;
  58451. }
  58452. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58453. },
  58454. enumerable: true,
  58455. configurable: true
  58456. });
  58457. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  58458. /**
  58459. * Gets if the current filter is set to "close ESM" (using the inverse of the
  58460. * exponential to prevent steep falloff artifacts).
  58461. */
  58462. get: function () {
  58463. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58464. },
  58465. /**
  58466. * Sets the current filter to "close ESM" (using the inverse of the
  58467. * exponential to prevent steep falloff artifacts).
  58468. */
  58469. set: function (value) {
  58470. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  58471. return;
  58472. }
  58473. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58474. },
  58475. enumerable: true,
  58476. configurable: true
  58477. });
  58478. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  58479. /**
  58480. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  58481. * exponential to prevent steep falloff artifacts).
  58482. */
  58483. get: function () {
  58484. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58485. },
  58486. /**
  58487. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  58488. * exponential to prevent steep falloff artifacts).
  58489. */
  58490. set: function (value) {
  58491. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58492. return;
  58493. }
  58494. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58495. },
  58496. enumerable: true,
  58497. configurable: true
  58498. });
  58499. /**
  58500. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  58501. * 0 means strongest and 1 would means no shadow.
  58502. * @returns the darkness.
  58503. */
  58504. ShadowGenerator.prototype.getDarkness = function () {
  58505. return this._darkness;
  58506. };
  58507. /**
  58508. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  58509. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  58510. * @returns the shadow generator allowing fluent coding.
  58511. */
  58512. ShadowGenerator.prototype.setDarkness = function (darkness) {
  58513. if (darkness >= 1.0)
  58514. this._darkness = 1.0;
  58515. else if (darkness <= 0.0)
  58516. this._darkness = 0.0;
  58517. else
  58518. this._darkness = darkness;
  58519. return this;
  58520. };
  58521. /**
  58522. * Sets the ability to have transparent shadow (boolean).
  58523. * @param transparent True if transparent else False
  58524. * @returns the shadow generator allowing fluent coding
  58525. */
  58526. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  58527. this._transparencyShadow = transparent;
  58528. return this;
  58529. };
  58530. /**
  58531. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  58532. * @returns The render target texture if present otherwise, null
  58533. */
  58534. ShadowGenerator.prototype.getShadowMap = function () {
  58535. return this._shadowMap;
  58536. };
  58537. /**
  58538. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  58539. * @returns The render target texture if the shadow map is present otherwise, null
  58540. */
  58541. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  58542. if (this._shadowMap2) {
  58543. return this._shadowMap2;
  58544. }
  58545. return this._shadowMap;
  58546. };
  58547. /**
  58548. * Helper function to add a mesh and its descendants to the list of shadow casters.
  58549. * @param mesh Mesh to add
  58550. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  58551. * @returns the Shadow Generator itself
  58552. */
  58553. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  58554. if (includeDescendants === void 0) { includeDescendants = true; }
  58555. if (!this._shadowMap) {
  58556. return this;
  58557. }
  58558. if (!this._shadowMap.renderList) {
  58559. this._shadowMap.renderList = [];
  58560. }
  58561. this._shadowMap.renderList.push(mesh);
  58562. if (includeDescendants) {
  58563. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  58564. }
  58565. return this;
  58566. var _a;
  58567. };
  58568. /**
  58569. * Helper function to remove a mesh and its descendants from the list of shadow casters
  58570. * @param mesh Mesh to remove
  58571. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  58572. * @returns the Shadow Generator itself
  58573. */
  58574. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  58575. if (includeDescendants === void 0) { includeDescendants = true; }
  58576. if (!this._shadowMap || !this._shadowMap.renderList) {
  58577. return this;
  58578. }
  58579. var index = this._shadowMap.renderList.indexOf(mesh);
  58580. if (index !== -1) {
  58581. this._shadowMap.renderList.splice(index, 1);
  58582. }
  58583. if (includeDescendants) {
  58584. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  58585. var child = _a[_i];
  58586. this.removeShadowCaster(child);
  58587. }
  58588. }
  58589. return this;
  58590. };
  58591. /**
  58592. * Returns the associated light object.
  58593. * @returns the light generating the shadow
  58594. */
  58595. ShadowGenerator.prototype.getLight = function () {
  58596. return this._light;
  58597. };
  58598. ShadowGenerator.prototype._initializeGenerator = function () {
  58599. this._light._markMeshesAsLightDirty();
  58600. this._initializeShadowMap();
  58601. };
  58602. ShadowGenerator.prototype._initializeShadowMap = function () {
  58603. var _this = this;
  58604. // Render target
  58605. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  58606. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58607. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58608. this._shadowMap.anisotropicFilteringLevel = 1;
  58609. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58610. this._shadowMap.renderParticles = false;
  58611. this._shadowMap.ignoreCameraViewport = true;
  58612. // Record Face Index before render.
  58613. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  58614. _this._currentFaceIndex = faceIndex;
  58615. });
  58616. // Custom render function.
  58617. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  58618. // Blur if required afer render.
  58619. this._shadowMap.onAfterUnbindObservable.add(function () {
  58620. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  58621. return;
  58622. }
  58623. var shadowMap = _this.getShadowMapForRendering();
  58624. if (shadowMap) {
  58625. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  58626. }
  58627. });
  58628. // Clear according to the chosen filter.
  58629. this._shadowMap.onClearObservable.add(function (engine) {
  58630. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  58631. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  58632. }
  58633. else {
  58634. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58635. }
  58636. });
  58637. };
  58638. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  58639. var _this = this;
  58640. var engine = this._scene.getEngine();
  58641. var targetSize = this._mapSize / this.blurScale;
  58642. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  58643. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  58644. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58645. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58646. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58647. }
  58648. if (this.useKernelBlur) {
  58649. 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);
  58650. this._kernelBlurXPostprocess.width = targetSize;
  58651. this._kernelBlurXPostprocess.height = targetSize;
  58652. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  58653. effect.setTexture("textureSampler", _this._shadowMap);
  58654. });
  58655. 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);
  58656. this._kernelBlurXPostprocess.autoClear = false;
  58657. this._kernelBlurYPostprocess.autoClear = false;
  58658. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58659. this._kernelBlurXPostprocess.packedFloat = true;
  58660. this._kernelBlurYPostprocess.packedFloat = true;
  58661. }
  58662. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  58663. }
  58664. else {
  58665. 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);
  58666. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  58667. effect.setFloat2("screenSize", targetSize, targetSize);
  58668. effect.setTexture("textureSampler", _this._shadowMap);
  58669. });
  58670. this._boxBlurPostprocess.autoClear = false;
  58671. this._blurPostProcesses = [this._boxBlurPostprocess];
  58672. }
  58673. };
  58674. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58675. var index;
  58676. var engine = this._scene.getEngine();
  58677. if (depthOnlySubMeshes.length) {
  58678. engine.setColorWrite(false);
  58679. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58680. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  58681. }
  58682. engine.setColorWrite(true);
  58683. }
  58684. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58685. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  58686. }
  58687. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58688. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  58689. }
  58690. if (this._transparencyShadow) {
  58691. for (index = 0; index < transparentSubMeshes.length; index++) {
  58692. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  58693. }
  58694. }
  58695. };
  58696. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  58697. var _this = this;
  58698. var mesh = subMesh.getRenderingMesh();
  58699. var scene = this._scene;
  58700. var engine = scene.getEngine();
  58701. var material = subMesh.getMaterial();
  58702. if (!material) {
  58703. return;
  58704. }
  58705. // Culling
  58706. engine.setState(material.backFaceCulling);
  58707. // Managing instances
  58708. var batch = mesh._getInstancesRenderList(subMesh._id);
  58709. if (batch.mustReturn) {
  58710. return;
  58711. }
  58712. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  58713. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  58714. engine.enableEffect(this._effect);
  58715. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  58716. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  58717. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  58718. this._effect.setVector3("lightPosition", this.getLight().position);
  58719. if (scene.activeCamera) {
  58720. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  58721. }
  58722. // Alpha test
  58723. if (material && material.needAlphaTesting()) {
  58724. var alphaTexture = material.getAlphaTestTexture();
  58725. if (alphaTexture) {
  58726. this._effect.setTexture("diffuseSampler", alphaTexture);
  58727. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  58728. }
  58729. }
  58730. // Bones
  58731. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58732. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  58733. }
  58734. if (this.forceBackFacesOnly) {
  58735. engine.setState(true, 0, false, true);
  58736. }
  58737. // Draw
  58738. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58739. if (this.forceBackFacesOnly) {
  58740. engine.setState(true, 0, false, false);
  58741. }
  58742. }
  58743. else {
  58744. // Need to reset refresh rate of the shadowMap
  58745. if (this._shadowMap) {
  58746. this._shadowMap.resetRefreshCounter();
  58747. }
  58748. }
  58749. };
  58750. ShadowGenerator.prototype._applyFilterValues = function () {
  58751. if (!this._shadowMap) {
  58752. return;
  58753. }
  58754. if (this.filter === ShadowGenerator.FILTER_NONE) {
  58755. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58756. }
  58757. else {
  58758. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58759. }
  58760. };
  58761. /**
  58762. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58763. * @param onCompiled Callback triggered at the and of the effects compilation
  58764. * @param options Sets of optional options forcing the compilation with different modes
  58765. */
  58766. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  58767. var _this = this;
  58768. var localOptions = __assign({ useInstances: false }, options);
  58769. var shadowMap = this.getShadowMap();
  58770. if (!shadowMap) {
  58771. if (onCompiled) {
  58772. onCompiled(this);
  58773. }
  58774. return;
  58775. }
  58776. var renderList = shadowMap.renderList;
  58777. if (!renderList) {
  58778. if (onCompiled) {
  58779. onCompiled(this);
  58780. }
  58781. return;
  58782. }
  58783. var subMeshes = new Array();
  58784. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  58785. var mesh = renderList_1[_i];
  58786. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  58787. }
  58788. if (subMeshes.length === 0) {
  58789. if (onCompiled) {
  58790. onCompiled(this);
  58791. }
  58792. return;
  58793. }
  58794. var currentIndex = 0;
  58795. var checkReady = function () {
  58796. if (!_this._scene || !_this._scene.getEngine()) {
  58797. return;
  58798. }
  58799. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  58800. currentIndex++;
  58801. if (currentIndex >= subMeshes.length) {
  58802. if (onCompiled) {
  58803. onCompiled(_this);
  58804. }
  58805. return;
  58806. }
  58807. }
  58808. setTimeout(checkReady, 16);
  58809. };
  58810. checkReady();
  58811. };
  58812. /**
  58813. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58814. * @param options Sets of optional options forcing the compilation with different modes
  58815. * @returns A promise that resolves when the compilation completes
  58816. */
  58817. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  58818. var _this = this;
  58819. return new Promise(function (resolve) {
  58820. _this.forceCompilation(function () {
  58821. resolve();
  58822. }, options);
  58823. });
  58824. };
  58825. /**
  58826. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  58827. * @param subMesh The submesh we want to render in the shadow map
  58828. * @param useInstances Defines wether will draw in the map using instances
  58829. * @returns true if ready otherwise, false
  58830. */
  58831. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  58832. var defines = [];
  58833. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58834. defines.push("#define FLOAT");
  58835. }
  58836. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58837. defines.push("#define ESM");
  58838. }
  58839. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58840. var mesh = subMesh.getMesh();
  58841. var material = subMesh.getMaterial();
  58842. // Alpha test
  58843. if (material && material.needAlphaTesting()) {
  58844. var alphaTexture = material.getAlphaTestTexture();
  58845. if (alphaTexture) {
  58846. defines.push("#define ALPHATEST");
  58847. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58848. attribs.push(BABYLON.VertexBuffer.UVKind);
  58849. defines.push("#define UV1");
  58850. }
  58851. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58852. if (alphaTexture.coordinatesIndex === 1) {
  58853. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58854. defines.push("#define UV2");
  58855. }
  58856. }
  58857. }
  58858. }
  58859. // Bones
  58860. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58861. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58862. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58863. if (mesh.numBoneInfluencers > 4) {
  58864. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58865. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58866. }
  58867. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58868. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58869. }
  58870. else {
  58871. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58872. }
  58873. // Instances
  58874. if (useInstances) {
  58875. defines.push("#define INSTANCES");
  58876. attribs.push("world0");
  58877. attribs.push("world1");
  58878. attribs.push("world2");
  58879. attribs.push("world3");
  58880. }
  58881. // Get correct effect
  58882. var join = defines.join("\n");
  58883. if (this._cachedDefines !== join) {
  58884. this._cachedDefines = join;
  58885. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  58886. }
  58887. if (!this._effect.isReady()) {
  58888. return false;
  58889. }
  58890. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58891. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  58892. this._initializeBlurRTTAndPostProcesses();
  58893. }
  58894. }
  58895. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  58896. return false;
  58897. }
  58898. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  58899. return false;
  58900. }
  58901. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  58902. return false;
  58903. }
  58904. return true;
  58905. };
  58906. /**
  58907. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  58908. * @param defines Defines of the material we want to update
  58909. * @param lightIndex Index of the light in the enabled light list of the material
  58910. */
  58911. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  58912. var scene = this._scene;
  58913. var light = this._light;
  58914. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58915. return;
  58916. }
  58917. defines["SHADOW" + lightIndex] = true;
  58918. if (this.usePoissonSampling) {
  58919. defines["SHADOWPCF" + lightIndex] = true;
  58920. }
  58921. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58922. defines["SHADOWESM" + lightIndex] = true;
  58923. }
  58924. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58925. defines["SHADOWCLOSEESM" + lightIndex] = true;
  58926. }
  58927. if (light.needCube()) {
  58928. defines["SHADOWCUBE" + lightIndex] = true;
  58929. }
  58930. };
  58931. /**
  58932. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  58933. * defined in the generator but impacting the effect).
  58934. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  58935. * @param effect The effect we are binfing the information for
  58936. */
  58937. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  58938. var light = this._light;
  58939. var scene = this._scene;
  58940. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58941. return;
  58942. }
  58943. var camera = scene.activeCamera;
  58944. if (!camera) {
  58945. return;
  58946. }
  58947. var shadowMap = this.getShadowMap();
  58948. if (!shadowMap) {
  58949. return;
  58950. }
  58951. if (!light.needCube()) {
  58952. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  58953. }
  58954. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  58955. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  58956. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  58957. };
  58958. /**
  58959. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  58960. * (eq to shadow prjection matrix * light transform matrix)
  58961. * @returns The transform matrix used to create the shadow map
  58962. */
  58963. ShadowGenerator.prototype.getTransformMatrix = function () {
  58964. var scene = this._scene;
  58965. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  58966. return this._transformMatrix;
  58967. }
  58968. this._currentRenderID = scene.getRenderId();
  58969. this._currentFaceIndexCache = this._currentFaceIndex;
  58970. var lightPosition = this._light.position;
  58971. if (this._light.computeTransformedInformation()) {
  58972. lightPosition = this._light.transformedPosition;
  58973. }
  58974. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  58975. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  58976. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  58977. }
  58978. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  58979. this._cachedPosition = lightPosition.clone();
  58980. this._cachedDirection = this._lightDirection.clone();
  58981. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  58982. var shadowMap = this.getShadowMap();
  58983. if (shadowMap) {
  58984. var renderList = shadowMap.renderList;
  58985. if (renderList) {
  58986. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  58987. }
  58988. }
  58989. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  58990. }
  58991. return this._transformMatrix;
  58992. };
  58993. /**
  58994. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  58995. * Cube and 2D textures for instance.
  58996. */
  58997. ShadowGenerator.prototype.recreateShadowMap = function () {
  58998. var shadowMap = this._shadowMap;
  58999. if (!shadowMap) {
  59000. return;
  59001. }
  59002. // Track render list.
  59003. var renderList = shadowMap.renderList;
  59004. // Clean up existing data.
  59005. this._disposeRTTandPostProcesses();
  59006. // Reinitializes.
  59007. this._initializeGenerator();
  59008. // Reaffect the filter to ensure a correct fallback if necessary.
  59009. this.filter = this.filter;
  59010. // Reaffect the filter.
  59011. this._applyFilterValues();
  59012. // Reaffect Render List.
  59013. this._shadowMap.renderList = renderList;
  59014. };
  59015. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  59016. if (this._shadowMap2) {
  59017. this._shadowMap2.dispose();
  59018. this._shadowMap2 = null;
  59019. }
  59020. if (this._boxBlurPostprocess) {
  59021. this._boxBlurPostprocess.dispose();
  59022. this._boxBlurPostprocess = null;
  59023. }
  59024. if (this._kernelBlurXPostprocess) {
  59025. this._kernelBlurXPostprocess.dispose();
  59026. this._kernelBlurXPostprocess = null;
  59027. }
  59028. if (this._kernelBlurYPostprocess) {
  59029. this._kernelBlurYPostprocess.dispose();
  59030. this._kernelBlurYPostprocess = null;
  59031. }
  59032. this._blurPostProcesses = [];
  59033. };
  59034. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  59035. if (this._shadowMap) {
  59036. this._shadowMap.dispose();
  59037. this._shadowMap = null;
  59038. }
  59039. this._disposeBlurPostProcesses();
  59040. };
  59041. /**
  59042. * Disposes the ShadowGenerator.
  59043. * Returns nothing.
  59044. */
  59045. ShadowGenerator.prototype.dispose = function () {
  59046. this._disposeRTTandPostProcesses();
  59047. if (this._light) {
  59048. this._light._shadowGenerator = null;
  59049. this._light._markMeshesAsLightDirty();
  59050. }
  59051. };
  59052. /**
  59053. * Serializes the shadow generator setup to a json object.
  59054. * @returns The serialized JSON object
  59055. */
  59056. ShadowGenerator.prototype.serialize = function () {
  59057. var serializationObject = {};
  59058. var shadowMap = this.getShadowMap();
  59059. if (!shadowMap) {
  59060. return serializationObject;
  59061. }
  59062. serializationObject.lightId = this._light.id;
  59063. serializationObject.mapSize = shadowMap.getRenderSize();
  59064. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  59065. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  59066. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59067. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59068. serializationObject.usePoissonSampling = this.usePoissonSampling;
  59069. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  59070. serializationObject.depthScale = this.depthScale;
  59071. serializationObject.darkness = this.getDarkness();
  59072. serializationObject.blurBoxOffset = this.blurBoxOffset;
  59073. serializationObject.blurKernel = this.blurKernel;
  59074. serializationObject.blurScale = this.blurScale;
  59075. serializationObject.useKernelBlur = this.useKernelBlur;
  59076. serializationObject.transparencyShadow = this._transparencyShadow;
  59077. serializationObject.renderList = [];
  59078. if (shadowMap.renderList) {
  59079. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  59080. var mesh = shadowMap.renderList[meshIndex];
  59081. serializationObject.renderList.push(mesh.id);
  59082. }
  59083. }
  59084. return serializationObject;
  59085. };
  59086. /**
  59087. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  59088. * @param parsedShadowGenerator The JSON object to parse
  59089. * @param scene The scene to create the shadow map for
  59090. * @returns The parsed shadow generator
  59091. */
  59092. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  59093. //casting to point light, as light is missing the position attr and typescript complains.
  59094. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  59095. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  59096. var shadowMap = shadowGenerator.getShadowMap();
  59097. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  59098. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  59099. meshes.forEach(function (mesh) {
  59100. if (!shadowMap) {
  59101. return;
  59102. }
  59103. if (!shadowMap.renderList) {
  59104. shadowMap.renderList = [];
  59105. }
  59106. shadowMap.renderList.push(mesh);
  59107. });
  59108. }
  59109. if (parsedShadowGenerator.usePoissonSampling) {
  59110. shadowGenerator.usePoissonSampling = true;
  59111. }
  59112. else if (parsedShadowGenerator.useExponentialShadowMap) {
  59113. shadowGenerator.useExponentialShadowMap = true;
  59114. }
  59115. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  59116. shadowGenerator.useBlurExponentialShadowMap = true;
  59117. }
  59118. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  59119. shadowGenerator.useCloseExponentialShadowMap = true;
  59120. }
  59121. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  59122. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  59123. }
  59124. else if (parsedShadowGenerator.useVarianceShadowMap) {
  59125. shadowGenerator.useExponentialShadowMap = true;
  59126. }
  59127. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  59128. shadowGenerator.useBlurExponentialShadowMap = true;
  59129. }
  59130. if (parsedShadowGenerator.depthScale) {
  59131. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  59132. }
  59133. if (parsedShadowGenerator.blurScale) {
  59134. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  59135. }
  59136. if (parsedShadowGenerator.blurBoxOffset) {
  59137. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  59138. }
  59139. if (parsedShadowGenerator.useKernelBlur) {
  59140. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  59141. }
  59142. if (parsedShadowGenerator.blurKernel) {
  59143. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  59144. }
  59145. if (parsedShadowGenerator.bias !== undefined) {
  59146. shadowGenerator.bias = parsedShadowGenerator.bias;
  59147. }
  59148. if (parsedShadowGenerator.darkness) {
  59149. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  59150. }
  59151. if (parsedShadowGenerator.transparencyShadow) {
  59152. shadowGenerator.setTransparencyShadow(true);
  59153. }
  59154. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  59155. return shadowGenerator;
  59156. };
  59157. ShadowGenerator._FILTER_NONE = 0;
  59158. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  59159. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  59160. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  59161. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  59162. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  59163. return ShadowGenerator;
  59164. }());
  59165. BABYLON.ShadowGenerator = ShadowGenerator;
  59166. })(BABYLON || (BABYLON = {}));
  59167. //# sourceMappingURL=babylon.shadowGenerator.js.map
  59168. var BABYLON;
  59169. (function (BABYLON) {
  59170. var DefaultLoadingScreen = /** @class */ (function () {
  59171. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  59172. if (_loadingText === void 0) { _loadingText = ""; }
  59173. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  59174. var _this = this;
  59175. this._renderingCanvas = _renderingCanvas;
  59176. this._loadingText = _loadingText;
  59177. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  59178. // Resize
  59179. this._resizeLoadingUI = function () {
  59180. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  59181. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  59182. if (!_this._loadingDiv) {
  59183. return;
  59184. }
  59185. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  59186. _this._loadingDiv.style.left = canvasRect.left + "px";
  59187. _this._loadingDiv.style.top = canvasRect.top + "px";
  59188. _this._loadingDiv.style.width = canvasRect.width + "px";
  59189. _this._loadingDiv.style.height = canvasRect.height + "px";
  59190. };
  59191. }
  59192. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  59193. if (this._loadingDiv) {
  59194. // Do not add a loading screen if there is already one
  59195. return;
  59196. }
  59197. this._loadingDiv = document.createElement("div");
  59198. this._loadingDiv.id = "babylonjsLoadingDiv";
  59199. this._loadingDiv.style.opacity = "0";
  59200. this._loadingDiv.style.transition = "opacity 1.5s ease";
  59201. this._loadingDiv.style.pointerEvents = "none";
  59202. // Loading text
  59203. this._loadingTextDiv = document.createElement("div");
  59204. this._loadingTextDiv.style.position = "absolute";
  59205. this._loadingTextDiv.style.left = "0";
  59206. this._loadingTextDiv.style.top = "50%";
  59207. this._loadingTextDiv.style.marginTop = "80px";
  59208. this._loadingTextDiv.style.width = "100%";
  59209. this._loadingTextDiv.style.height = "20px";
  59210. this._loadingTextDiv.style.fontFamily = "Arial";
  59211. this._loadingTextDiv.style.fontSize = "14px";
  59212. this._loadingTextDiv.style.color = "white";
  59213. this._loadingTextDiv.style.textAlign = "center";
  59214. this._loadingTextDiv.innerHTML = "Loading";
  59215. this._loadingDiv.appendChild(this._loadingTextDiv);
  59216. //set the predefined text
  59217. this._loadingTextDiv.innerHTML = this._loadingText;
  59218. // Generating keyframes
  59219. var style = document.createElement('style');
  59220. style.type = 'text/css';
  59221. 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 }";
  59222. style.innerHTML = keyFrames;
  59223. document.getElementsByTagName('head')[0].appendChild(style);
  59224. // Loading img
  59225. var imgBack = new Image();
  59226. 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";
  59227. imgBack.style.position = "absolute";
  59228. imgBack.style.left = "50%";
  59229. imgBack.style.top = "50%";
  59230. imgBack.style.marginLeft = "-60px";
  59231. imgBack.style.marginTop = "-60px";
  59232. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  59233. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  59234. imgBack.style.transformOrigin = "50% 50%";
  59235. imgBack.style.webkitTransformOrigin = "50% 50%";
  59236. this._loadingDiv.appendChild(imgBack);
  59237. this._resizeLoadingUI();
  59238. window.addEventListener("resize", this._resizeLoadingUI);
  59239. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59240. document.body.appendChild(this._loadingDiv);
  59241. this._loadingDiv.style.opacity = "1";
  59242. };
  59243. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  59244. var _this = this;
  59245. if (!this._loadingDiv) {
  59246. return;
  59247. }
  59248. var onTransitionEnd = function () {
  59249. if (!_this._loadingDiv) {
  59250. return;
  59251. }
  59252. document.body.removeChild(_this._loadingDiv);
  59253. window.removeEventListener("resize", _this._resizeLoadingUI);
  59254. _this._loadingDiv = null;
  59255. };
  59256. this._loadingDiv.style.opacity = "0";
  59257. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  59258. };
  59259. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  59260. set: function (text) {
  59261. this._loadingText = text;
  59262. if (this._loadingTextDiv) {
  59263. this._loadingTextDiv.innerHTML = this._loadingText;
  59264. }
  59265. },
  59266. enumerable: true,
  59267. configurable: true
  59268. });
  59269. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  59270. get: function () {
  59271. return this._loadingDivBackgroundColor;
  59272. },
  59273. set: function (color) {
  59274. this._loadingDivBackgroundColor = color;
  59275. if (!this._loadingDiv) {
  59276. return;
  59277. }
  59278. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59279. },
  59280. enumerable: true,
  59281. configurable: true
  59282. });
  59283. return DefaultLoadingScreen;
  59284. }());
  59285. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  59286. })(BABYLON || (BABYLON = {}));
  59287. //# sourceMappingURL=babylon.loadingScreen.js.map
  59288. var BABYLON;
  59289. (function (BABYLON) {
  59290. var SceneLoaderProgressEvent = /** @class */ (function () {
  59291. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  59292. this.lengthComputable = lengthComputable;
  59293. this.loaded = loaded;
  59294. this.total = total;
  59295. }
  59296. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  59297. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  59298. };
  59299. return SceneLoaderProgressEvent;
  59300. }());
  59301. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  59302. var SceneLoader = /** @class */ (function () {
  59303. function SceneLoader() {
  59304. }
  59305. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  59306. get: function () {
  59307. return 0;
  59308. },
  59309. enumerable: true,
  59310. configurable: true
  59311. });
  59312. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  59313. get: function () {
  59314. return 1;
  59315. },
  59316. enumerable: true,
  59317. configurable: true
  59318. });
  59319. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  59320. get: function () {
  59321. return 2;
  59322. },
  59323. enumerable: true,
  59324. configurable: true
  59325. });
  59326. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  59327. get: function () {
  59328. return 3;
  59329. },
  59330. enumerable: true,
  59331. configurable: true
  59332. });
  59333. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  59334. get: function () {
  59335. return SceneLoader._ForceFullSceneLoadingForIncremental;
  59336. },
  59337. set: function (value) {
  59338. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  59339. },
  59340. enumerable: true,
  59341. configurable: true
  59342. });
  59343. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  59344. get: function () {
  59345. return SceneLoader._ShowLoadingScreen;
  59346. },
  59347. set: function (value) {
  59348. SceneLoader._ShowLoadingScreen = value;
  59349. },
  59350. enumerable: true,
  59351. configurable: true
  59352. });
  59353. Object.defineProperty(SceneLoader, "loggingLevel", {
  59354. get: function () {
  59355. return SceneLoader._loggingLevel;
  59356. },
  59357. set: function (value) {
  59358. SceneLoader._loggingLevel = value;
  59359. },
  59360. enumerable: true,
  59361. configurable: true
  59362. });
  59363. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  59364. get: function () {
  59365. return SceneLoader._CleanBoneMatrixWeights;
  59366. },
  59367. set: function (value) {
  59368. SceneLoader._CleanBoneMatrixWeights = value;
  59369. },
  59370. enumerable: true,
  59371. configurable: true
  59372. });
  59373. SceneLoader._getDefaultPlugin = function () {
  59374. return SceneLoader._registeredPlugins[".babylon"];
  59375. };
  59376. SceneLoader._getPluginForExtension = function (extension) {
  59377. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  59378. if (registeredPlugin) {
  59379. return registeredPlugin;
  59380. }
  59381. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  59382. return SceneLoader._getDefaultPlugin();
  59383. };
  59384. SceneLoader._getPluginForDirectLoad = function (data) {
  59385. for (var extension in SceneLoader._registeredPlugins) {
  59386. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  59387. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  59388. return SceneLoader._registeredPlugins[extension];
  59389. }
  59390. }
  59391. return SceneLoader._getDefaultPlugin();
  59392. };
  59393. SceneLoader._getPluginForFilename = function (sceneFilename) {
  59394. if (sceneFilename.name) {
  59395. sceneFilename = sceneFilename.name;
  59396. }
  59397. var queryStringPosition = sceneFilename.indexOf("?");
  59398. if (queryStringPosition !== -1) {
  59399. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  59400. }
  59401. var dotPosition = sceneFilename.lastIndexOf(".");
  59402. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  59403. return SceneLoader._getPluginForExtension(extension);
  59404. };
  59405. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  59406. SceneLoader._getDirectLoad = function (sceneFilename) {
  59407. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  59408. return sceneFilename.substr(5);
  59409. }
  59410. return null;
  59411. };
  59412. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  59413. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  59414. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  59415. var plugin;
  59416. if (registeredPlugin.plugin.createPlugin) {
  59417. plugin = registeredPlugin.plugin.createPlugin();
  59418. }
  59419. else {
  59420. plugin = registeredPlugin.plugin;
  59421. }
  59422. var useArrayBuffer = registeredPlugin.isBinary;
  59423. var database;
  59424. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  59425. var dataCallback = function (data, responseURL) {
  59426. if (scene.isDisposed) {
  59427. onError("Scene has been disposed");
  59428. return;
  59429. }
  59430. scene.database = database;
  59431. onSuccess(plugin, data, responseURL);
  59432. };
  59433. var request = null;
  59434. var pluginDisposed = false;
  59435. var onDisposeObservable = plugin.onDisposeObservable;
  59436. if (onDisposeObservable) {
  59437. onDisposeObservable.add(function () {
  59438. pluginDisposed = true;
  59439. if (request) {
  59440. request.abort();
  59441. request = null;
  59442. }
  59443. onDispose();
  59444. });
  59445. }
  59446. var manifestChecked = function () {
  59447. if (pluginDisposed) {
  59448. return;
  59449. }
  59450. var url = rootUrl + sceneFilename;
  59451. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  59452. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  59453. } : undefined, database, useArrayBuffer, function (request, exception) {
  59454. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  59455. });
  59456. };
  59457. if (directLoad) {
  59458. dataCallback(directLoad);
  59459. return plugin;
  59460. }
  59461. if (rootUrl.indexOf("file:") === -1) {
  59462. if (scene.getEngine().enableOfflineSupport) {
  59463. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  59464. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  59465. }
  59466. else {
  59467. manifestChecked();
  59468. }
  59469. }
  59470. else {
  59471. var fileOrString = sceneFilename;
  59472. if (fileOrString.name) {
  59473. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  59474. }
  59475. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  59476. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  59477. }
  59478. else {
  59479. onError("Unable to find file named " + sceneFilename);
  59480. }
  59481. }
  59482. return plugin;
  59483. };
  59484. // Public functions
  59485. SceneLoader.GetPluginForExtension = function (extension) {
  59486. return SceneLoader._getPluginForExtension(extension).plugin;
  59487. };
  59488. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  59489. return !!SceneLoader._registeredPlugins[extension];
  59490. };
  59491. SceneLoader.RegisterPlugin = function (plugin) {
  59492. if (typeof plugin.extensions === "string") {
  59493. var extension = plugin.extensions;
  59494. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59495. plugin: plugin,
  59496. isBinary: false
  59497. };
  59498. }
  59499. else {
  59500. var extensions = plugin.extensions;
  59501. Object.keys(extensions).forEach(function (extension) {
  59502. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59503. plugin: plugin,
  59504. isBinary: extensions[extension].isBinary
  59505. };
  59506. });
  59507. }
  59508. };
  59509. /**
  59510. * Import meshes into a scene
  59511. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59512. * @param rootUrl a string that defines the root url for scene and resources
  59513. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59514. * @param scene the instance of BABYLON.Scene to append to
  59515. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  59516. * @param onProgress a callback with a progress event for each file being loaded
  59517. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59518. * @param pluginExtension the extension used to determine the plugin
  59519. * @returns The loaded plugin
  59520. */
  59521. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59522. if (onSuccess === void 0) { onSuccess = null; }
  59523. if (onProgress === void 0) { onProgress = null; }
  59524. if (onError === void 0) { onError = null; }
  59525. if (pluginExtension === void 0) { pluginExtension = null; }
  59526. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59527. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59528. return null;
  59529. }
  59530. var loadingToken = {};
  59531. scene._addPendingData(loadingToken);
  59532. var disposeHandler = function () {
  59533. scene._removePendingData(loadingToken);
  59534. };
  59535. var errorHandler = function (message, exception) {
  59536. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  59537. if (onError) {
  59538. onError(scene, errorMessage, exception);
  59539. }
  59540. else {
  59541. BABYLON.Tools.Error(errorMessage);
  59542. // should the exception be thrown?
  59543. }
  59544. disposeHandler();
  59545. };
  59546. var progressHandler = onProgress ? function (event) {
  59547. try {
  59548. onProgress(event);
  59549. }
  59550. catch (e) {
  59551. errorHandler("Error in onProgress callback", e);
  59552. }
  59553. } : undefined;
  59554. var successHandler = function (meshes, particleSystems, skeletons) {
  59555. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  59556. if (onSuccess) {
  59557. try {
  59558. onSuccess(meshes, particleSystems, skeletons);
  59559. }
  59560. catch (e) {
  59561. errorHandler("Error in onSuccess callback", e);
  59562. }
  59563. }
  59564. scene._removePendingData(loadingToken);
  59565. };
  59566. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59567. if (plugin.rewriteRootURL) {
  59568. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  59569. }
  59570. if (sceneFilename === "") {
  59571. if (sceneFilename === "") {
  59572. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59573. }
  59574. }
  59575. if (plugin.importMesh) {
  59576. var syncedPlugin = plugin;
  59577. var meshes = new Array();
  59578. var particleSystems = new Array();
  59579. var skeletons = new Array();
  59580. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  59581. return;
  59582. }
  59583. scene.loadingPluginName = plugin.name;
  59584. successHandler(meshes, particleSystems, skeletons);
  59585. }
  59586. else {
  59587. var asyncedPlugin = plugin;
  59588. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  59589. scene.loadingPluginName = plugin.name;
  59590. successHandler(result.meshes, result.particleSystems, result.skeletons);
  59591. }).catch(function (error) {
  59592. errorHandler(error.message, error);
  59593. });
  59594. }
  59595. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59596. };
  59597. /**
  59598. * Import meshes into a scene
  59599. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59600. * @param rootUrl a string that defines the root url for scene and resources
  59601. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59602. * @param scene the instance of BABYLON.Scene to append to
  59603. * @param onProgress a callback with a progress event for each file being loaded
  59604. * @param pluginExtension the extension used to determine the plugin
  59605. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  59606. */
  59607. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59608. if (onProgress === void 0) { onProgress = null; }
  59609. if (pluginExtension === void 0) { pluginExtension = null; }
  59610. return new Promise(function (resolve, reject) {
  59611. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  59612. resolve({
  59613. meshes: meshes,
  59614. particleSystems: particleSystems,
  59615. skeletons: skeletons
  59616. });
  59617. }, onProgress, function (scene, message, exception) {
  59618. reject(exception || new Error(message));
  59619. });
  59620. });
  59621. };
  59622. /**
  59623. * Load a scene
  59624. * @param rootUrl a string that defines the root url for scene and resources
  59625. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59626. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59627. * @param onSuccess a callback with the scene when import succeeds
  59628. * @param onProgress a callback with a progress event for each file being loaded
  59629. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59630. * @param pluginExtension the extension used to determine the plugin
  59631. * @returns The loaded plugin
  59632. */
  59633. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  59634. if (onSuccess === void 0) { onSuccess = null; }
  59635. if (onProgress === void 0) { onProgress = null; }
  59636. if (onError === void 0) { onError = null; }
  59637. if (pluginExtension === void 0) { pluginExtension = null; }
  59638. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  59639. };
  59640. /**
  59641. * Load a scene
  59642. * @param rootUrl a string that defines the root url for scene and resources
  59643. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59644. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59645. * @param onProgress a callback with a progress event for each file being loaded
  59646. * @param pluginExtension the extension used to determine the plugin
  59647. * @returns The loaded scene
  59648. */
  59649. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  59650. if (onProgress === void 0) { onProgress = null; }
  59651. if (pluginExtension === void 0) { pluginExtension = null; }
  59652. return new Promise(function (resolve, reject) {
  59653. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  59654. resolve(scene);
  59655. }, onProgress, function (scene, message, exception) {
  59656. reject(exception || new Error(message));
  59657. }, pluginExtension);
  59658. });
  59659. };
  59660. /**
  59661. * Append a scene
  59662. * @param rootUrl a string that defines the root url for scene and resources
  59663. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59664. * @param scene is the instance of BABYLON.Scene to append to
  59665. * @param onSuccess a callback with the scene when import succeeds
  59666. * @param onProgress a callback with a progress event for each file being loaded
  59667. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59668. * @param pluginExtension the extension used to determine the plugin
  59669. * @returns The loaded plugin
  59670. */
  59671. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59672. if (onSuccess === void 0) { onSuccess = null; }
  59673. if (onProgress === void 0) { onProgress = null; }
  59674. if (onError === void 0) { onError = null; }
  59675. if (pluginExtension === void 0) { pluginExtension = null; }
  59676. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59677. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59678. return null;
  59679. }
  59680. if (SceneLoader.ShowLoadingScreen) {
  59681. scene.getEngine().displayLoadingUI();
  59682. }
  59683. var loadingToken = {};
  59684. scene._addPendingData(loadingToken);
  59685. var disposeHandler = function () {
  59686. scene._removePendingData(loadingToken);
  59687. scene.getEngine().hideLoadingUI();
  59688. };
  59689. var errorHandler = function (message, exception) {
  59690. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59691. if (onError) {
  59692. onError(scene, errorMessage, exception);
  59693. }
  59694. else {
  59695. BABYLON.Tools.Error(errorMessage);
  59696. // should the exception be thrown?
  59697. }
  59698. disposeHandler();
  59699. };
  59700. var progressHandler = onProgress ? function (event) {
  59701. try {
  59702. onProgress(event);
  59703. }
  59704. catch (e) {
  59705. errorHandler("Error in onProgress callback", e);
  59706. }
  59707. } : undefined;
  59708. var successHandler = function () {
  59709. if (onSuccess) {
  59710. try {
  59711. onSuccess(scene);
  59712. }
  59713. catch (e) {
  59714. errorHandler("Error in onSuccess callback", e);
  59715. }
  59716. }
  59717. scene._removePendingData(loadingToken);
  59718. };
  59719. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59720. if (sceneFilename === "") {
  59721. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59722. }
  59723. if (plugin.load) {
  59724. var syncedPlugin = plugin;
  59725. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  59726. return;
  59727. }
  59728. scene.loadingPluginName = plugin.name;
  59729. successHandler();
  59730. }
  59731. else {
  59732. var asyncedPlugin = plugin;
  59733. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  59734. scene.loadingPluginName = plugin.name;
  59735. successHandler();
  59736. }).catch(function (error) {
  59737. errorHandler(error.message, error);
  59738. });
  59739. }
  59740. if (SceneLoader.ShowLoadingScreen) {
  59741. scene.executeWhenReady(function () {
  59742. scene.getEngine().hideLoadingUI();
  59743. });
  59744. }
  59745. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59746. };
  59747. /**
  59748. * Append a scene
  59749. * @param rootUrl a string that defines the root url for scene and resources
  59750. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59751. * @param scene is the instance of BABYLON.Scene to append to
  59752. * @param onProgress a callback with a progress event for each file being loaded
  59753. * @param pluginExtension the extension used to determine the plugin
  59754. * @returns The given scene
  59755. */
  59756. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59757. if (onProgress === void 0) { onProgress = null; }
  59758. if (pluginExtension === void 0) { pluginExtension = null; }
  59759. return new Promise(function (resolve, reject) {
  59760. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  59761. resolve(scene);
  59762. }, onProgress, function (scene, message, exception) {
  59763. reject(exception || new Error(message));
  59764. }, pluginExtension);
  59765. });
  59766. };
  59767. /**
  59768. * Load a scene into an asset container
  59769. * @param rootUrl a string that defines the root url for scene and resources
  59770. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59771. * @param scene is the instance of BABYLON.Scene to append to
  59772. * @param onSuccess a callback with the scene when import succeeds
  59773. * @param onProgress a callback with a progress event for each file being loaded
  59774. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59775. * @param pluginExtension the extension used to determine the plugin
  59776. * @returns The loaded plugin
  59777. */
  59778. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59779. if (onSuccess === void 0) { onSuccess = null; }
  59780. if (onProgress === void 0) { onProgress = null; }
  59781. if (onError === void 0) { onError = null; }
  59782. if (pluginExtension === void 0) { pluginExtension = null; }
  59783. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59784. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59785. return null;
  59786. }
  59787. var loadingToken = {};
  59788. scene._addPendingData(loadingToken);
  59789. var disposeHandler = function () {
  59790. scene._removePendingData(loadingToken);
  59791. };
  59792. var errorHandler = function (message, exception) {
  59793. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59794. if (onError) {
  59795. onError(scene, errorMessage, exception);
  59796. }
  59797. else {
  59798. BABYLON.Tools.Error(errorMessage);
  59799. // should the exception be thrown?
  59800. }
  59801. disposeHandler();
  59802. };
  59803. var progressHandler = onProgress ? function (event) {
  59804. try {
  59805. onProgress(event);
  59806. }
  59807. catch (e) {
  59808. errorHandler("Error in onProgress callback", e);
  59809. }
  59810. } : undefined;
  59811. var successHandler = function (assets) {
  59812. if (onSuccess) {
  59813. try {
  59814. onSuccess(assets);
  59815. }
  59816. catch (e) {
  59817. errorHandler("Error in onSuccess callback", e);
  59818. }
  59819. }
  59820. scene._removePendingData(loadingToken);
  59821. };
  59822. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59823. if (plugin.loadAssetContainer) {
  59824. var syncedPlugin = plugin;
  59825. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  59826. if (!assetContainer) {
  59827. return;
  59828. }
  59829. scene.loadingPluginName = plugin.name;
  59830. successHandler(assetContainer);
  59831. }
  59832. else if (plugin.loadAssetContainerAsync) {
  59833. var asyncedPlugin = plugin;
  59834. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  59835. scene.loadingPluginName = plugin.name;
  59836. successHandler(assetContainer);
  59837. }).catch(function (error) {
  59838. errorHandler(error.message, error);
  59839. });
  59840. }
  59841. else {
  59842. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  59843. }
  59844. if (SceneLoader.ShowLoadingScreen) {
  59845. scene.executeWhenReady(function () {
  59846. scene.getEngine().hideLoadingUI();
  59847. });
  59848. }
  59849. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59850. };
  59851. /**
  59852. * Load a scene into an asset container
  59853. * @param rootUrl a string that defines the root url for scene and resources
  59854. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59855. * @param scene is the instance of BABYLON.Scene to append to
  59856. * @param onProgress a callback with a progress event for each file being loaded
  59857. * @param pluginExtension the extension used to determine the plugin
  59858. * @returns The loaded asset container
  59859. */
  59860. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59861. if (onProgress === void 0) { onProgress = null; }
  59862. if (pluginExtension === void 0) { pluginExtension = null; }
  59863. return new Promise(function (resolve, reject) {
  59864. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  59865. resolve(assetContainer);
  59866. }, onProgress, function (scene, message, exception) {
  59867. reject(exception || new Error(message));
  59868. }, pluginExtension);
  59869. });
  59870. };
  59871. // Flags
  59872. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  59873. SceneLoader._ShowLoadingScreen = true;
  59874. SceneLoader._CleanBoneMatrixWeights = false;
  59875. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  59876. // Members
  59877. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  59878. SceneLoader._registeredPlugins = {};
  59879. return SceneLoader;
  59880. }());
  59881. BABYLON.SceneLoader = SceneLoader;
  59882. ;
  59883. })(BABYLON || (BABYLON = {}));
  59884. //# sourceMappingURL=babylon.sceneLoader.js.map
  59885. var BABYLON;
  59886. (function (BABYLON) {
  59887. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  59888. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59889. var parsedMaterial = parsedData.materials[index];
  59890. if (parsedMaterial.id === id) {
  59891. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59892. }
  59893. }
  59894. return null;
  59895. };
  59896. var isDescendantOf = function (mesh, names, hierarchyIds) {
  59897. for (var i in names) {
  59898. if (mesh.name === names[i]) {
  59899. hierarchyIds.push(mesh.id);
  59900. return true;
  59901. }
  59902. }
  59903. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  59904. hierarchyIds.push(mesh.id);
  59905. return true;
  59906. }
  59907. return false;
  59908. };
  59909. var logOperation = function (operation, producer) {
  59910. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  59911. };
  59912. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  59913. if (addToScene === void 0) { addToScene = false; }
  59914. var container = new BABYLON.AssetContainer(scene);
  59915. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  59916. // when SceneLoader.debugLogging = true (default), or exception encountered.
  59917. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  59918. // and avoid problems with multiple concurrent .babylon loads.
  59919. var log = "importScene has failed JSON parse";
  59920. try {
  59921. var parsedData = JSON.parse(data);
  59922. log = "";
  59923. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  59924. var index;
  59925. var cache;
  59926. // Lights
  59927. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  59928. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  59929. var parsedLight = parsedData.lights[index];
  59930. var light = BABYLON.Light.Parse(parsedLight, scene);
  59931. if (light) {
  59932. container.lights.push(light);
  59933. log += (index === 0 ? "\n\tLights:" : "");
  59934. log += "\n\t\t" + light.toString(fullDetails);
  59935. }
  59936. }
  59937. }
  59938. // Animations
  59939. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  59940. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  59941. var parsedAnimation = parsedData.animations[index];
  59942. var animation = BABYLON.Animation.Parse(parsedAnimation);
  59943. scene.animations.push(animation);
  59944. container.animations.push(animation);
  59945. log += (index === 0 ? "\n\tAnimations:" : "");
  59946. log += "\n\t\t" + animation.toString(fullDetails);
  59947. }
  59948. }
  59949. // Materials
  59950. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  59951. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59952. var parsedMaterial = parsedData.materials[index];
  59953. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59954. container.materials.push(mat);
  59955. log += (index === 0 ? "\n\tMaterials:" : "");
  59956. log += "\n\t\t" + mat.toString(fullDetails);
  59957. }
  59958. }
  59959. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  59960. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  59961. var parsedMultiMaterial = parsedData.multiMaterials[index];
  59962. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  59963. container.multiMaterials.push(mmat);
  59964. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  59965. log += "\n\t\t" + mmat.toString(fullDetails);
  59966. }
  59967. }
  59968. // Morph targets
  59969. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  59970. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  59971. var managerData = _a[_i];
  59972. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  59973. }
  59974. }
  59975. // Skeletons
  59976. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  59977. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  59978. var parsedSkeleton = parsedData.skeletons[index];
  59979. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  59980. container.skeletons.push(skeleton);
  59981. log += (index === 0 ? "\n\tSkeletons:" : "");
  59982. log += "\n\t\t" + skeleton.toString(fullDetails);
  59983. }
  59984. }
  59985. // Geometries
  59986. var geometries = parsedData.geometries;
  59987. if (geometries !== undefined && geometries !== null) {
  59988. var addedGeometry = new Array();
  59989. // Boxes
  59990. var boxes = geometries.boxes;
  59991. if (boxes !== undefined && boxes !== null) {
  59992. for (index = 0, cache = boxes.length; index < cache; index++) {
  59993. var parsedBox = boxes[index];
  59994. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  59995. }
  59996. }
  59997. // Spheres
  59998. var spheres = geometries.spheres;
  59999. if (spheres !== undefined && spheres !== null) {
  60000. for (index = 0, cache = spheres.length; index < cache; index++) {
  60001. var parsedSphere = spheres[index];
  60002. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  60003. }
  60004. }
  60005. // Cylinders
  60006. var cylinders = geometries.cylinders;
  60007. if (cylinders !== undefined && cylinders !== null) {
  60008. for (index = 0, cache = cylinders.length; index < cache; index++) {
  60009. var parsedCylinder = cylinders[index];
  60010. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  60011. }
  60012. }
  60013. // Toruses
  60014. var toruses = geometries.toruses;
  60015. if (toruses !== undefined && toruses !== null) {
  60016. for (index = 0, cache = toruses.length; index < cache; index++) {
  60017. var parsedTorus = toruses[index];
  60018. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  60019. }
  60020. }
  60021. // Grounds
  60022. var grounds = geometries.grounds;
  60023. if (grounds !== undefined && grounds !== null) {
  60024. for (index = 0, cache = grounds.length; index < cache; index++) {
  60025. var parsedGround = grounds[index];
  60026. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  60027. }
  60028. }
  60029. // Planes
  60030. var planes = geometries.planes;
  60031. if (planes !== undefined && planes !== null) {
  60032. for (index = 0, cache = planes.length; index < cache; index++) {
  60033. var parsedPlane = planes[index];
  60034. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  60035. }
  60036. }
  60037. // TorusKnots
  60038. var torusKnots = geometries.torusKnots;
  60039. if (torusKnots !== undefined && torusKnots !== null) {
  60040. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  60041. var parsedTorusKnot = torusKnots[index];
  60042. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  60043. }
  60044. }
  60045. // VertexData
  60046. var vertexData = geometries.vertexData;
  60047. if (vertexData !== undefined && vertexData !== null) {
  60048. for (index = 0, cache = vertexData.length; index < cache; index++) {
  60049. var parsedVertexData = vertexData[index];
  60050. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  60051. }
  60052. }
  60053. addedGeometry.forEach(function (g) {
  60054. if (g) {
  60055. container.geometries.push(g);
  60056. }
  60057. });
  60058. }
  60059. // Transform nodes
  60060. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  60061. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  60062. var parsedTransformNode = parsedData.transformNodes[index];
  60063. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  60064. container.transformNodes.push(node);
  60065. }
  60066. }
  60067. // Meshes
  60068. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60069. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60070. var parsedMesh = parsedData.meshes[index];
  60071. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60072. container.meshes.push(mesh);
  60073. log += (index === 0 ? "\n\tMeshes:" : "");
  60074. log += "\n\t\t" + mesh.toString(fullDetails);
  60075. }
  60076. }
  60077. // Cameras
  60078. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  60079. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  60080. var parsedCamera = parsedData.cameras[index];
  60081. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  60082. container.cameras.push(camera);
  60083. log += (index === 0 ? "\n\tCameras:" : "");
  60084. log += "\n\t\t" + camera.toString(fullDetails);
  60085. }
  60086. }
  60087. // Browsing all the graph to connect the dots
  60088. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  60089. var camera = scene.cameras[index];
  60090. if (camera._waitingParentId) {
  60091. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  60092. camera._waitingParentId = null;
  60093. }
  60094. }
  60095. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60096. var light_1 = scene.lights[index];
  60097. if (light_1 && light_1._waitingParentId) {
  60098. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  60099. light_1._waitingParentId = null;
  60100. }
  60101. }
  60102. // Sounds
  60103. // TODO: add sound
  60104. var loadedSounds = [];
  60105. var loadedSound;
  60106. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  60107. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  60108. var parsedSound = parsedData.sounds[index];
  60109. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60110. if (!parsedSound.url)
  60111. parsedSound.url = parsedSound.name;
  60112. if (!loadedSounds[parsedSound.url]) {
  60113. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  60114. loadedSounds[parsedSound.url] = loadedSound;
  60115. container.sounds.push(loadedSound);
  60116. }
  60117. else {
  60118. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  60119. }
  60120. }
  60121. else {
  60122. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  60123. }
  60124. }
  60125. }
  60126. loadedSounds = [];
  60127. // Connect parents & children and parse actions
  60128. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  60129. var transformNode = scene.transformNodes[index];
  60130. if (transformNode._waitingParentId) {
  60131. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  60132. transformNode._waitingParentId = null;
  60133. }
  60134. }
  60135. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60136. var mesh = scene.meshes[index];
  60137. if (mesh._waitingParentId) {
  60138. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  60139. mesh._waitingParentId = null;
  60140. }
  60141. if (mesh._waitingActions) {
  60142. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  60143. mesh._waitingActions = null;
  60144. }
  60145. }
  60146. // freeze world matrix application
  60147. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60148. var currentMesh = scene.meshes[index];
  60149. if (currentMesh._waitingFreezeWorldMatrix) {
  60150. currentMesh.freezeWorldMatrix();
  60151. currentMesh._waitingFreezeWorldMatrix = null;
  60152. }
  60153. else {
  60154. currentMesh.computeWorldMatrix(true);
  60155. }
  60156. }
  60157. // Particles Systems
  60158. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60159. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60160. var parsedParticleSystem = parsedData.particleSystems[index];
  60161. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60162. container.particleSystems.push(ps);
  60163. }
  60164. }
  60165. // Lens flares
  60166. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  60167. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  60168. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  60169. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  60170. container.lensFlareSystems.push(lf);
  60171. }
  60172. }
  60173. // Shadows
  60174. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  60175. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  60176. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  60177. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  60178. container.shadowGenerators.push(sg);
  60179. }
  60180. }
  60181. // Lights exclusions / inclusions
  60182. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60183. var light_2 = scene.lights[index];
  60184. // Excluded check
  60185. if (light_2._excludedMeshesIds.length > 0) {
  60186. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  60187. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  60188. if (excludedMesh) {
  60189. light_2.excludedMeshes.push(excludedMesh);
  60190. }
  60191. }
  60192. light_2._excludedMeshesIds = [];
  60193. }
  60194. // Included check
  60195. if (light_2._includedOnlyMeshesIds.length > 0) {
  60196. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  60197. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  60198. if (includedOnlyMesh) {
  60199. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  60200. }
  60201. }
  60202. light_2._includedOnlyMeshesIds = [];
  60203. }
  60204. }
  60205. // Actions (scene)
  60206. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  60207. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  60208. }
  60209. if (!addToScene) {
  60210. container.removeAllFromScene();
  60211. }
  60212. }
  60213. catch (err) {
  60214. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  60215. if (onError) {
  60216. onError(msg, err);
  60217. }
  60218. else {
  60219. BABYLON.Tools.Log(msg);
  60220. throw err;
  60221. }
  60222. }
  60223. finally {
  60224. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60225. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60226. }
  60227. }
  60228. return container;
  60229. };
  60230. BABYLON.SceneLoader.RegisterPlugin({
  60231. name: "babylon.js",
  60232. extensions: ".babylon",
  60233. canDirectLoad: function (data) {
  60234. if (data.indexOf("babylon") !== -1) {
  60235. return true;
  60236. }
  60237. return false;
  60238. },
  60239. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  60240. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60241. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60242. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60243. // and avoid problems with multiple concurrent .babylon loads.
  60244. var log = "importMesh has failed JSON parse";
  60245. try {
  60246. var parsedData = JSON.parse(data);
  60247. log = "";
  60248. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60249. if (!meshesNames) {
  60250. meshesNames = null;
  60251. }
  60252. else if (!Array.isArray(meshesNames)) {
  60253. meshesNames = [meshesNames];
  60254. }
  60255. var hierarchyIds = new Array();
  60256. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60257. var loadedSkeletonsIds = [];
  60258. var loadedMaterialsIds = [];
  60259. var index;
  60260. var cache;
  60261. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60262. var parsedMesh = parsedData.meshes[index];
  60263. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  60264. if (meshesNames !== null) {
  60265. // Remove found mesh name from list.
  60266. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  60267. }
  60268. //Geometry?
  60269. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  60270. //does the file contain geometries?
  60271. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  60272. //find the correct geometry and add it to the scene
  60273. var found = false;
  60274. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  60275. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  60276. return;
  60277. }
  60278. else {
  60279. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  60280. if (parsedGeometryData.id === parsedMesh.geometryId) {
  60281. switch (geometryType) {
  60282. case "boxes":
  60283. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  60284. break;
  60285. case "spheres":
  60286. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  60287. break;
  60288. case "cylinders":
  60289. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  60290. break;
  60291. case "toruses":
  60292. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  60293. break;
  60294. case "grounds":
  60295. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  60296. break;
  60297. case "planes":
  60298. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  60299. break;
  60300. case "torusKnots":
  60301. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  60302. break;
  60303. case "vertexData":
  60304. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  60305. break;
  60306. }
  60307. found = true;
  60308. }
  60309. });
  60310. }
  60311. });
  60312. if (found === false) {
  60313. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  60314. }
  60315. }
  60316. }
  60317. // Material ?
  60318. if (parsedMesh.materialId) {
  60319. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  60320. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60321. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  60322. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  60323. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  60324. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  60325. var subMatId = parsedMultiMaterial.materials[matIndex];
  60326. loadedMaterialsIds.push(subMatId);
  60327. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  60328. if (mat) {
  60329. log += "\n\tMaterial " + mat.toString(fullDetails);
  60330. }
  60331. }
  60332. loadedMaterialsIds.push(parsedMultiMaterial.id);
  60333. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60334. if (mmat) {
  60335. materialFound = true;
  60336. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  60337. }
  60338. break;
  60339. }
  60340. }
  60341. }
  60342. if (materialFound === false) {
  60343. loadedMaterialsIds.push(parsedMesh.materialId);
  60344. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  60345. if (!mat) {
  60346. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  60347. }
  60348. else {
  60349. log += "\n\tMaterial " + mat.toString(fullDetails);
  60350. }
  60351. }
  60352. }
  60353. // Skeleton ?
  60354. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60355. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  60356. if (skeletonAlreadyLoaded === false) {
  60357. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  60358. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  60359. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  60360. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60361. skeletons.push(skeleton);
  60362. loadedSkeletonsIds.push(parsedSkeleton.id);
  60363. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  60364. }
  60365. }
  60366. }
  60367. }
  60368. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60369. meshes.push(mesh);
  60370. log += "\n\tMesh " + mesh.toString(fullDetails);
  60371. }
  60372. }
  60373. // Connecting parents
  60374. var currentMesh;
  60375. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60376. currentMesh = scene.meshes[index];
  60377. if (currentMesh._waitingParentId) {
  60378. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  60379. currentMesh._waitingParentId = null;
  60380. }
  60381. }
  60382. // freeze and compute world matrix application
  60383. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60384. currentMesh = scene.meshes[index];
  60385. if (currentMesh._waitingFreezeWorldMatrix) {
  60386. currentMesh.freezeWorldMatrix();
  60387. currentMesh._waitingFreezeWorldMatrix = null;
  60388. }
  60389. else {
  60390. currentMesh.computeWorldMatrix(true);
  60391. }
  60392. }
  60393. }
  60394. // Particles
  60395. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60396. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60397. var parsedParticleSystem = parsedData.particleSystems[index];
  60398. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  60399. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  60400. }
  60401. }
  60402. }
  60403. return true;
  60404. }
  60405. catch (err) {
  60406. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  60407. if (onError) {
  60408. onError(msg, err);
  60409. }
  60410. else {
  60411. BABYLON.Tools.Log(msg);
  60412. throw err;
  60413. }
  60414. }
  60415. finally {
  60416. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60417. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60418. }
  60419. }
  60420. return false;
  60421. },
  60422. load: function (scene, data, rootUrl, onError) {
  60423. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60424. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60425. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60426. // and avoid problems with multiple concurrent .babylon loads.
  60427. var log = "importScene has failed JSON parse";
  60428. try {
  60429. var parsedData = JSON.parse(data);
  60430. log = "";
  60431. // Scene
  60432. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  60433. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  60434. }
  60435. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  60436. scene.autoClear = parsedData.autoClear;
  60437. }
  60438. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  60439. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  60440. }
  60441. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  60442. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  60443. }
  60444. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  60445. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  60446. }
  60447. // Fog
  60448. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  60449. scene.fogMode = parsedData.fogMode;
  60450. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  60451. scene.fogStart = parsedData.fogStart;
  60452. scene.fogEnd = parsedData.fogEnd;
  60453. scene.fogDensity = parsedData.fogDensity;
  60454. log += "\tFog mode for scene: ";
  60455. switch (scene.fogMode) {
  60456. // getters not compiling, so using hardcoded
  60457. case 1:
  60458. log += "exp\n";
  60459. break;
  60460. case 2:
  60461. log += "exp2\n";
  60462. break;
  60463. case 3:
  60464. log += "linear\n";
  60465. break;
  60466. }
  60467. }
  60468. //Physics
  60469. if (parsedData.physicsEnabled) {
  60470. var physicsPlugin;
  60471. if (parsedData.physicsEngine === "cannon") {
  60472. physicsPlugin = new BABYLON.CannonJSPlugin();
  60473. }
  60474. else if (parsedData.physicsEngine === "oimo") {
  60475. physicsPlugin = new BABYLON.OimoJSPlugin();
  60476. }
  60477. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  60478. //else - default engine, which is currently oimo
  60479. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  60480. scene.enablePhysics(physicsGravity, physicsPlugin);
  60481. }
  60482. // Metadata
  60483. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  60484. scene.metadata = parsedData.metadata;
  60485. }
  60486. //collisions, if defined. otherwise, default is true
  60487. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  60488. scene.collisionsEnabled = parsedData.collisionsEnabled;
  60489. }
  60490. scene.workerCollisions = !!parsedData.workerCollisions;
  60491. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  60492. if (!container) {
  60493. return false;
  60494. }
  60495. if (parsedData.autoAnimate) {
  60496. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  60497. }
  60498. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  60499. scene.setActiveCameraByID(parsedData.activeCameraID);
  60500. }
  60501. // Environment texture
  60502. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  60503. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  60504. if (parsedData.createDefaultSkybox === true) {
  60505. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  60506. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  60507. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  60508. }
  60509. }
  60510. // Finish
  60511. return true;
  60512. }
  60513. catch (err) {
  60514. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  60515. if (onError) {
  60516. onError(msg, err);
  60517. }
  60518. else {
  60519. BABYLON.Tools.Log(msg);
  60520. throw err;
  60521. }
  60522. }
  60523. finally {
  60524. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60525. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60526. }
  60527. }
  60528. return false;
  60529. },
  60530. loadAssetContainer: function (scene, data, rootUrl, onError) {
  60531. var container = loadAssetContainer(scene, data, rootUrl, onError);
  60532. return container;
  60533. }
  60534. });
  60535. })(BABYLON || (BABYLON = {}));
  60536. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  60537. var BABYLON;
  60538. (function (BABYLON) {
  60539. var FilesInput = /** @class */ (function () {
  60540. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  60541. this.onProcessFileCallback = function () { return true; };
  60542. this._engine = engine;
  60543. this._currentScene = scene;
  60544. this._sceneLoadedCallback = sceneLoadedCallback;
  60545. this._progressCallback = progressCallback;
  60546. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  60547. this._textureLoadingCallback = textureLoadingCallback;
  60548. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  60549. this._onReloadCallback = onReloadCallback;
  60550. this._errorCallback = errorCallback;
  60551. }
  60552. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  60553. var _this = this;
  60554. if (elementToMonitor) {
  60555. this._elementToMonitor = elementToMonitor;
  60556. this._dragEnterHandler = function (e) { _this.drag(e); };
  60557. this._dragOverHandler = function (e) { _this.drag(e); };
  60558. this._dropHandler = function (e) { _this.drop(e); };
  60559. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  60560. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  60561. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  60562. }
  60563. };
  60564. FilesInput.prototype.dispose = function () {
  60565. if (!this._elementToMonitor) {
  60566. return;
  60567. }
  60568. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  60569. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  60570. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  60571. };
  60572. FilesInput.prototype.renderFunction = function () {
  60573. if (this._additionalRenderLoopLogicCallback) {
  60574. this._additionalRenderLoopLogicCallback();
  60575. }
  60576. if (this._currentScene) {
  60577. if (this._textureLoadingCallback) {
  60578. var remaining = this._currentScene.getWaitingItemsCount();
  60579. if (remaining > 0) {
  60580. this._textureLoadingCallback(remaining);
  60581. }
  60582. }
  60583. this._currentScene.render();
  60584. }
  60585. };
  60586. FilesInput.prototype.drag = function (e) {
  60587. e.stopPropagation();
  60588. e.preventDefault();
  60589. };
  60590. FilesInput.prototype.drop = function (eventDrop) {
  60591. eventDrop.stopPropagation();
  60592. eventDrop.preventDefault();
  60593. this.loadFiles(eventDrop);
  60594. };
  60595. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  60596. var _this = this;
  60597. var reader = folder.createReader();
  60598. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  60599. reader.readEntries(function (entries) {
  60600. remaining.count += entries.length;
  60601. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  60602. var entry = entries_1[_i];
  60603. if (entry.isFile) {
  60604. entry.file(function (file) {
  60605. file.correctName = relativePath + file.name;
  60606. files.push(file);
  60607. if (--remaining.count === 0) {
  60608. callback();
  60609. }
  60610. });
  60611. }
  60612. else if (entry.isDirectory) {
  60613. _this._traverseFolder(entry, files, remaining, callback);
  60614. }
  60615. }
  60616. if (--remaining.count) {
  60617. callback();
  60618. }
  60619. });
  60620. };
  60621. FilesInput.prototype._processFiles = function (files) {
  60622. for (var i = 0; i < files.length; i++) {
  60623. var name = files[i].correctName.toLowerCase();
  60624. var extension = name.split('.').pop();
  60625. if (!this.onProcessFileCallback(files[i], name, extension)) {
  60626. continue;
  60627. }
  60628. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  60629. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  60630. this._sceneFileToLoad = files[i];
  60631. }
  60632. else {
  60633. FilesInput.FilesToLoad[name] = files[i];
  60634. }
  60635. }
  60636. };
  60637. FilesInput.prototype.loadFiles = function (event) {
  60638. var _this = this;
  60639. if (this._startingProcessingFilesCallback)
  60640. this._startingProcessingFilesCallback();
  60641. // Handling data transfer via drag'n'drop
  60642. if (event && event.dataTransfer && event.dataTransfer.files) {
  60643. this._filesToLoad = event.dataTransfer.files;
  60644. }
  60645. // Handling files from input files
  60646. if (event && event.target && event.target.files) {
  60647. this._filesToLoad = event.target.files;
  60648. }
  60649. if (this._filesToLoad && this._filesToLoad.length > 0) {
  60650. var files_1 = new Array();
  60651. var folders = [];
  60652. var items = event.dataTransfer ? event.dataTransfer.items : null;
  60653. for (var i = 0; i < this._filesToLoad.length; i++) {
  60654. var fileToLoad = this._filesToLoad[i];
  60655. var name_1 = fileToLoad.name.toLowerCase();
  60656. var entry = void 0;
  60657. fileToLoad.correctName = name_1;
  60658. if (items) {
  60659. var item = items[i];
  60660. if (item.getAsEntry) {
  60661. entry = item.getAsEntry();
  60662. }
  60663. else if (item.webkitGetAsEntry) {
  60664. entry = item.webkitGetAsEntry();
  60665. }
  60666. }
  60667. if (!entry) {
  60668. files_1.push(fileToLoad);
  60669. }
  60670. else {
  60671. if (entry.isDirectory) {
  60672. folders.push(entry);
  60673. }
  60674. else {
  60675. files_1.push(fileToLoad);
  60676. }
  60677. }
  60678. }
  60679. if (folders.length === 0) {
  60680. this._processFiles(files_1);
  60681. this._processReload();
  60682. }
  60683. else {
  60684. var remaining = { count: folders.length };
  60685. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  60686. var folder = folders_1[_i];
  60687. this._traverseFolder(folder, files_1, remaining, function () {
  60688. _this._processFiles(files_1);
  60689. if (remaining.count === 0) {
  60690. _this._processReload();
  60691. }
  60692. });
  60693. }
  60694. }
  60695. }
  60696. };
  60697. FilesInput.prototype._processReload = function () {
  60698. if (this._onReloadCallback) {
  60699. this._onReloadCallback(this._sceneFileToLoad);
  60700. }
  60701. else {
  60702. this.reload();
  60703. }
  60704. };
  60705. FilesInput.prototype.reload = function () {
  60706. var _this = this;
  60707. // If a scene file has been provided
  60708. if (this._sceneFileToLoad) {
  60709. if (this._currentScene) {
  60710. if (BABYLON.Tools.errorsCount > 0) {
  60711. BABYLON.Tools.ClearLogCache();
  60712. }
  60713. this._engine.stopRenderLoop();
  60714. this._currentScene.dispose();
  60715. }
  60716. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  60717. if (_this._progressCallback) {
  60718. _this._progressCallback(progress);
  60719. }
  60720. }).then(function (scene) {
  60721. _this._currentScene = scene;
  60722. if (_this._sceneLoadedCallback) {
  60723. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  60724. }
  60725. // Wait for textures and shaders to be ready
  60726. _this._currentScene.executeWhenReady(function () {
  60727. _this._engine.runRenderLoop(function () {
  60728. _this.renderFunction();
  60729. });
  60730. });
  60731. }).catch(function (error) {
  60732. if (_this._errorCallback) {
  60733. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  60734. }
  60735. });
  60736. }
  60737. else {
  60738. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  60739. }
  60740. };
  60741. FilesInput.FilesToLoad = {};
  60742. return FilesInput;
  60743. }());
  60744. BABYLON.FilesInput = FilesInput;
  60745. })(BABYLON || (BABYLON = {}));
  60746. //# sourceMappingURL=babylon.filesInput.js.map
  60747. var BABYLON;
  60748. (function (BABYLON) {
  60749. /**
  60750. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60751. * The underlying implementation relies on an associative array to ensure the best performances.
  60752. * The value can be anything including 'null' but except 'undefined'
  60753. */
  60754. var StringDictionary = /** @class */ (function () {
  60755. function StringDictionary() {
  60756. this._count = 0;
  60757. this._data = {};
  60758. }
  60759. /**
  60760. * This will clear this dictionary and copy the content from the 'source' one.
  60761. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60762. * @param source the dictionary to take the content from and copy to this dictionary
  60763. */
  60764. StringDictionary.prototype.copyFrom = function (source) {
  60765. var _this = this;
  60766. this.clear();
  60767. source.forEach(function (t, v) { return _this.add(t, v); });
  60768. };
  60769. /**
  60770. * Get a value based from its key
  60771. * @param key the given key to get the matching value from
  60772. * @return the value if found, otherwise undefined is returned
  60773. */
  60774. StringDictionary.prototype.get = function (key) {
  60775. var val = this._data[key];
  60776. if (val !== undefined) {
  60777. return val;
  60778. }
  60779. return undefined;
  60780. };
  60781. /**
  60782. * Get a value from its key or add it if it doesn't exist.
  60783. * This method will ensure you that a given key/data will be present in the dictionary.
  60784. * @param key the given key to get the matching value from
  60785. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60786. * The factory will only be invoked if there's no data for the given key.
  60787. * @return the value corresponding to the key.
  60788. */
  60789. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60790. var val = this.get(key);
  60791. if (val !== undefined) {
  60792. return val;
  60793. }
  60794. val = factory(key);
  60795. if (val) {
  60796. this.add(key, val);
  60797. }
  60798. return val;
  60799. };
  60800. /**
  60801. * Get a value from its key if present in the dictionary otherwise add it
  60802. * @param key the key to get the value from
  60803. * @param val if there's no such key/value pair in the dictionary add it with this value
  60804. * @return the value corresponding to the key
  60805. */
  60806. StringDictionary.prototype.getOrAdd = function (key, val) {
  60807. var curVal = this.get(key);
  60808. if (curVal !== undefined) {
  60809. return curVal;
  60810. }
  60811. this.add(key, val);
  60812. return val;
  60813. };
  60814. /**
  60815. * Check if there's a given key in the dictionary
  60816. * @param key the key to check for
  60817. * @return true if the key is present, false otherwise
  60818. */
  60819. StringDictionary.prototype.contains = function (key) {
  60820. return this._data[key] !== undefined;
  60821. };
  60822. /**
  60823. * Add a new key and its corresponding value
  60824. * @param key the key to add
  60825. * @param value the value corresponding to the key
  60826. * @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
  60827. */
  60828. StringDictionary.prototype.add = function (key, value) {
  60829. if (this._data[key] !== undefined) {
  60830. return false;
  60831. }
  60832. this._data[key] = value;
  60833. ++this._count;
  60834. return true;
  60835. };
  60836. StringDictionary.prototype.set = function (key, value) {
  60837. if (this._data[key] === undefined) {
  60838. return false;
  60839. }
  60840. this._data[key] = value;
  60841. return true;
  60842. };
  60843. /**
  60844. * Get the element of the given key and remove it from the dictionary
  60845. * @param key
  60846. */
  60847. StringDictionary.prototype.getAndRemove = function (key) {
  60848. var val = this.get(key);
  60849. if (val !== undefined) {
  60850. delete this._data[key];
  60851. --this._count;
  60852. return val;
  60853. }
  60854. return null;
  60855. };
  60856. /**
  60857. * Remove a key/value from the dictionary.
  60858. * @param key the key to remove
  60859. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60860. */
  60861. StringDictionary.prototype.remove = function (key) {
  60862. if (this.contains(key)) {
  60863. delete this._data[key];
  60864. --this._count;
  60865. return true;
  60866. }
  60867. return false;
  60868. };
  60869. /**
  60870. * Clear the whole content of the dictionary
  60871. */
  60872. StringDictionary.prototype.clear = function () {
  60873. this._data = {};
  60874. this._count = 0;
  60875. };
  60876. Object.defineProperty(StringDictionary.prototype, "count", {
  60877. get: function () {
  60878. return this._count;
  60879. },
  60880. enumerable: true,
  60881. configurable: true
  60882. });
  60883. /**
  60884. * Execute a callback on each key/val of the dictionary.
  60885. * Note that you can remove any element in this dictionary in the callback implementation
  60886. * @param callback the callback to execute on a given key/value pair
  60887. */
  60888. StringDictionary.prototype.forEach = function (callback) {
  60889. for (var cur in this._data) {
  60890. var val = this._data[cur];
  60891. callback(cur, val);
  60892. }
  60893. };
  60894. /**
  60895. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60896. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60897. * Note that you can remove any element in this dictionary in the callback implementation
  60898. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60899. */
  60900. StringDictionary.prototype.first = function (callback) {
  60901. for (var cur in this._data) {
  60902. var val = this._data[cur];
  60903. var res = callback(cur, val);
  60904. if (res) {
  60905. return res;
  60906. }
  60907. }
  60908. return null;
  60909. };
  60910. return StringDictionary;
  60911. }());
  60912. BABYLON.StringDictionary = StringDictionary;
  60913. })(BABYLON || (BABYLON = {}));
  60914. //# sourceMappingURL=babylon.stringDictionary.js.map
  60915. var BABYLON;
  60916. (function (BABYLON) {
  60917. var Tags = /** @class */ (function () {
  60918. function Tags() {
  60919. }
  60920. Tags.EnableFor = function (obj) {
  60921. obj._tags = obj._tags || {};
  60922. obj.hasTags = function () {
  60923. return Tags.HasTags(obj);
  60924. };
  60925. obj.addTags = function (tagsString) {
  60926. return Tags.AddTagsTo(obj, tagsString);
  60927. };
  60928. obj.removeTags = function (tagsString) {
  60929. return Tags.RemoveTagsFrom(obj, tagsString);
  60930. };
  60931. obj.matchesTagsQuery = function (tagsQuery) {
  60932. return Tags.MatchesQuery(obj, tagsQuery);
  60933. };
  60934. };
  60935. Tags.DisableFor = function (obj) {
  60936. delete obj._tags;
  60937. delete obj.hasTags;
  60938. delete obj.addTags;
  60939. delete obj.removeTags;
  60940. delete obj.matchesTagsQuery;
  60941. };
  60942. Tags.HasTags = function (obj) {
  60943. if (!obj._tags) {
  60944. return false;
  60945. }
  60946. return !BABYLON.Tools.IsEmpty(obj._tags);
  60947. };
  60948. Tags.GetTags = function (obj, asString) {
  60949. if (asString === void 0) { asString = true; }
  60950. if (!obj._tags) {
  60951. return null;
  60952. }
  60953. if (asString) {
  60954. var tagsArray = [];
  60955. for (var tag in obj._tags) {
  60956. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  60957. tagsArray.push(tag);
  60958. }
  60959. }
  60960. return tagsArray.join(" ");
  60961. }
  60962. else {
  60963. return obj._tags;
  60964. }
  60965. };
  60966. // the tags 'true' and 'false' are reserved and cannot be used as tags
  60967. // a tag cannot start with '||', '&&', and '!'
  60968. // it cannot contain whitespaces
  60969. Tags.AddTagsTo = function (obj, tagsString) {
  60970. if (!tagsString) {
  60971. return;
  60972. }
  60973. if (typeof tagsString !== "string") {
  60974. return;
  60975. }
  60976. var tags = tagsString.split(" ");
  60977. tags.forEach(function (tag, index, array) {
  60978. Tags._AddTagTo(obj, tag);
  60979. });
  60980. };
  60981. Tags._AddTagTo = function (obj, tag) {
  60982. tag = tag.trim();
  60983. if (tag === "" || tag === "true" || tag === "false") {
  60984. return;
  60985. }
  60986. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  60987. return;
  60988. }
  60989. Tags.EnableFor(obj);
  60990. obj._tags[tag] = true;
  60991. };
  60992. Tags.RemoveTagsFrom = function (obj, tagsString) {
  60993. if (!Tags.HasTags(obj)) {
  60994. return;
  60995. }
  60996. var tags = tagsString.split(" ");
  60997. for (var t in tags) {
  60998. Tags._RemoveTagFrom(obj, tags[t]);
  60999. }
  61000. };
  61001. Tags._RemoveTagFrom = function (obj, tag) {
  61002. delete obj._tags[tag];
  61003. };
  61004. Tags.MatchesQuery = function (obj, tagsQuery) {
  61005. if (tagsQuery === undefined) {
  61006. return true;
  61007. }
  61008. if (tagsQuery === "") {
  61009. return Tags.HasTags(obj);
  61010. }
  61011. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  61012. };
  61013. return Tags;
  61014. }());
  61015. BABYLON.Tags = Tags;
  61016. })(BABYLON || (BABYLON = {}));
  61017. //# sourceMappingURL=babylon.tags.js.map
  61018. var BABYLON;
  61019. (function (BABYLON) {
  61020. var AndOrNotEvaluator = /** @class */ (function () {
  61021. function AndOrNotEvaluator() {
  61022. }
  61023. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  61024. if (!query.match(/\([^\(\)]*\)/g)) {
  61025. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  61026. }
  61027. else {
  61028. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  61029. // remove parenthesis
  61030. r = r.slice(1, r.length - 1);
  61031. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  61032. });
  61033. }
  61034. if (query === "true") {
  61035. return true;
  61036. }
  61037. if (query === "false") {
  61038. return false;
  61039. }
  61040. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  61041. };
  61042. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  61043. evaluateCallback = evaluateCallback || (function (r) {
  61044. return r === "true" ? true : false;
  61045. });
  61046. var result;
  61047. var or = parenthesisContent.split("||");
  61048. for (var i in or) {
  61049. if (or.hasOwnProperty(i)) {
  61050. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  61051. var and = ori.split("&&");
  61052. if (and.length > 1) {
  61053. for (var j = 0; j < and.length; ++j) {
  61054. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  61055. if (andj !== "true" && andj !== "false") {
  61056. if (andj[0] === "!") {
  61057. result = !evaluateCallback(andj.substring(1));
  61058. }
  61059. else {
  61060. result = evaluateCallback(andj);
  61061. }
  61062. }
  61063. else {
  61064. result = andj === "true" ? true : false;
  61065. }
  61066. if (!result) {
  61067. ori = "false";
  61068. break;
  61069. }
  61070. }
  61071. }
  61072. if (result || ori === "true") {
  61073. result = true;
  61074. break;
  61075. }
  61076. // result equals false (or undefined)
  61077. if (ori !== "true" && ori !== "false") {
  61078. if (ori[0] === "!") {
  61079. result = !evaluateCallback(ori.substring(1));
  61080. }
  61081. else {
  61082. result = evaluateCallback(ori);
  61083. }
  61084. }
  61085. else {
  61086. result = ori === "true" ? true : false;
  61087. }
  61088. }
  61089. }
  61090. // the whole parenthesis scope is replaced by 'true' or 'false'
  61091. return result ? "true" : "false";
  61092. };
  61093. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  61094. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  61095. // remove whitespaces
  61096. r = r.replace(/[\s]/g, function () { return ""; });
  61097. return r.length % 2 ? "!" : "";
  61098. });
  61099. booleanString = booleanString.trim();
  61100. if (booleanString === "!true") {
  61101. booleanString = "false";
  61102. }
  61103. else if (booleanString === "!false") {
  61104. booleanString = "true";
  61105. }
  61106. return booleanString;
  61107. };
  61108. return AndOrNotEvaluator;
  61109. }());
  61110. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  61111. })(BABYLON || (BABYLON = {}));
  61112. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  61113. var BABYLON;
  61114. (function (BABYLON) {
  61115. var Database = /** @class */ (function () {
  61116. function Database(urlToScene, callbackManifestChecked) {
  61117. // Handling various flavors of prefixed version of IndexedDB
  61118. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  61119. this.callbackManifestChecked = callbackManifestChecked;
  61120. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  61121. this.db = null;
  61122. this._enableSceneOffline = false;
  61123. this._enableTexturesOffline = false;
  61124. this.manifestVersionFound = 0;
  61125. this.mustUpdateRessources = false;
  61126. this.hasReachedQuota = false;
  61127. if (!Database.IDBStorageEnabled) {
  61128. this.callbackManifestChecked(true);
  61129. }
  61130. else {
  61131. this.checkManifestFile();
  61132. }
  61133. }
  61134. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  61135. get: function () {
  61136. return this._enableSceneOffline;
  61137. },
  61138. enumerable: true,
  61139. configurable: true
  61140. });
  61141. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  61142. get: function () {
  61143. return this._enableTexturesOffline;
  61144. },
  61145. enumerable: true,
  61146. configurable: true
  61147. });
  61148. Database.prototype.checkManifestFile = function () {
  61149. var _this = this;
  61150. var noManifestFile = function () {
  61151. _this._enableSceneOffline = false;
  61152. _this._enableTexturesOffline = false;
  61153. _this.callbackManifestChecked(false);
  61154. };
  61155. var timeStampUsed = false;
  61156. var manifestURL = this.currentSceneUrl + ".manifest";
  61157. var xhr = new XMLHttpRequest();
  61158. if (navigator.onLine) {
  61159. // Adding a timestamp to by-pass browsers' cache
  61160. timeStampUsed = true;
  61161. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  61162. }
  61163. xhr.open("GET", manifestURL, true);
  61164. xhr.addEventListener("load", function () {
  61165. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  61166. try {
  61167. var manifestFile = JSON.parse(xhr.response);
  61168. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  61169. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  61170. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  61171. _this.manifestVersionFound = manifestFile.version;
  61172. }
  61173. if (_this.callbackManifestChecked) {
  61174. _this.callbackManifestChecked(true);
  61175. }
  61176. }
  61177. catch (ex) {
  61178. noManifestFile();
  61179. }
  61180. }
  61181. else {
  61182. noManifestFile();
  61183. }
  61184. }, false);
  61185. xhr.addEventListener("error", function (event) {
  61186. if (timeStampUsed) {
  61187. timeStampUsed = false;
  61188. // Let's retry without the timeStamp
  61189. // It could fail when coupled with HTML5 Offline API
  61190. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  61191. xhr.open("GET", retryManifestURL, true);
  61192. xhr.send();
  61193. }
  61194. else {
  61195. noManifestFile();
  61196. }
  61197. }, false);
  61198. try {
  61199. xhr.send();
  61200. }
  61201. catch (ex) {
  61202. BABYLON.Tools.Error("Error on XHR send request.");
  61203. this.callbackManifestChecked(false);
  61204. }
  61205. };
  61206. Database.prototype.openAsync = function (successCallback, errorCallback) {
  61207. var _this = this;
  61208. var handleError = function () {
  61209. _this.isSupported = false;
  61210. if (errorCallback)
  61211. errorCallback();
  61212. };
  61213. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  61214. // Your browser doesn't support IndexedDB
  61215. this.isSupported = false;
  61216. if (errorCallback)
  61217. errorCallback();
  61218. }
  61219. else {
  61220. // If the DB hasn't been opened or created yet
  61221. if (!this.db) {
  61222. this.hasReachedQuota = false;
  61223. this.isSupported = true;
  61224. var request = this.idbFactory.open("babylonjs", 1);
  61225. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  61226. request.onerror = function (event) {
  61227. handleError();
  61228. };
  61229. // executes when a version change transaction cannot complete due to other active transactions
  61230. request.onblocked = function (event) {
  61231. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  61232. handleError();
  61233. };
  61234. // DB has been opened successfully
  61235. request.onsuccess = function (event) {
  61236. _this.db = request.result;
  61237. successCallback();
  61238. };
  61239. // Initialization of the DB. Creating Scenes & Textures stores
  61240. request.onupgradeneeded = function (event) {
  61241. _this.db = (event.target).result;
  61242. if (_this.db) {
  61243. try {
  61244. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  61245. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  61246. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  61247. }
  61248. catch (ex) {
  61249. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  61250. handleError();
  61251. }
  61252. }
  61253. };
  61254. }
  61255. else {
  61256. if (successCallback)
  61257. successCallback();
  61258. }
  61259. }
  61260. };
  61261. Database.prototype.loadImageFromDB = function (url, image) {
  61262. var _this = this;
  61263. var completeURL = Database.ReturnFullUrlLocation(url);
  61264. var saveAndLoadImage = function () {
  61265. if (!_this.hasReachedQuota && _this.db !== null) {
  61266. // the texture is not yet in the DB, let's try to save it
  61267. _this._saveImageIntoDBAsync(completeURL, image);
  61268. }
  61269. else {
  61270. image.src = url;
  61271. }
  61272. };
  61273. if (!this.mustUpdateRessources) {
  61274. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  61275. }
  61276. else {
  61277. saveAndLoadImage();
  61278. }
  61279. };
  61280. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  61281. if (this.isSupported && this.db !== null) {
  61282. var texture;
  61283. var transaction = this.db.transaction(["textures"]);
  61284. transaction.onabort = function (event) {
  61285. image.src = url;
  61286. };
  61287. transaction.oncomplete = function (event) {
  61288. var blobTextureURL;
  61289. if (texture) {
  61290. var URL = window.URL || window.webkitURL;
  61291. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  61292. image.onerror = function () {
  61293. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  61294. image.src = url;
  61295. };
  61296. image.src = blobTextureURL;
  61297. }
  61298. else {
  61299. notInDBCallback();
  61300. }
  61301. };
  61302. var getRequest = transaction.objectStore("textures").get(url);
  61303. getRequest.onsuccess = function (event) {
  61304. texture = (event.target).result;
  61305. };
  61306. getRequest.onerror = function (event) {
  61307. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  61308. image.src = url;
  61309. };
  61310. }
  61311. else {
  61312. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61313. image.src = url;
  61314. }
  61315. };
  61316. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  61317. var _this = this;
  61318. if (this.isSupported) {
  61319. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  61320. var generateBlobUrl = function () {
  61321. var blobTextureURL;
  61322. if (blob) {
  61323. var URL = window.URL || window.webkitURL;
  61324. try {
  61325. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  61326. }
  61327. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  61328. catch (ex) {
  61329. blobTextureURL = URL.createObjectURL(blob);
  61330. }
  61331. }
  61332. if (blobTextureURL) {
  61333. image.src = blobTextureURL;
  61334. }
  61335. };
  61336. if (Database.IsUASupportingBlobStorage) {
  61337. var xhr = new XMLHttpRequest(), blob;
  61338. xhr.open("GET", url, true);
  61339. xhr.responseType = "blob";
  61340. xhr.addEventListener("load", function () {
  61341. if (xhr.status === 200 && _this.db) {
  61342. // Blob as response (XHR2)
  61343. blob = xhr.response;
  61344. var transaction = _this.db.transaction(["textures"], "readwrite");
  61345. // the transaction could abort because of a QuotaExceededError error
  61346. transaction.onabort = function (event) {
  61347. try {
  61348. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61349. var srcElement = (event.srcElement || event.target);
  61350. var error = srcElement.error;
  61351. if (error && error.name === "QuotaExceededError") {
  61352. _this.hasReachedQuota = true;
  61353. }
  61354. }
  61355. catch (ex) { }
  61356. generateBlobUrl();
  61357. };
  61358. transaction.oncomplete = function (event) {
  61359. generateBlobUrl();
  61360. };
  61361. var newTexture = { textureUrl: url, data: blob };
  61362. try {
  61363. // Put the blob into the dabase
  61364. var addRequest = transaction.objectStore("textures").put(newTexture);
  61365. addRequest.onsuccess = function (event) {
  61366. };
  61367. addRequest.onerror = function (event) {
  61368. generateBlobUrl();
  61369. };
  61370. }
  61371. catch (ex) {
  61372. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  61373. if (ex.code === 25) {
  61374. Database.IsUASupportingBlobStorage = false;
  61375. }
  61376. image.src = url;
  61377. }
  61378. }
  61379. else {
  61380. image.src = url;
  61381. }
  61382. }, false);
  61383. xhr.addEventListener("error", function (event) {
  61384. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  61385. image.src = url;
  61386. }, false);
  61387. xhr.send();
  61388. }
  61389. else {
  61390. image.src = url;
  61391. }
  61392. }
  61393. else {
  61394. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61395. image.src = url;
  61396. }
  61397. };
  61398. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  61399. var _this = this;
  61400. var updateVersion = function () {
  61401. // the version is not yet in the DB or we need to update it
  61402. _this._saveVersionIntoDBAsync(url, versionLoaded);
  61403. };
  61404. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  61405. };
  61406. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  61407. var _this = this;
  61408. if (this.isSupported && this.db) {
  61409. var version;
  61410. try {
  61411. var transaction = this.db.transaction(["versions"]);
  61412. transaction.oncomplete = function (event) {
  61413. if (version) {
  61414. // If the version in the JSON file is > than the version in DB
  61415. if (_this.manifestVersionFound > version.data) {
  61416. _this.mustUpdateRessources = true;
  61417. updateInDBCallback();
  61418. }
  61419. else {
  61420. callback(version.data);
  61421. }
  61422. }
  61423. else {
  61424. _this.mustUpdateRessources = true;
  61425. updateInDBCallback();
  61426. }
  61427. };
  61428. transaction.onabort = function (event) {
  61429. callback(-1);
  61430. };
  61431. var getRequest = transaction.objectStore("versions").get(url);
  61432. getRequest.onsuccess = function (event) {
  61433. version = (event.target).result;
  61434. };
  61435. getRequest.onerror = function (event) {
  61436. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  61437. callback(-1);
  61438. };
  61439. }
  61440. catch (ex) {
  61441. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  61442. callback(-1);
  61443. }
  61444. }
  61445. else {
  61446. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61447. callback(-1);
  61448. }
  61449. };
  61450. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  61451. var _this = this;
  61452. if (this.isSupported && !this.hasReachedQuota && this.db) {
  61453. try {
  61454. // Open a transaction to the database
  61455. var transaction = this.db.transaction(["versions"], "readwrite");
  61456. // the transaction could abort because of a QuotaExceededError error
  61457. transaction.onabort = function (event) {
  61458. try {
  61459. var error = event.srcElement['error'];
  61460. if (error && error.name === "QuotaExceededError") {
  61461. _this.hasReachedQuota = true;
  61462. }
  61463. }
  61464. catch (ex) { }
  61465. callback(-1);
  61466. };
  61467. transaction.oncomplete = function (event) {
  61468. callback(_this.manifestVersionFound);
  61469. };
  61470. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  61471. // Put the scene into the database
  61472. var addRequest = transaction.objectStore("versions").put(newVersion);
  61473. addRequest.onsuccess = function (event) {
  61474. };
  61475. addRequest.onerror = function (event) {
  61476. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  61477. };
  61478. }
  61479. catch (ex) {
  61480. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  61481. callback(-1);
  61482. }
  61483. }
  61484. else {
  61485. callback(-1);
  61486. }
  61487. };
  61488. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  61489. var _this = this;
  61490. var completeUrl = Database.ReturnFullUrlLocation(url);
  61491. var saveAndLoadFile = function () {
  61492. // the scene is not yet in the DB, let's try to save it
  61493. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  61494. };
  61495. this._checkVersionFromDB(completeUrl, function (version) {
  61496. if (version !== -1) {
  61497. if (!_this.mustUpdateRessources) {
  61498. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  61499. }
  61500. else {
  61501. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  61502. }
  61503. }
  61504. else {
  61505. if (errorCallback) {
  61506. errorCallback();
  61507. }
  61508. }
  61509. });
  61510. };
  61511. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  61512. if (this.isSupported && this.db) {
  61513. var targetStore;
  61514. if (url.indexOf(".babylon") !== -1) {
  61515. targetStore = "scenes";
  61516. }
  61517. else {
  61518. targetStore = "textures";
  61519. }
  61520. var file;
  61521. var transaction = this.db.transaction([targetStore]);
  61522. transaction.oncomplete = function (event) {
  61523. if (file) {
  61524. callback(file.data);
  61525. }
  61526. else {
  61527. notInDBCallback();
  61528. }
  61529. };
  61530. transaction.onabort = function (event) {
  61531. notInDBCallback();
  61532. };
  61533. var getRequest = transaction.objectStore(targetStore).get(url);
  61534. getRequest.onsuccess = function (event) {
  61535. file = (event.target).result;
  61536. };
  61537. getRequest.onerror = function (event) {
  61538. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  61539. notInDBCallback();
  61540. };
  61541. }
  61542. else {
  61543. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61544. callback();
  61545. }
  61546. };
  61547. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  61548. var _this = this;
  61549. if (this.isSupported) {
  61550. var targetStore;
  61551. if (url.indexOf(".babylon") !== -1) {
  61552. targetStore = "scenes";
  61553. }
  61554. else {
  61555. targetStore = "textures";
  61556. }
  61557. // Create XHR
  61558. var xhr = new XMLHttpRequest();
  61559. var fileData;
  61560. xhr.open("GET", url, true);
  61561. if (useArrayBuffer) {
  61562. xhr.responseType = "arraybuffer";
  61563. }
  61564. if (progressCallback) {
  61565. xhr.onprogress = progressCallback;
  61566. }
  61567. xhr.addEventListener("load", function () {
  61568. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  61569. // Blob as response (XHR2)
  61570. //fileData = xhr.responseText;
  61571. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  61572. if (!_this.hasReachedQuota && _this.db) {
  61573. // Open a transaction to the database
  61574. var transaction = _this.db.transaction([targetStore], "readwrite");
  61575. // the transaction could abort because of a QuotaExceededError error
  61576. transaction.onabort = function (event) {
  61577. try {
  61578. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61579. var error = event.srcElement['error'];
  61580. if (error && error.name === "QuotaExceededError") {
  61581. _this.hasReachedQuota = true;
  61582. }
  61583. }
  61584. catch (ex) { }
  61585. callback(fileData);
  61586. };
  61587. transaction.oncomplete = function (event) {
  61588. callback(fileData);
  61589. };
  61590. var newFile;
  61591. if (targetStore === "scenes") {
  61592. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  61593. }
  61594. else {
  61595. newFile = { textureUrl: url, data: fileData };
  61596. }
  61597. try {
  61598. // Put the scene into the database
  61599. var addRequest = transaction.objectStore(targetStore).put(newFile);
  61600. addRequest.onsuccess = function (event) {
  61601. };
  61602. addRequest.onerror = function (event) {
  61603. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  61604. };
  61605. }
  61606. catch (ex) {
  61607. callback(fileData);
  61608. }
  61609. }
  61610. else {
  61611. callback(fileData);
  61612. }
  61613. }
  61614. else {
  61615. callback();
  61616. }
  61617. }, false);
  61618. xhr.addEventListener("error", function (event) {
  61619. BABYLON.Tools.Error("error on XHR request.");
  61620. callback();
  61621. }, false);
  61622. xhr.send();
  61623. }
  61624. else {
  61625. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61626. callback();
  61627. }
  61628. };
  61629. Database.IsUASupportingBlobStorage = true;
  61630. Database.IDBStorageEnabled = true;
  61631. Database.parseURL = function (url) {
  61632. var a = document.createElement('a');
  61633. a.href = url;
  61634. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  61635. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  61636. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  61637. return absLocation;
  61638. };
  61639. Database.ReturnFullUrlLocation = function (url) {
  61640. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  61641. return (Database.parseURL(window.location.href) + url);
  61642. }
  61643. else {
  61644. return url;
  61645. }
  61646. };
  61647. return Database;
  61648. }());
  61649. BABYLON.Database = Database;
  61650. })(BABYLON || (BABYLON = {}));
  61651. //# sourceMappingURL=babylon.database.js.map
  61652. var BABYLON;
  61653. (function (BABYLON) {
  61654. var FresnelParameters = /** @class */ (function () {
  61655. function FresnelParameters() {
  61656. this._isEnabled = true;
  61657. this.leftColor = BABYLON.Color3.White();
  61658. this.rightColor = BABYLON.Color3.Black();
  61659. this.bias = 0;
  61660. this.power = 1;
  61661. }
  61662. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  61663. get: function () {
  61664. return this._isEnabled;
  61665. },
  61666. set: function (value) {
  61667. if (this._isEnabled === value) {
  61668. return;
  61669. }
  61670. this._isEnabled = value;
  61671. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  61672. },
  61673. enumerable: true,
  61674. configurable: true
  61675. });
  61676. FresnelParameters.prototype.clone = function () {
  61677. var newFresnelParameters = new FresnelParameters();
  61678. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  61679. return newFresnelParameters;
  61680. };
  61681. FresnelParameters.prototype.serialize = function () {
  61682. var serializationObject = {};
  61683. serializationObject.isEnabled = this.isEnabled;
  61684. serializationObject.leftColor = this.leftColor;
  61685. serializationObject.rightColor = this.rightColor;
  61686. serializationObject.bias = this.bias;
  61687. serializationObject.power = this.power;
  61688. return serializationObject;
  61689. };
  61690. FresnelParameters.Parse = function (parsedFresnelParameters) {
  61691. var fresnelParameters = new FresnelParameters();
  61692. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  61693. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  61694. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  61695. fresnelParameters.bias = parsedFresnelParameters.bias;
  61696. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  61697. return fresnelParameters;
  61698. };
  61699. return FresnelParameters;
  61700. }());
  61701. BABYLON.FresnelParameters = FresnelParameters;
  61702. })(BABYLON || (BABYLON = {}));
  61703. //# sourceMappingURL=babylon.fresnelParameters.js.map
  61704. var BABYLON;
  61705. (function (BABYLON) {
  61706. var MultiMaterial = /** @class */ (function (_super) {
  61707. __extends(MultiMaterial, _super);
  61708. function MultiMaterial(name, scene) {
  61709. var _this = _super.call(this, name, scene, true) || this;
  61710. scene.multiMaterials.push(_this);
  61711. _this.subMaterials = new Array();
  61712. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  61713. return _this;
  61714. }
  61715. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  61716. get: function () {
  61717. return this._subMaterials;
  61718. },
  61719. set: function (value) {
  61720. this._subMaterials = value;
  61721. this._hookArray(value);
  61722. },
  61723. enumerable: true,
  61724. configurable: true
  61725. });
  61726. MultiMaterial.prototype._hookArray = function (array) {
  61727. var _this = this;
  61728. var oldPush = array.push;
  61729. array.push = function () {
  61730. var items = [];
  61731. for (var _i = 0; _i < arguments.length; _i++) {
  61732. items[_i] = arguments[_i];
  61733. }
  61734. var result = oldPush.apply(array, items);
  61735. _this._markAllSubMeshesAsTexturesDirty();
  61736. return result;
  61737. };
  61738. var oldSplice = array.splice;
  61739. array.splice = function (index, deleteCount) {
  61740. var deleted = oldSplice.apply(array, [index, deleteCount]);
  61741. _this._markAllSubMeshesAsTexturesDirty();
  61742. return deleted;
  61743. };
  61744. };
  61745. // Properties
  61746. MultiMaterial.prototype.getSubMaterial = function (index) {
  61747. if (index < 0 || index >= this.subMaterials.length) {
  61748. return this.getScene().defaultMaterial;
  61749. }
  61750. return this.subMaterials[index];
  61751. };
  61752. MultiMaterial.prototype.getActiveTextures = function () {
  61753. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  61754. if (subMaterial) {
  61755. return subMaterial.getActiveTextures();
  61756. }
  61757. else {
  61758. return [];
  61759. }
  61760. }));
  61761. var _a;
  61762. };
  61763. // Methods
  61764. MultiMaterial.prototype.getClassName = function () {
  61765. return "MultiMaterial";
  61766. };
  61767. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  61768. for (var index = 0; index < this.subMaterials.length; index++) {
  61769. var subMaterial = this.subMaterials[index];
  61770. if (subMaterial) {
  61771. if (subMaterial.storeEffectOnSubMeshes) {
  61772. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  61773. return false;
  61774. }
  61775. continue;
  61776. }
  61777. if (!subMaterial.isReady(mesh)) {
  61778. return false;
  61779. }
  61780. }
  61781. }
  61782. return true;
  61783. };
  61784. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  61785. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  61786. for (var index = 0; index < this.subMaterials.length; index++) {
  61787. var subMaterial = null;
  61788. var current = this.subMaterials[index];
  61789. if (cloneChildren && current) {
  61790. subMaterial = current.clone(name + "-" + current.name);
  61791. }
  61792. else {
  61793. subMaterial = this.subMaterials[index];
  61794. }
  61795. newMultiMaterial.subMaterials.push(subMaterial);
  61796. }
  61797. return newMultiMaterial;
  61798. };
  61799. MultiMaterial.prototype.serialize = function () {
  61800. var serializationObject = {};
  61801. serializationObject.name = this.name;
  61802. serializationObject.id = this.id;
  61803. if (BABYLON.Tags) {
  61804. serializationObject.tags = BABYLON.Tags.GetTags(this);
  61805. }
  61806. serializationObject.materials = [];
  61807. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  61808. var subMat = this.subMaterials[matIndex];
  61809. if (subMat) {
  61810. serializationObject.materials.push(subMat.id);
  61811. }
  61812. else {
  61813. serializationObject.materials.push(null);
  61814. }
  61815. }
  61816. return serializationObject;
  61817. };
  61818. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61819. var scene = this.getScene();
  61820. if (!scene) {
  61821. return;
  61822. }
  61823. var index = scene.multiMaterials.indexOf(this);
  61824. if (index >= 0) {
  61825. scene.multiMaterials.splice(index, 1);
  61826. }
  61827. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61828. };
  61829. return MultiMaterial;
  61830. }(BABYLON.Material));
  61831. BABYLON.MultiMaterial = MultiMaterial;
  61832. })(BABYLON || (BABYLON = {}));
  61833. //# sourceMappingURL=babylon.multiMaterial.js.map
  61834. var BABYLON;
  61835. (function (BABYLON) {
  61836. var FreeCameraTouchInput = /** @class */ (function () {
  61837. function FreeCameraTouchInput() {
  61838. this._offsetX = null;
  61839. this._offsetY = null;
  61840. this._pointerPressed = new Array();
  61841. this.touchAngularSensibility = 200000.0;
  61842. this.touchMoveSensibility = 250.0;
  61843. }
  61844. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  61845. var _this = this;
  61846. var previousPosition = null;
  61847. if (this._pointerInput === undefined) {
  61848. this._onLostFocus = function (evt) {
  61849. _this._offsetX = null;
  61850. _this._offsetY = null;
  61851. };
  61852. this._pointerInput = function (p, s) {
  61853. var evt = p.event;
  61854. if (evt.pointerType === "mouse") {
  61855. return;
  61856. }
  61857. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  61858. if (!noPreventDefault) {
  61859. evt.preventDefault();
  61860. }
  61861. _this._pointerPressed.push(evt.pointerId);
  61862. if (_this._pointerPressed.length !== 1) {
  61863. return;
  61864. }
  61865. previousPosition = {
  61866. x: evt.clientX,
  61867. y: evt.clientY
  61868. };
  61869. }
  61870. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  61871. if (!noPreventDefault) {
  61872. evt.preventDefault();
  61873. }
  61874. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61875. if (index === -1) {
  61876. return;
  61877. }
  61878. _this._pointerPressed.splice(index, 1);
  61879. if (index != 0) {
  61880. return;
  61881. }
  61882. previousPosition = null;
  61883. _this._offsetX = null;
  61884. _this._offsetY = null;
  61885. }
  61886. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  61887. if (!noPreventDefault) {
  61888. evt.preventDefault();
  61889. }
  61890. if (!previousPosition) {
  61891. return;
  61892. }
  61893. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61894. if (index != 0) {
  61895. return;
  61896. }
  61897. _this._offsetX = evt.clientX - previousPosition.x;
  61898. _this._offsetY = -(evt.clientY - previousPosition.y);
  61899. }
  61900. };
  61901. }
  61902. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  61903. if (this._onLostFocus) {
  61904. element.addEventListener("blur", this._onLostFocus);
  61905. }
  61906. };
  61907. FreeCameraTouchInput.prototype.detachControl = function (element) {
  61908. if (this._pointerInput && element) {
  61909. if (this._observer) {
  61910. this.camera.getScene().onPointerObservable.remove(this._observer);
  61911. this._observer = null;
  61912. }
  61913. if (this._onLostFocus) {
  61914. element.removeEventListener("blur", this._onLostFocus);
  61915. this._onLostFocus = null;
  61916. }
  61917. this._pointerPressed = [];
  61918. this._offsetX = null;
  61919. this._offsetY = null;
  61920. }
  61921. };
  61922. FreeCameraTouchInput.prototype.checkInputs = function () {
  61923. if (this._offsetX && this._offsetY) {
  61924. var camera = this.camera;
  61925. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  61926. if (this._pointerPressed.length > 1) {
  61927. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  61928. }
  61929. else {
  61930. var speed = camera._computeLocalCameraSpeed();
  61931. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  61932. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  61933. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  61934. }
  61935. }
  61936. };
  61937. FreeCameraTouchInput.prototype.getClassName = function () {
  61938. return "FreeCameraTouchInput";
  61939. };
  61940. FreeCameraTouchInput.prototype.getSimpleName = function () {
  61941. return "touch";
  61942. };
  61943. __decorate([
  61944. BABYLON.serialize()
  61945. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  61946. __decorate([
  61947. BABYLON.serialize()
  61948. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  61949. return FreeCameraTouchInput;
  61950. }());
  61951. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  61952. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  61953. })(BABYLON || (BABYLON = {}));
  61954. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  61955. var BABYLON;
  61956. (function (BABYLON) {
  61957. // We're mainly based on the logic defined into the FreeCamera code
  61958. var TouchCamera = /** @class */ (function (_super) {
  61959. __extends(TouchCamera, _super);
  61960. //-- end properties for backward compatibility for inputs
  61961. function TouchCamera(name, position, scene) {
  61962. var _this = _super.call(this, name, position, scene) || this;
  61963. _this.inputs.addTouch();
  61964. _this._setupInputs();
  61965. return _this;
  61966. }
  61967. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  61968. //-- Begin properties for backward compatibility for inputs
  61969. get: function () {
  61970. var touch = this.inputs.attached["touch"];
  61971. if (touch)
  61972. return touch.touchAngularSensibility;
  61973. return 0;
  61974. },
  61975. set: function (value) {
  61976. var touch = this.inputs.attached["touch"];
  61977. if (touch)
  61978. touch.touchAngularSensibility = value;
  61979. },
  61980. enumerable: true,
  61981. configurable: true
  61982. });
  61983. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  61984. get: function () {
  61985. var touch = this.inputs.attached["touch"];
  61986. if (touch)
  61987. return touch.touchMoveSensibility;
  61988. return 0;
  61989. },
  61990. set: function (value) {
  61991. var touch = this.inputs.attached["touch"];
  61992. if (touch)
  61993. touch.touchMoveSensibility = value;
  61994. },
  61995. enumerable: true,
  61996. configurable: true
  61997. });
  61998. TouchCamera.prototype.getClassName = function () {
  61999. return "TouchCamera";
  62000. };
  62001. TouchCamera.prototype._setupInputs = function () {
  62002. var mouse = this.inputs.attached["mouse"];
  62003. if (mouse) {
  62004. mouse.touchEnabled = false;
  62005. }
  62006. };
  62007. return TouchCamera;
  62008. }(BABYLON.FreeCamera));
  62009. BABYLON.TouchCamera = TouchCamera;
  62010. })(BABYLON || (BABYLON = {}));
  62011. //# sourceMappingURL=babylon.touchCamera.js.map
  62012. var BABYLON;
  62013. (function (BABYLON) {
  62014. var ProceduralTexture = /** @class */ (function (_super) {
  62015. __extends(ProceduralTexture, _super);
  62016. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  62017. if (fallbackTexture === void 0) { fallbackTexture = null; }
  62018. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62019. if (isCube === void 0) { isCube = false; }
  62020. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62021. _this.isCube = isCube;
  62022. _this.isEnabled = true;
  62023. _this._currentRefreshId = -1;
  62024. _this._refreshRate = 1;
  62025. _this._vertexBuffers = {};
  62026. _this._uniforms = new Array();
  62027. _this._samplers = new Array();
  62028. _this._textures = {};
  62029. _this._floats = {};
  62030. _this._floatsArrays = {};
  62031. _this._colors3 = {};
  62032. _this._colors4 = {};
  62033. _this._vectors2 = {};
  62034. _this._vectors3 = {};
  62035. _this._matrices = {};
  62036. _this._fallbackTextureUsed = false;
  62037. scene._proceduralTextures.push(_this);
  62038. _this._engine = scene.getEngine();
  62039. _this.name = name;
  62040. _this.isRenderTarget = true;
  62041. _this._size = size;
  62042. _this._generateMipMaps = generateMipMaps;
  62043. _this.setFragment(fragment);
  62044. _this._fallbackTexture = fallbackTexture;
  62045. if (isCube) {
  62046. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  62047. _this.setFloat("face", 0);
  62048. }
  62049. else {
  62050. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  62051. }
  62052. // VBO
  62053. var vertices = [];
  62054. vertices.push(1, 1);
  62055. vertices.push(-1, 1);
  62056. vertices.push(-1, -1);
  62057. vertices.push(1, -1);
  62058. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  62059. _this._createIndexBuffer();
  62060. return _this;
  62061. }
  62062. ProceduralTexture.prototype._createIndexBuffer = function () {
  62063. var engine = this._engine;
  62064. // Indices
  62065. var indices = [];
  62066. indices.push(0);
  62067. indices.push(1);
  62068. indices.push(2);
  62069. indices.push(0);
  62070. indices.push(2);
  62071. indices.push(3);
  62072. this._indexBuffer = engine.createIndexBuffer(indices);
  62073. };
  62074. ProceduralTexture.prototype._rebuild = function () {
  62075. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62076. if (vb) {
  62077. vb._rebuild();
  62078. }
  62079. this._createIndexBuffer();
  62080. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  62081. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  62082. }
  62083. };
  62084. ProceduralTexture.prototype.reset = function () {
  62085. if (this._effect === undefined) {
  62086. return;
  62087. }
  62088. var engine = this._engine;
  62089. engine._releaseEffect(this._effect);
  62090. };
  62091. ProceduralTexture.prototype.isReady = function () {
  62092. var _this = this;
  62093. var engine = this._engine;
  62094. var shaders;
  62095. if (!this._fragment) {
  62096. return false;
  62097. }
  62098. if (this._fallbackTextureUsed) {
  62099. return true;
  62100. }
  62101. if (this._fragment.fragmentElement !== undefined) {
  62102. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  62103. }
  62104. else {
  62105. shaders = { vertex: "procedural", fragment: this._fragment };
  62106. }
  62107. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  62108. _this.releaseInternalTexture();
  62109. if (_this._fallbackTexture) {
  62110. _this._texture = _this._fallbackTexture._texture;
  62111. if (_this._texture) {
  62112. _this._texture.incrementReferences();
  62113. }
  62114. }
  62115. _this._fallbackTextureUsed = true;
  62116. });
  62117. return this._effect.isReady();
  62118. };
  62119. ProceduralTexture.prototype.resetRefreshCounter = function () {
  62120. this._currentRefreshId = -1;
  62121. };
  62122. ProceduralTexture.prototype.setFragment = function (fragment) {
  62123. this._fragment = fragment;
  62124. };
  62125. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  62126. get: function () {
  62127. return this._refreshRate;
  62128. },
  62129. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62130. set: function (value) {
  62131. this._refreshRate = value;
  62132. this.resetRefreshCounter();
  62133. },
  62134. enumerable: true,
  62135. configurable: true
  62136. });
  62137. ProceduralTexture.prototype._shouldRender = function () {
  62138. if (!this.isEnabled || !this.isReady() || !this._texture) {
  62139. return false;
  62140. }
  62141. if (this._fallbackTextureUsed) {
  62142. return false;
  62143. }
  62144. if (this._currentRefreshId === -1) {
  62145. this._currentRefreshId = 1;
  62146. return true;
  62147. }
  62148. if (this.refreshRate === this._currentRefreshId) {
  62149. this._currentRefreshId = 1;
  62150. return true;
  62151. }
  62152. this._currentRefreshId++;
  62153. return false;
  62154. };
  62155. ProceduralTexture.prototype.getRenderSize = function () {
  62156. return this._size;
  62157. };
  62158. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  62159. if (this._fallbackTextureUsed) {
  62160. return;
  62161. }
  62162. this.releaseInternalTexture();
  62163. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  62164. };
  62165. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  62166. if (this._uniforms.indexOf(uniformName) === -1) {
  62167. this._uniforms.push(uniformName);
  62168. }
  62169. };
  62170. ProceduralTexture.prototype.setTexture = function (name, texture) {
  62171. if (this._samplers.indexOf(name) === -1) {
  62172. this._samplers.push(name);
  62173. }
  62174. this._textures[name] = texture;
  62175. return this;
  62176. };
  62177. ProceduralTexture.prototype.setFloat = function (name, value) {
  62178. this._checkUniform(name);
  62179. this._floats[name] = value;
  62180. return this;
  62181. };
  62182. ProceduralTexture.prototype.setFloats = function (name, value) {
  62183. this._checkUniform(name);
  62184. this._floatsArrays[name] = value;
  62185. return this;
  62186. };
  62187. ProceduralTexture.prototype.setColor3 = function (name, value) {
  62188. this._checkUniform(name);
  62189. this._colors3[name] = value;
  62190. return this;
  62191. };
  62192. ProceduralTexture.prototype.setColor4 = function (name, value) {
  62193. this._checkUniform(name);
  62194. this._colors4[name] = value;
  62195. return this;
  62196. };
  62197. ProceduralTexture.prototype.setVector2 = function (name, value) {
  62198. this._checkUniform(name);
  62199. this._vectors2[name] = value;
  62200. return this;
  62201. };
  62202. ProceduralTexture.prototype.setVector3 = function (name, value) {
  62203. this._checkUniform(name);
  62204. this._vectors3[name] = value;
  62205. return this;
  62206. };
  62207. ProceduralTexture.prototype.setMatrix = function (name, value) {
  62208. this._checkUniform(name);
  62209. this._matrices[name] = value;
  62210. return this;
  62211. };
  62212. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62213. var scene = this.getScene();
  62214. if (!scene) {
  62215. return;
  62216. }
  62217. var engine = this._engine;
  62218. // Render
  62219. engine.enableEffect(this._effect);
  62220. engine.setState(false);
  62221. // Texture
  62222. for (var name in this._textures) {
  62223. this._effect.setTexture(name, this._textures[name]);
  62224. }
  62225. // Float
  62226. for (name in this._floats) {
  62227. this._effect.setFloat(name, this._floats[name]);
  62228. }
  62229. // Floats
  62230. for (name in this._floatsArrays) {
  62231. this._effect.setArray(name, this._floatsArrays[name]);
  62232. }
  62233. // Color3
  62234. for (name in this._colors3) {
  62235. this._effect.setColor3(name, this._colors3[name]);
  62236. }
  62237. // Color4
  62238. for (name in this._colors4) {
  62239. var color = this._colors4[name];
  62240. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62241. }
  62242. // Vector2
  62243. for (name in this._vectors2) {
  62244. this._effect.setVector2(name, this._vectors2[name]);
  62245. }
  62246. // Vector3
  62247. for (name in this._vectors3) {
  62248. this._effect.setVector3(name, this._vectors3[name]);
  62249. }
  62250. // Matrix
  62251. for (name in this._matrices) {
  62252. this._effect.setMatrix(name, this._matrices[name]);
  62253. }
  62254. if (!this._texture) {
  62255. return;
  62256. }
  62257. if (this.isCube) {
  62258. for (var face = 0; face < 6; face++) {
  62259. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  62260. // VBOs
  62261. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62262. this._effect.setFloat("face", face);
  62263. // Clear
  62264. engine.clear(scene.clearColor, true, true, true);
  62265. // Draw order
  62266. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62267. // Mipmaps
  62268. if (face === 5) {
  62269. engine.generateMipMapsForCubemap(this._texture);
  62270. }
  62271. }
  62272. }
  62273. else {
  62274. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  62275. // VBOs
  62276. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62277. // Clear
  62278. engine.clear(scene.clearColor, true, true, true);
  62279. // Draw order
  62280. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62281. }
  62282. // Unbind
  62283. engine.unBindFramebuffer(this._texture, this.isCube);
  62284. if (this.onGenerated) {
  62285. this.onGenerated();
  62286. }
  62287. };
  62288. ProceduralTexture.prototype.clone = function () {
  62289. var textureSize = this.getSize();
  62290. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  62291. // Base texture
  62292. newTexture.hasAlpha = this.hasAlpha;
  62293. newTexture.level = this.level;
  62294. // RenderTarget Texture
  62295. newTexture.coordinatesMode = this.coordinatesMode;
  62296. return newTexture;
  62297. };
  62298. ProceduralTexture.prototype.dispose = function () {
  62299. var scene = this.getScene();
  62300. if (!scene) {
  62301. return;
  62302. }
  62303. var index = scene._proceduralTextures.indexOf(this);
  62304. if (index >= 0) {
  62305. scene._proceduralTextures.splice(index, 1);
  62306. }
  62307. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62308. if (vertexBuffer) {
  62309. vertexBuffer.dispose();
  62310. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62311. }
  62312. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  62313. this._indexBuffer = null;
  62314. }
  62315. _super.prototype.dispose.call(this);
  62316. };
  62317. return ProceduralTexture;
  62318. }(BABYLON.Texture));
  62319. BABYLON.ProceduralTexture = ProceduralTexture;
  62320. })(BABYLON || (BABYLON = {}));
  62321. //# sourceMappingURL=babylon.proceduralTexture.js.map
  62322. var BABYLON;
  62323. (function (BABYLON) {
  62324. var CustomProceduralTexture = /** @class */ (function (_super) {
  62325. __extends(CustomProceduralTexture, _super);
  62326. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  62327. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  62328. _this._animate = true;
  62329. _this._time = 0;
  62330. _this._texturePath = texturePath;
  62331. //Try to load json
  62332. _this.loadJson(texturePath);
  62333. _this.refreshRate = 1;
  62334. return _this;
  62335. }
  62336. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  62337. var _this = this;
  62338. var noConfigFile = function () {
  62339. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  62340. try {
  62341. _this.setFragment(_this._texturePath);
  62342. }
  62343. catch (ex) {
  62344. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  62345. }
  62346. };
  62347. var configFileUrl = jsonUrl + "/config.json";
  62348. var xhr = new XMLHttpRequest();
  62349. xhr.open("GET", configFileUrl, true);
  62350. xhr.addEventListener("load", function () {
  62351. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62352. try {
  62353. _this._config = JSON.parse(xhr.response);
  62354. _this.updateShaderUniforms();
  62355. _this.updateTextures();
  62356. _this.setFragment(_this._texturePath + "/custom");
  62357. _this._animate = _this._config.animate;
  62358. _this.refreshRate = _this._config.refreshrate;
  62359. }
  62360. catch (ex) {
  62361. noConfigFile();
  62362. }
  62363. }
  62364. else {
  62365. noConfigFile();
  62366. }
  62367. }, false);
  62368. xhr.addEventListener("error", function () {
  62369. noConfigFile();
  62370. }, false);
  62371. try {
  62372. xhr.send();
  62373. }
  62374. catch (ex) {
  62375. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  62376. }
  62377. };
  62378. CustomProceduralTexture.prototype.isReady = function () {
  62379. if (!_super.prototype.isReady.call(this)) {
  62380. return false;
  62381. }
  62382. for (var name in this._textures) {
  62383. var texture = this._textures[name];
  62384. if (!texture.isReady()) {
  62385. return false;
  62386. }
  62387. }
  62388. return true;
  62389. };
  62390. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62391. var scene = this.getScene();
  62392. if (this._animate && scene) {
  62393. this._time += scene.getAnimationRatio() * 0.03;
  62394. this.updateShaderUniforms();
  62395. }
  62396. _super.prototype.render.call(this, useCameraPostProcess);
  62397. };
  62398. CustomProceduralTexture.prototype.updateTextures = function () {
  62399. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  62400. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  62401. }
  62402. };
  62403. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  62404. if (this._config) {
  62405. for (var j = 0; j < this._config.uniforms.length; j++) {
  62406. var uniform = this._config.uniforms[j];
  62407. switch (uniform.type) {
  62408. case "float":
  62409. this.setFloat(uniform.name, uniform.value);
  62410. break;
  62411. case "color3":
  62412. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  62413. break;
  62414. case "color4":
  62415. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  62416. break;
  62417. case "vector2":
  62418. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  62419. break;
  62420. case "vector3":
  62421. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  62422. break;
  62423. }
  62424. }
  62425. }
  62426. this.setFloat("time", this._time);
  62427. };
  62428. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  62429. get: function () {
  62430. return this._animate;
  62431. },
  62432. set: function (value) {
  62433. this._animate = value;
  62434. },
  62435. enumerable: true,
  62436. configurable: true
  62437. });
  62438. return CustomProceduralTexture;
  62439. }(BABYLON.ProceduralTexture));
  62440. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  62441. })(BABYLON || (BABYLON = {}));
  62442. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  62443. var BABYLON;
  62444. (function (BABYLON) {
  62445. var FreeCameraGamepadInput = /** @class */ (function () {
  62446. function FreeCameraGamepadInput() {
  62447. this.gamepadAngularSensibility = 200;
  62448. this.gamepadMoveSensibility = 40;
  62449. // private members
  62450. this._cameraTransform = BABYLON.Matrix.Identity();
  62451. this._deltaTransform = BABYLON.Vector3.Zero();
  62452. this._vector3 = BABYLON.Vector3.Zero();
  62453. this._vector2 = BABYLON.Vector2.Zero();
  62454. }
  62455. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62456. var _this = this;
  62457. var manager = this.camera.getScene().gamepadManager;
  62458. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62459. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62460. // prioritize XBOX gamepads.
  62461. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62462. _this.gamepad = gamepad;
  62463. }
  62464. }
  62465. });
  62466. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62467. if (_this.gamepad === gamepad) {
  62468. _this.gamepad = null;
  62469. }
  62470. });
  62471. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62472. };
  62473. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  62474. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62475. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62476. this.gamepad = null;
  62477. };
  62478. FreeCameraGamepadInput.prototype.checkInputs = function () {
  62479. if (this.gamepad && this.gamepad.leftStick) {
  62480. var camera = this.camera;
  62481. var LSValues = this.gamepad.leftStick;
  62482. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  62483. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62484. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  62485. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  62486. var RSValues = this.gamepad.rightStick;
  62487. if (RSValues) {
  62488. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  62489. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  62490. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  62491. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  62492. }
  62493. else {
  62494. RSValues = { x: 0, y: 0 };
  62495. }
  62496. if (!camera.rotationQuaternion) {
  62497. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  62498. }
  62499. else {
  62500. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  62501. }
  62502. var speed = camera._computeLocalCameraSpeed() * 50.0;
  62503. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  62504. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  62505. camera.cameraDirection.addInPlace(this._deltaTransform);
  62506. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  62507. camera.cameraRotation.addInPlace(this._vector2);
  62508. }
  62509. };
  62510. FreeCameraGamepadInput.prototype.getClassName = function () {
  62511. return "FreeCameraGamepadInput";
  62512. };
  62513. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  62514. return "gamepad";
  62515. };
  62516. __decorate([
  62517. BABYLON.serialize()
  62518. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  62519. __decorate([
  62520. BABYLON.serialize()
  62521. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62522. return FreeCameraGamepadInput;
  62523. }());
  62524. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  62525. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  62526. })(BABYLON || (BABYLON = {}));
  62527. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  62528. var BABYLON;
  62529. (function (BABYLON) {
  62530. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  62531. function ArcRotateCameraGamepadInput() {
  62532. this.gamepadRotationSensibility = 80;
  62533. this.gamepadMoveSensibility = 40;
  62534. }
  62535. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62536. var _this = this;
  62537. var manager = this.camera.getScene().gamepadManager;
  62538. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62539. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62540. // prioritize XBOX gamepads.
  62541. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62542. _this.gamepad = gamepad;
  62543. }
  62544. }
  62545. });
  62546. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62547. if (_this.gamepad === gamepad) {
  62548. _this.gamepad = null;
  62549. }
  62550. });
  62551. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62552. };
  62553. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  62554. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62555. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62556. this.gamepad = null;
  62557. };
  62558. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  62559. if (this.gamepad) {
  62560. var camera = this.camera;
  62561. var RSValues = this.gamepad.rightStick;
  62562. if (RSValues) {
  62563. if (RSValues.x != 0) {
  62564. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  62565. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  62566. camera.inertialAlphaOffset += normalizedRX;
  62567. }
  62568. }
  62569. if (RSValues.y != 0) {
  62570. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  62571. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  62572. camera.inertialBetaOffset += normalizedRY;
  62573. }
  62574. }
  62575. }
  62576. var LSValues = this.gamepad.leftStick;
  62577. if (LSValues && LSValues.y != 0) {
  62578. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62579. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  62580. this.camera.inertialRadiusOffset -= normalizedLY;
  62581. }
  62582. }
  62583. }
  62584. };
  62585. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  62586. return "ArcRotateCameraGamepadInput";
  62587. };
  62588. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  62589. return "gamepad";
  62590. };
  62591. __decorate([
  62592. BABYLON.serialize()
  62593. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  62594. __decorate([
  62595. BABYLON.serialize()
  62596. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62597. return ArcRotateCameraGamepadInput;
  62598. }());
  62599. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  62600. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  62601. })(BABYLON || (BABYLON = {}));
  62602. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  62603. var BABYLON;
  62604. (function (BABYLON) {
  62605. var GamepadManager = /** @class */ (function () {
  62606. function GamepadManager(_scene) {
  62607. var _this = this;
  62608. this._scene = _scene;
  62609. this._babylonGamepads = [];
  62610. this._oneGamepadConnected = false;
  62611. this._isMonitoring = false;
  62612. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  62613. if (!BABYLON.Tools.IsWindowObjectExist()) {
  62614. this._gamepadEventSupported = false;
  62615. }
  62616. else {
  62617. this._gamepadEventSupported = 'GamepadEvent' in window;
  62618. this._gamepadSupport = (navigator.getGamepads ||
  62619. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  62620. }
  62621. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  62622. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  62623. for (var i in _this._babylonGamepads) {
  62624. var gamepad = _this._babylonGamepads[i];
  62625. if (gamepad && gamepad._isConnected) {
  62626. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  62627. }
  62628. }
  62629. });
  62630. this._onGamepadConnectedEvent = function (evt) {
  62631. var gamepad = evt.gamepad;
  62632. if (gamepad.index in _this._babylonGamepads) {
  62633. if (_this._babylonGamepads[gamepad.index].isConnected) {
  62634. return;
  62635. }
  62636. }
  62637. var newGamepad;
  62638. if (_this._babylonGamepads[gamepad.index]) {
  62639. newGamepad = _this._babylonGamepads[gamepad.index];
  62640. newGamepad.browserGamepad = gamepad;
  62641. newGamepad._isConnected = true;
  62642. }
  62643. else {
  62644. newGamepad = _this._addNewGamepad(gamepad);
  62645. }
  62646. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62647. _this._startMonitoringGamepads();
  62648. };
  62649. this._onGamepadDisconnectedEvent = function (evt) {
  62650. var gamepad = evt.gamepad;
  62651. // Remove the gamepad from the list of gamepads to monitor.
  62652. for (var i in _this._babylonGamepads) {
  62653. if (_this._babylonGamepads[i].index === gamepad.index) {
  62654. var disconnectedGamepad = _this._babylonGamepads[i];
  62655. disconnectedGamepad._isConnected = false;
  62656. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  62657. break;
  62658. }
  62659. }
  62660. };
  62661. if (this._gamepadSupport) {
  62662. //first add already-connected gamepads
  62663. this._updateGamepadObjects();
  62664. if (this._babylonGamepads.length) {
  62665. this._startMonitoringGamepads();
  62666. }
  62667. // Checking if the gamepad connected event is supported (like in Firefox)
  62668. if (this._gamepadEventSupported) {
  62669. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  62670. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  62671. }
  62672. else {
  62673. this._startMonitoringGamepads();
  62674. }
  62675. }
  62676. }
  62677. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  62678. get: function () {
  62679. return this._babylonGamepads;
  62680. },
  62681. enumerable: true,
  62682. configurable: true
  62683. });
  62684. GamepadManager.prototype.getGamepadByType = function (type) {
  62685. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  62686. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  62687. var gamepad = _a[_i];
  62688. if (gamepad && gamepad.type === type) {
  62689. return gamepad;
  62690. }
  62691. }
  62692. return null;
  62693. };
  62694. GamepadManager.prototype.dispose = function () {
  62695. if (this._gamepadEventSupported) {
  62696. if (this._onGamepadConnectedEvent) {
  62697. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  62698. }
  62699. if (this._onGamepadDisconnectedEvent) {
  62700. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  62701. }
  62702. this._onGamepadConnectedEvent = null;
  62703. this._onGamepadDisconnectedEvent = null;
  62704. }
  62705. this._babylonGamepads.forEach(function (gamepad) {
  62706. gamepad.dispose();
  62707. });
  62708. this.onGamepadConnectedObservable.clear();
  62709. this.onGamepadDisconnectedObservable.clear();
  62710. this._oneGamepadConnected = false;
  62711. this._stopMonitoringGamepads();
  62712. this._babylonGamepads = [];
  62713. };
  62714. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  62715. if (!this._oneGamepadConnected) {
  62716. this._oneGamepadConnected = true;
  62717. }
  62718. var newGamepad;
  62719. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  62720. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  62721. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  62722. }
  62723. else if (gamepad.pose) {
  62724. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  62725. }
  62726. else {
  62727. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  62728. }
  62729. this._babylonGamepads[newGamepad.index] = newGamepad;
  62730. return newGamepad;
  62731. };
  62732. GamepadManager.prototype._startMonitoringGamepads = function () {
  62733. if (!this._isMonitoring) {
  62734. this._isMonitoring = true;
  62735. //back-comp
  62736. if (!this._scene) {
  62737. this._checkGamepadsStatus();
  62738. }
  62739. }
  62740. };
  62741. GamepadManager.prototype._stopMonitoringGamepads = function () {
  62742. this._isMonitoring = false;
  62743. };
  62744. GamepadManager.prototype._checkGamepadsStatus = function () {
  62745. var _this = this;
  62746. // Hack to be compatible Chrome
  62747. this._updateGamepadObjects();
  62748. for (var i in this._babylonGamepads) {
  62749. var gamepad = this._babylonGamepads[i];
  62750. if (!gamepad || !gamepad.isConnected) {
  62751. continue;
  62752. }
  62753. gamepad.update();
  62754. }
  62755. if (this._isMonitoring && !this._scene) {
  62756. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  62757. }
  62758. };
  62759. // This function is called only on Chrome, which does not properly support
  62760. // connection/disconnection events and forces you to recopy again the gamepad object
  62761. GamepadManager.prototype._updateGamepadObjects = function () {
  62762. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  62763. for (var i = 0; i < gamepads.length; i++) {
  62764. if (gamepads[i]) {
  62765. if (!this._babylonGamepads[gamepads[i].index]) {
  62766. var newGamepad = this._addNewGamepad(gamepads[i]);
  62767. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62768. }
  62769. else {
  62770. // Forced to copy again this object for Chrome for unknown reason
  62771. this._babylonGamepads[i].browserGamepad = gamepads[i];
  62772. if (!this._babylonGamepads[i].isConnected) {
  62773. this._babylonGamepads[i]._isConnected = true;
  62774. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  62775. }
  62776. }
  62777. }
  62778. }
  62779. };
  62780. return GamepadManager;
  62781. }());
  62782. BABYLON.GamepadManager = GamepadManager;
  62783. })(BABYLON || (BABYLON = {}));
  62784. //# sourceMappingURL=babylon.gamepadManager.js.map
  62785. var BABYLON;
  62786. (function (BABYLON) {
  62787. var StickValues = /** @class */ (function () {
  62788. function StickValues(x, y) {
  62789. this.x = x;
  62790. this.y = y;
  62791. }
  62792. return StickValues;
  62793. }());
  62794. BABYLON.StickValues = StickValues;
  62795. var Gamepad = /** @class */ (function () {
  62796. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  62797. if (leftStickX === void 0) { leftStickX = 0; }
  62798. if (leftStickY === void 0) { leftStickY = 1; }
  62799. if (rightStickX === void 0) { rightStickX = 2; }
  62800. if (rightStickY === void 0) { rightStickY = 3; }
  62801. this.id = id;
  62802. this.index = index;
  62803. this.browserGamepad = browserGamepad;
  62804. this._isConnected = true;
  62805. this._invertLeftStickY = false;
  62806. this.type = Gamepad.GAMEPAD;
  62807. this._leftStickAxisX = leftStickX;
  62808. this._leftStickAxisY = leftStickY;
  62809. this._rightStickAxisX = rightStickX;
  62810. this._rightStickAxisY = rightStickY;
  62811. if (this.browserGamepad.axes.length >= 2) {
  62812. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62813. }
  62814. if (this.browserGamepad.axes.length >= 4) {
  62815. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62816. }
  62817. }
  62818. Object.defineProperty(Gamepad.prototype, "isConnected", {
  62819. get: function () {
  62820. return this._isConnected;
  62821. },
  62822. enumerable: true,
  62823. configurable: true
  62824. });
  62825. Gamepad.prototype.onleftstickchanged = function (callback) {
  62826. this._onleftstickchanged = callback;
  62827. };
  62828. Gamepad.prototype.onrightstickchanged = function (callback) {
  62829. this._onrightstickchanged = callback;
  62830. };
  62831. Object.defineProperty(Gamepad.prototype, "leftStick", {
  62832. get: function () {
  62833. return this._leftStick;
  62834. },
  62835. set: function (newValues) {
  62836. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  62837. this._onleftstickchanged(newValues);
  62838. }
  62839. this._leftStick = newValues;
  62840. },
  62841. enumerable: true,
  62842. configurable: true
  62843. });
  62844. Object.defineProperty(Gamepad.prototype, "rightStick", {
  62845. get: function () {
  62846. return this._rightStick;
  62847. },
  62848. set: function (newValues) {
  62849. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  62850. this._onrightstickchanged(newValues);
  62851. }
  62852. this._rightStick = newValues;
  62853. },
  62854. enumerable: true,
  62855. configurable: true
  62856. });
  62857. Gamepad.prototype.update = function () {
  62858. if (this._leftStick) {
  62859. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62860. if (this._invertLeftStickY) {
  62861. this.leftStick.y *= -1;
  62862. }
  62863. }
  62864. if (this._rightStick) {
  62865. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62866. }
  62867. };
  62868. Gamepad.prototype.dispose = function () {
  62869. };
  62870. Gamepad.GAMEPAD = 0;
  62871. Gamepad.GENERIC = 1;
  62872. Gamepad.XBOX = 2;
  62873. Gamepad.POSE_ENABLED = 3;
  62874. return Gamepad;
  62875. }());
  62876. BABYLON.Gamepad = Gamepad;
  62877. var GenericPad = /** @class */ (function (_super) {
  62878. __extends(GenericPad, _super);
  62879. function GenericPad(id, index, browserGamepad) {
  62880. var _this = _super.call(this, id, index, browserGamepad) || this;
  62881. _this.onButtonDownObservable = new BABYLON.Observable();
  62882. _this.onButtonUpObservable = new BABYLON.Observable();
  62883. _this.type = Gamepad.GENERIC;
  62884. _this._buttons = new Array(browserGamepad.buttons.length);
  62885. return _this;
  62886. }
  62887. GenericPad.prototype.onbuttondown = function (callback) {
  62888. this._onbuttondown = callback;
  62889. };
  62890. GenericPad.prototype.onbuttonup = function (callback) {
  62891. this._onbuttonup = callback;
  62892. };
  62893. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  62894. if (newValue !== currentValue) {
  62895. if (newValue === 1) {
  62896. if (this._onbuttondown) {
  62897. this._onbuttondown(buttonIndex);
  62898. }
  62899. this.onButtonDownObservable.notifyObservers(buttonIndex);
  62900. }
  62901. if (newValue === 0) {
  62902. if (this._onbuttonup) {
  62903. this._onbuttonup(buttonIndex);
  62904. }
  62905. this.onButtonUpObservable.notifyObservers(buttonIndex);
  62906. }
  62907. }
  62908. return newValue;
  62909. };
  62910. GenericPad.prototype.update = function () {
  62911. _super.prototype.update.call(this);
  62912. for (var index = 0; index < this._buttons.length; index++) {
  62913. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  62914. }
  62915. };
  62916. GenericPad.prototype.dispose = function () {
  62917. _super.prototype.dispose.call(this);
  62918. this.onButtonDownObservable.clear();
  62919. this.onButtonUpObservable.clear();
  62920. };
  62921. return GenericPad;
  62922. }(Gamepad));
  62923. BABYLON.GenericPad = GenericPad;
  62924. })(BABYLON || (BABYLON = {}));
  62925. //# sourceMappingURL=babylon.gamepad.js.map
  62926. var BABYLON;
  62927. (function (BABYLON) {
  62928. var Xbox360Button;
  62929. (function (Xbox360Button) {
  62930. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  62931. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  62932. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  62933. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  62934. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  62935. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  62936. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  62937. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  62938. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  62939. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  62940. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  62941. var Xbox360Dpad;
  62942. (function (Xbox360Dpad) {
  62943. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  62944. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  62945. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  62946. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  62947. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  62948. var Xbox360Pad = /** @class */ (function (_super) {
  62949. __extends(Xbox360Pad, _super);
  62950. function Xbox360Pad(id, index, gamepad, xboxOne) {
  62951. if (xboxOne === void 0) { xboxOne = false; }
  62952. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  62953. _this._leftTrigger = 0;
  62954. _this._rightTrigger = 0;
  62955. _this.onButtonDownObservable = new BABYLON.Observable();
  62956. _this.onButtonUpObservable = new BABYLON.Observable();
  62957. _this.onPadDownObservable = new BABYLON.Observable();
  62958. _this.onPadUpObservable = new BABYLON.Observable();
  62959. _this._buttonA = 0;
  62960. _this._buttonB = 0;
  62961. _this._buttonX = 0;
  62962. _this._buttonY = 0;
  62963. _this._buttonBack = 0;
  62964. _this._buttonStart = 0;
  62965. _this._buttonLB = 0;
  62966. _this._buttonRB = 0;
  62967. _this._buttonLeftStick = 0;
  62968. _this._buttonRightStick = 0;
  62969. _this._dPadUp = 0;
  62970. _this._dPadDown = 0;
  62971. _this._dPadLeft = 0;
  62972. _this._dPadRight = 0;
  62973. _this._isXboxOnePad = false;
  62974. _this.type = BABYLON.Gamepad.XBOX;
  62975. _this._isXboxOnePad = xboxOne;
  62976. return _this;
  62977. }
  62978. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  62979. this._onlefttriggerchanged = callback;
  62980. };
  62981. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  62982. this._onrighttriggerchanged = callback;
  62983. };
  62984. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  62985. get: function () {
  62986. return this._leftTrigger;
  62987. },
  62988. set: function (newValue) {
  62989. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  62990. this._onlefttriggerchanged(newValue);
  62991. }
  62992. this._leftTrigger = newValue;
  62993. },
  62994. enumerable: true,
  62995. configurable: true
  62996. });
  62997. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  62998. get: function () {
  62999. return this._rightTrigger;
  63000. },
  63001. set: function (newValue) {
  63002. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  63003. this._onrighttriggerchanged(newValue);
  63004. }
  63005. this._rightTrigger = newValue;
  63006. },
  63007. enumerable: true,
  63008. configurable: true
  63009. });
  63010. Xbox360Pad.prototype.onbuttondown = function (callback) {
  63011. this._onbuttondown = callback;
  63012. };
  63013. Xbox360Pad.prototype.onbuttonup = function (callback) {
  63014. this._onbuttonup = callback;
  63015. };
  63016. Xbox360Pad.prototype.ondpaddown = function (callback) {
  63017. this._ondpaddown = callback;
  63018. };
  63019. Xbox360Pad.prototype.ondpadup = function (callback) {
  63020. this._ondpadup = callback;
  63021. };
  63022. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  63023. if (newValue !== currentValue) {
  63024. if (newValue === 1) {
  63025. if (this._onbuttondown) {
  63026. this._onbuttondown(buttonType);
  63027. }
  63028. this.onButtonDownObservable.notifyObservers(buttonType);
  63029. }
  63030. if (newValue === 0) {
  63031. if (this._onbuttonup) {
  63032. this._onbuttonup(buttonType);
  63033. }
  63034. this.onButtonUpObservable.notifyObservers(buttonType);
  63035. }
  63036. }
  63037. return newValue;
  63038. };
  63039. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  63040. if (newValue !== currentValue) {
  63041. if (newValue === 1) {
  63042. if (this._ondpaddown) {
  63043. this._ondpaddown(buttonType);
  63044. }
  63045. this.onPadDownObservable.notifyObservers(buttonType);
  63046. }
  63047. if (newValue === 0) {
  63048. if (this._ondpadup) {
  63049. this._ondpadup(buttonType);
  63050. }
  63051. this.onPadUpObservable.notifyObservers(buttonType);
  63052. }
  63053. }
  63054. return newValue;
  63055. };
  63056. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  63057. get: function () {
  63058. return this._buttonA;
  63059. },
  63060. set: function (value) {
  63061. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  63062. },
  63063. enumerable: true,
  63064. configurable: true
  63065. });
  63066. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  63067. get: function () {
  63068. return this._buttonB;
  63069. },
  63070. set: function (value) {
  63071. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  63072. },
  63073. enumerable: true,
  63074. configurable: true
  63075. });
  63076. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  63077. get: function () {
  63078. return this._buttonX;
  63079. },
  63080. set: function (value) {
  63081. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  63082. },
  63083. enumerable: true,
  63084. configurable: true
  63085. });
  63086. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  63087. get: function () {
  63088. return this._buttonY;
  63089. },
  63090. set: function (value) {
  63091. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  63092. },
  63093. enumerable: true,
  63094. configurable: true
  63095. });
  63096. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  63097. get: function () {
  63098. return this._buttonStart;
  63099. },
  63100. set: function (value) {
  63101. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  63102. },
  63103. enumerable: true,
  63104. configurable: true
  63105. });
  63106. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  63107. get: function () {
  63108. return this._buttonBack;
  63109. },
  63110. set: function (value) {
  63111. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  63112. },
  63113. enumerable: true,
  63114. configurable: true
  63115. });
  63116. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  63117. get: function () {
  63118. return this._buttonLB;
  63119. },
  63120. set: function (value) {
  63121. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  63122. },
  63123. enumerable: true,
  63124. configurable: true
  63125. });
  63126. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  63127. get: function () {
  63128. return this._buttonRB;
  63129. },
  63130. set: function (value) {
  63131. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  63132. },
  63133. enumerable: true,
  63134. configurable: true
  63135. });
  63136. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  63137. get: function () {
  63138. return this._buttonLeftStick;
  63139. },
  63140. set: function (value) {
  63141. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  63142. },
  63143. enumerable: true,
  63144. configurable: true
  63145. });
  63146. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  63147. get: function () {
  63148. return this._buttonRightStick;
  63149. },
  63150. set: function (value) {
  63151. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  63152. },
  63153. enumerable: true,
  63154. configurable: true
  63155. });
  63156. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  63157. get: function () {
  63158. return this._dPadUp;
  63159. },
  63160. set: function (value) {
  63161. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  63162. },
  63163. enumerable: true,
  63164. configurable: true
  63165. });
  63166. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  63167. get: function () {
  63168. return this._dPadDown;
  63169. },
  63170. set: function (value) {
  63171. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  63172. },
  63173. enumerable: true,
  63174. configurable: true
  63175. });
  63176. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  63177. get: function () {
  63178. return this._dPadLeft;
  63179. },
  63180. set: function (value) {
  63181. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  63182. },
  63183. enumerable: true,
  63184. configurable: true
  63185. });
  63186. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  63187. get: function () {
  63188. return this._dPadRight;
  63189. },
  63190. set: function (value) {
  63191. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  63192. },
  63193. enumerable: true,
  63194. configurable: true
  63195. });
  63196. Xbox360Pad.prototype.update = function () {
  63197. _super.prototype.update.call(this);
  63198. if (this._isXboxOnePad) {
  63199. this.buttonA = this.browserGamepad.buttons[0].value;
  63200. this.buttonB = this.browserGamepad.buttons[1].value;
  63201. this.buttonX = this.browserGamepad.buttons[2].value;
  63202. this.buttonY = this.browserGamepad.buttons[3].value;
  63203. this.buttonLB = this.browserGamepad.buttons[4].value;
  63204. this.buttonRB = this.browserGamepad.buttons[5].value;
  63205. this.leftTrigger = this.browserGamepad.axes[2];
  63206. this.rightTrigger = this.browserGamepad.axes[5];
  63207. this.buttonBack = this.browserGamepad.buttons[9].value;
  63208. this.buttonStart = this.browserGamepad.buttons[8].value;
  63209. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  63210. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  63211. this.dPadUp = this.browserGamepad.buttons[11].value;
  63212. this.dPadDown = this.browserGamepad.buttons[12].value;
  63213. this.dPadLeft = this.browserGamepad.buttons[13].value;
  63214. this.dPadRight = this.browserGamepad.buttons[14].value;
  63215. }
  63216. else {
  63217. this.buttonA = this.browserGamepad.buttons[0].value;
  63218. this.buttonB = this.browserGamepad.buttons[1].value;
  63219. this.buttonX = this.browserGamepad.buttons[2].value;
  63220. this.buttonY = this.browserGamepad.buttons[3].value;
  63221. this.buttonLB = this.browserGamepad.buttons[4].value;
  63222. this.buttonRB = this.browserGamepad.buttons[5].value;
  63223. this.leftTrigger = this.browserGamepad.buttons[6].value;
  63224. this.rightTrigger = this.browserGamepad.buttons[7].value;
  63225. this.buttonBack = this.browserGamepad.buttons[8].value;
  63226. this.buttonStart = this.browserGamepad.buttons[9].value;
  63227. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  63228. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  63229. this.dPadUp = this.browserGamepad.buttons[12].value;
  63230. this.dPadDown = this.browserGamepad.buttons[13].value;
  63231. this.dPadLeft = this.browserGamepad.buttons[14].value;
  63232. this.dPadRight = this.browserGamepad.buttons[15].value;
  63233. }
  63234. };
  63235. Xbox360Pad.prototype.dispose = function () {
  63236. _super.prototype.dispose.call(this);
  63237. this.onButtonDownObservable.clear();
  63238. this.onButtonUpObservable.clear();
  63239. this.onPadDownObservable.clear();
  63240. this.onPadUpObservable.clear();
  63241. };
  63242. return Xbox360Pad;
  63243. }(BABYLON.Gamepad));
  63244. BABYLON.Xbox360Pad = Xbox360Pad;
  63245. })(BABYLON || (BABYLON = {}));
  63246. //# sourceMappingURL=babylon.xboxGamepad.js.map
  63247. var BABYLON;
  63248. (function (BABYLON) {
  63249. var PoseEnabledControllerType;
  63250. (function (PoseEnabledControllerType) {
  63251. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  63252. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  63253. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  63254. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  63255. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  63256. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  63257. var PoseEnabledControllerHelper = /** @class */ (function () {
  63258. function PoseEnabledControllerHelper() {
  63259. }
  63260. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  63261. // Oculus Touch
  63262. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  63263. return new BABYLON.OculusTouchController(vrGamepad);
  63264. }
  63265. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  63266. return new BABYLON.WindowsMotionController(vrGamepad);
  63267. }
  63268. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  63269. return new BABYLON.ViveController(vrGamepad);
  63270. }
  63271. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  63272. return new BABYLON.GearVRController(vrGamepad);
  63273. }
  63274. else {
  63275. return new BABYLON.GenericController(vrGamepad);
  63276. }
  63277. };
  63278. return PoseEnabledControllerHelper;
  63279. }());
  63280. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  63281. var PoseEnabledController = /** @class */ (function (_super) {
  63282. __extends(PoseEnabledController, _super);
  63283. function PoseEnabledController(browserGamepad) {
  63284. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  63285. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  63286. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  63287. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  63288. // Represents device position and rotation in babylon space
  63289. _this.devicePosition = BABYLON.Vector3.Zero();
  63290. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  63291. _this.deviceScaleFactor = 1;
  63292. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  63293. _this._deviceToWorld = BABYLON.Matrix.Identity();
  63294. _this._workingMatrix = BABYLON.Matrix.Identity();
  63295. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  63296. _this.controllerType = PoseEnabledControllerType.GENERIC;
  63297. _this.position = BABYLON.Vector3.Zero();
  63298. _this.rotationQuaternion = new BABYLON.Quaternion();
  63299. _this._calculatedPosition = BABYLON.Vector3.Zero();
  63300. _this._calculatedRotation = new BABYLON.Quaternion();
  63301. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  63302. return _this;
  63303. }
  63304. PoseEnabledController.prototype.update = function () {
  63305. _super.prototype.update.call(this);
  63306. var pose = this.browserGamepad.pose;
  63307. this.updateFromDevice(pose);
  63308. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  63309. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  63310. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  63311. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  63312. if (this._mesh) {
  63313. this._mesh.position.copyFrom(this.devicePosition);
  63314. if (this._mesh.rotationQuaternion) {
  63315. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63316. }
  63317. }
  63318. };
  63319. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  63320. if (poseData) {
  63321. this.rawPose = poseData;
  63322. if (poseData.position) {
  63323. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  63324. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  63325. this._deviceRoomPosition.z *= -1;
  63326. }
  63327. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  63328. this._calculatedPosition.addInPlace(this.position);
  63329. }
  63330. var pose = this.rawPose;
  63331. if (poseData.orientation && pose.orientation) {
  63332. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  63333. if (this._mesh) {
  63334. if (this._mesh.getScene().useRightHandedSystem) {
  63335. this._deviceRoomRotationQuaternion.z *= -1;
  63336. this._deviceRoomRotationQuaternion.w *= -1;
  63337. }
  63338. else {
  63339. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  63340. }
  63341. }
  63342. // if the camera is set, rotate to the camera's rotation
  63343. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  63344. }
  63345. }
  63346. };
  63347. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  63348. if (this._mesh) {
  63349. this._mesh.parent = null;
  63350. }
  63351. this._mesh = mesh;
  63352. if (this._poseControlledCamera) {
  63353. this._mesh.parent = this._poseControlledCamera;
  63354. }
  63355. if (!this._mesh.rotationQuaternion) {
  63356. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  63357. }
  63358. };
  63359. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  63360. this._poseControlledCamera = camera;
  63361. if (this._mesh) {
  63362. this._mesh.parent = this._poseControlledCamera;
  63363. }
  63364. };
  63365. PoseEnabledController.prototype.dispose = function () {
  63366. if (this._mesh) {
  63367. this._mesh.dispose();
  63368. }
  63369. this._mesh = null;
  63370. _super.prototype.dispose.call(this);
  63371. };
  63372. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  63373. get: function () {
  63374. return this._mesh;
  63375. },
  63376. enumerable: true,
  63377. configurable: true
  63378. });
  63379. PoseEnabledController.prototype.getForwardRay = function (length) {
  63380. if (length === void 0) { length = 100; }
  63381. if (!this.mesh) {
  63382. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  63383. }
  63384. var m = this.mesh.getWorldMatrix();
  63385. var origin = m.getTranslation();
  63386. var forward = new BABYLON.Vector3(0, 0, -1);
  63387. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63388. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63389. return new BABYLON.Ray(origin, direction, length);
  63390. };
  63391. return PoseEnabledController;
  63392. }(BABYLON.Gamepad));
  63393. BABYLON.PoseEnabledController = PoseEnabledController;
  63394. })(BABYLON || (BABYLON = {}));
  63395. //# sourceMappingURL=babylon.poseEnabledController.js.map
  63396. var BABYLON;
  63397. (function (BABYLON) {
  63398. var WebVRController = /** @class */ (function (_super) {
  63399. __extends(WebVRController, _super);
  63400. function WebVRController(vrGamepad) {
  63401. var _this = _super.call(this, vrGamepad) || this;
  63402. // Observables
  63403. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  63404. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  63405. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  63406. _this.onPadStateChangedObservable = new BABYLON.Observable();
  63407. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  63408. _this.pad = { x: 0, y: 0 };
  63409. // avoid GC, store state in a tmp object
  63410. _this._changes = {
  63411. pressChanged: false,
  63412. touchChanged: false,
  63413. valueChanged: false,
  63414. changed: false
  63415. };
  63416. _this._buttons = new Array(vrGamepad.buttons.length);
  63417. _this.hand = vrGamepad.hand;
  63418. return _this;
  63419. }
  63420. WebVRController.prototype.onButtonStateChange = function (callback) {
  63421. this._onButtonStateChange = callback;
  63422. };
  63423. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  63424. get: function () {
  63425. return this._defaultModel;
  63426. },
  63427. enumerable: true,
  63428. configurable: true
  63429. });
  63430. WebVRController.prototype.update = function () {
  63431. _super.prototype.update.call(this);
  63432. for (var index = 0; index < this._buttons.length; index++) {
  63433. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  63434. }
  63435. ;
  63436. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  63437. this.pad.x = this.leftStick.x;
  63438. this.pad.y = this.leftStick.y;
  63439. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  63440. }
  63441. };
  63442. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  63443. if (!newState) {
  63444. newState = {
  63445. pressed: false,
  63446. touched: false,
  63447. value: 0
  63448. };
  63449. }
  63450. if (!currentState) {
  63451. this._buttons[buttonIndex] = {
  63452. pressed: newState.pressed,
  63453. touched: newState.touched,
  63454. value: newState.value
  63455. };
  63456. return;
  63457. }
  63458. this._checkChanges(newState, currentState);
  63459. if (this._changes.changed) {
  63460. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  63461. this.handleButtonChange(buttonIndex, newState, this._changes);
  63462. }
  63463. this._buttons[buttonIndex].pressed = newState.pressed;
  63464. this._buttons[buttonIndex].touched = newState.touched;
  63465. // oculus triggers are never 0, thou not touched.
  63466. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  63467. };
  63468. WebVRController.prototype._checkChanges = function (newState, currentState) {
  63469. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  63470. this._changes.touchChanged = newState.touched !== currentState.touched;
  63471. this._changes.valueChanged = newState.value !== currentState.value;
  63472. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  63473. return this._changes;
  63474. };
  63475. WebVRController.prototype.dispose = function () {
  63476. _super.prototype.dispose.call(this);
  63477. this.onTriggerStateChangedObservable.clear();
  63478. this.onMainButtonStateChangedObservable.clear();
  63479. this.onSecondaryButtonStateChangedObservable.clear();
  63480. this.onPadStateChangedObservable.clear();
  63481. this.onPadValuesChangedObservable.clear();
  63482. };
  63483. return WebVRController;
  63484. }(BABYLON.PoseEnabledController));
  63485. BABYLON.WebVRController = WebVRController;
  63486. })(BABYLON || (BABYLON = {}));
  63487. //# sourceMappingURL=babylon.webVRController.js.map
  63488. var BABYLON;
  63489. (function (BABYLON) {
  63490. var OculusTouchController = /** @class */ (function (_super) {
  63491. __extends(OculusTouchController, _super);
  63492. function OculusTouchController(vrGamepad) {
  63493. var _this = _super.call(this, vrGamepad) || this;
  63494. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  63495. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  63496. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  63497. return _this;
  63498. }
  63499. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63500. var _this = this;
  63501. var meshName;
  63502. // Hand
  63503. if (this.hand === 'left') {
  63504. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  63505. }
  63506. else {
  63507. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  63508. }
  63509. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  63510. /*
  63511. Parent Mesh name: oculus_touch_left
  63512. - body
  63513. - trigger
  63514. - thumbstick
  63515. - grip
  63516. - button_y
  63517. - button_x
  63518. - button_enter
  63519. */
  63520. _this._defaultModel = newMeshes[1];
  63521. _this.attachToMesh(_this._defaultModel);
  63522. if (meshLoaded) {
  63523. meshLoaded(_this._defaultModel);
  63524. }
  63525. });
  63526. };
  63527. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  63528. // helper getters for left and right hand.
  63529. get: function () {
  63530. if (this.hand === 'right') {
  63531. return this.onMainButtonStateChangedObservable;
  63532. }
  63533. else {
  63534. throw new Error('No A button on left hand');
  63535. }
  63536. },
  63537. enumerable: true,
  63538. configurable: true
  63539. });
  63540. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  63541. get: function () {
  63542. if (this.hand === 'right') {
  63543. return this.onSecondaryButtonStateChangedObservable;
  63544. }
  63545. else {
  63546. throw new Error('No B button on left hand');
  63547. }
  63548. },
  63549. enumerable: true,
  63550. configurable: true
  63551. });
  63552. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  63553. get: function () {
  63554. if (this.hand === 'left') {
  63555. return this.onMainButtonStateChangedObservable;
  63556. }
  63557. else {
  63558. throw new Error('No X button on right hand');
  63559. }
  63560. },
  63561. enumerable: true,
  63562. configurable: true
  63563. });
  63564. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  63565. get: function () {
  63566. if (this.hand === 'left') {
  63567. return this.onSecondaryButtonStateChangedObservable;
  63568. }
  63569. else {
  63570. throw new Error('No Y button on right hand');
  63571. }
  63572. },
  63573. enumerable: true,
  63574. configurable: true
  63575. });
  63576. /*
  63577. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  63578. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  63579. 2) secondary trigger (same)
  63580. 3) A (right) X (left), touch, pressed = value
  63581. 4) B / Y
  63582. 5) thumb rest
  63583. */
  63584. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63585. var notifyObject = state; //{ state: state, changes: changes };
  63586. var triggerDirection = this.hand === 'right' ? -1 : 1;
  63587. switch (buttonIdx) {
  63588. case 0:
  63589. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63590. return;
  63591. case 1:// index trigger
  63592. if (this._defaultModel) {
  63593. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  63594. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  63595. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  63596. }
  63597. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63598. return;
  63599. case 2:// secondary trigger
  63600. if (this._defaultModel) {
  63601. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  63602. }
  63603. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  63604. return;
  63605. case 3:
  63606. if (this._defaultModel) {
  63607. if (notifyObject.pressed) {
  63608. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  63609. }
  63610. else {
  63611. (this._defaultModel.getChildren()[1]).position.y = 0;
  63612. }
  63613. }
  63614. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63615. return;
  63616. case 4:
  63617. if (this._defaultModel) {
  63618. if (notifyObject.pressed) {
  63619. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63620. }
  63621. else {
  63622. (this._defaultModel.getChildren()[2]).position.y = 0;
  63623. }
  63624. }
  63625. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63626. return;
  63627. case 5:
  63628. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  63629. return;
  63630. }
  63631. };
  63632. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  63633. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  63634. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  63635. return OculusTouchController;
  63636. }(BABYLON.WebVRController));
  63637. BABYLON.OculusTouchController = OculusTouchController;
  63638. })(BABYLON || (BABYLON = {}));
  63639. //# sourceMappingURL=babylon.oculusTouchController.js.map
  63640. var BABYLON;
  63641. (function (BABYLON) {
  63642. var ViveController = /** @class */ (function (_super) {
  63643. __extends(ViveController, _super);
  63644. function ViveController(vrGamepad) {
  63645. var _this = _super.call(this, vrGamepad) || this;
  63646. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  63647. _this._invertLeftStickY = true;
  63648. return _this;
  63649. }
  63650. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63651. var _this = this;
  63652. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  63653. /*
  63654. Parent Mesh name: ViveWand
  63655. - body
  63656. - r_gripper
  63657. - l_gripper
  63658. - menu_button
  63659. - system_button
  63660. - trackpad
  63661. - trigger
  63662. - LED
  63663. */
  63664. _this._defaultModel = newMeshes[1];
  63665. _this.attachToMesh(_this._defaultModel);
  63666. if (meshLoaded) {
  63667. meshLoaded(_this._defaultModel);
  63668. }
  63669. });
  63670. };
  63671. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  63672. get: function () {
  63673. return this.onMainButtonStateChangedObservable;
  63674. },
  63675. enumerable: true,
  63676. configurable: true
  63677. });
  63678. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  63679. get: function () {
  63680. return this.onMainButtonStateChangedObservable;
  63681. },
  63682. enumerable: true,
  63683. configurable: true
  63684. });
  63685. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  63686. get: function () {
  63687. return this.onSecondaryButtonStateChangedObservable;
  63688. },
  63689. enumerable: true,
  63690. configurable: true
  63691. });
  63692. /**
  63693. * Vive mapping:
  63694. * 0: touchpad
  63695. * 1: trigger
  63696. * 2: left AND right buttons
  63697. * 3: menu button
  63698. */
  63699. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63700. var notifyObject = state; //{ state: state, changes: changes };
  63701. switch (buttonIdx) {
  63702. case 0:
  63703. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63704. return;
  63705. case 1:// index trigger
  63706. if (this._defaultModel) {
  63707. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  63708. }
  63709. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63710. return;
  63711. case 2:// left AND right button
  63712. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63713. return;
  63714. case 3:
  63715. if (this._defaultModel) {
  63716. if (notifyObject.pressed) {
  63717. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63718. }
  63719. else {
  63720. (this._defaultModel.getChildren()[2]).position.y = 0;
  63721. }
  63722. }
  63723. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63724. return;
  63725. }
  63726. };
  63727. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  63728. ViveController.MODEL_FILENAME = 'wand.babylon';
  63729. return ViveController;
  63730. }(BABYLON.WebVRController));
  63731. BABYLON.ViveController = ViveController;
  63732. })(BABYLON || (BABYLON = {}));
  63733. //# sourceMappingURL=babylon.viveController.js.map
  63734. var BABYLON;
  63735. (function (BABYLON) {
  63736. var GenericController = /** @class */ (function (_super) {
  63737. __extends(GenericController, _super);
  63738. function GenericController(vrGamepad) {
  63739. return _super.call(this, vrGamepad) || this;
  63740. }
  63741. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63742. var _this = this;
  63743. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  63744. _this._defaultModel = newMeshes[1];
  63745. _this.attachToMesh(_this._defaultModel);
  63746. if (meshLoaded) {
  63747. meshLoaded(_this._defaultModel);
  63748. }
  63749. });
  63750. };
  63751. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63752. console.log("Button id: " + buttonIdx + "state: ");
  63753. console.dir(state);
  63754. };
  63755. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  63756. GenericController.MODEL_FILENAME = 'generic.babylon';
  63757. return GenericController;
  63758. }(BABYLON.WebVRController));
  63759. BABYLON.GenericController = GenericController;
  63760. })(BABYLON || (BABYLON = {}));
  63761. //# sourceMappingURL=babylon.genericController.js.map
  63762. var BABYLON;
  63763. (function (BABYLON) {
  63764. var LoadedMeshInfo = /** @class */ (function () {
  63765. function LoadedMeshInfo() {
  63766. this.buttonMeshes = {};
  63767. this.axisMeshes = {};
  63768. }
  63769. return LoadedMeshInfo;
  63770. }());
  63771. var WindowsMotionController = /** @class */ (function (_super) {
  63772. __extends(WindowsMotionController, _super);
  63773. function WindowsMotionController(vrGamepad) {
  63774. var _this = _super.call(this, vrGamepad) || this;
  63775. _this._mapping = {
  63776. // Semantic button names
  63777. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  63778. // A mapping of the button name to glTF model node name
  63779. // that should be transformed by button value.
  63780. buttonMeshNames: {
  63781. 'trigger': 'SELECT',
  63782. 'menu': 'MENU',
  63783. 'grip': 'GRASP',
  63784. 'thumbstick': 'THUMBSTICK_PRESS',
  63785. 'trackpad': 'TOUCHPAD_PRESS'
  63786. },
  63787. // This mapping is used to translate from the Motion Controller to Babylon semantics
  63788. buttonObservableNames: {
  63789. 'trigger': 'onTriggerStateChangedObservable',
  63790. 'menu': 'onSecondaryButtonStateChangedObservable',
  63791. 'grip': 'onMainButtonStateChangedObservable',
  63792. 'thumbstick': 'onPadStateChangedObservable',
  63793. 'trackpad': 'onTrackpadChangedObservable'
  63794. },
  63795. // A mapping of the axis name to glTF model node name
  63796. // that should be transformed by axis value.
  63797. // This array mirrors the browserGamepad.axes array, such that
  63798. // the mesh corresponding to axis 0 is in this array index 0.
  63799. axisMeshNames: [
  63800. 'THUMBSTICK_X',
  63801. 'THUMBSTICK_Y',
  63802. 'TOUCHPAD_TOUCH_X',
  63803. 'TOUCHPAD_TOUCH_Y'
  63804. ],
  63805. pointingPoseMeshName: 'POINTING_POSE'
  63806. };
  63807. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  63808. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  63809. _this.trackpad = { x: 0, y: 0 };
  63810. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  63811. _this._loadedMeshInfo = null;
  63812. return _this;
  63813. }
  63814. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  63815. get: function () {
  63816. return this.onTriggerStateChangedObservable;
  63817. },
  63818. enumerable: true,
  63819. configurable: true
  63820. });
  63821. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  63822. get: function () {
  63823. return this.onSecondaryButtonStateChangedObservable;
  63824. },
  63825. enumerable: true,
  63826. configurable: true
  63827. });
  63828. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  63829. get: function () {
  63830. return this.onMainButtonStateChangedObservable;
  63831. },
  63832. enumerable: true,
  63833. configurable: true
  63834. });
  63835. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  63836. get: function () {
  63837. return this.onPadStateChangedObservable;
  63838. },
  63839. enumerable: true,
  63840. configurable: true
  63841. });
  63842. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  63843. get: function () {
  63844. return this.onTrackpadChangedObservable;
  63845. },
  63846. enumerable: true,
  63847. configurable: true
  63848. });
  63849. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  63850. get: function () {
  63851. return this.onTrackpadValuesChangedObservable;
  63852. },
  63853. enumerable: true,
  63854. configurable: true
  63855. });
  63856. /**
  63857. * Called once per frame by the engine.
  63858. */
  63859. WindowsMotionController.prototype.update = function () {
  63860. _super.prototype.update.call(this);
  63861. // Only need to animate axes if there is a loaded mesh
  63862. if (this._loadedMeshInfo) {
  63863. if (this.browserGamepad.axes) {
  63864. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  63865. this.trackpad.x = this.browserGamepad["axes"][2];
  63866. this.trackpad.y = this.browserGamepad["axes"][3];
  63867. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  63868. }
  63869. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  63870. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  63871. }
  63872. }
  63873. }
  63874. };
  63875. /**
  63876. * Called once for each button that changed state since the last frame
  63877. * @param buttonIdx Which button index changed
  63878. * @param state New state of the button
  63879. * @param changes Which properties on the state changed since last frame
  63880. */
  63881. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63882. var buttonName = this._mapping.buttons[buttonIdx];
  63883. if (!buttonName) {
  63884. return;
  63885. }
  63886. // Only emit events for buttons that we know how to map from index to name
  63887. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  63888. if (observable) {
  63889. observable.notifyObservers(state);
  63890. }
  63891. this.lerpButtonTransform(buttonName, state.value);
  63892. };
  63893. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  63894. // If there is no loaded mesh, there is nothing to transform.
  63895. if (!this._loadedMeshInfo) {
  63896. return;
  63897. }
  63898. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  63899. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63900. return;
  63901. }
  63902. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  63903. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  63904. };
  63905. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  63906. if (!this._loadedMeshInfo) {
  63907. return;
  63908. }
  63909. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  63910. if (!meshInfo) {
  63911. return;
  63912. }
  63913. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63914. return;
  63915. }
  63916. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  63917. var lerpValue = axisValue * 0.5 + 0.5;
  63918. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  63919. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  63920. };
  63921. /**
  63922. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  63923. * @param scene scene in which to add meshes
  63924. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  63925. */
  63926. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  63927. var _this = this;
  63928. if (forceDefault === void 0) { forceDefault = false; }
  63929. var path;
  63930. var filename;
  63931. // Checking if GLB loader is present
  63932. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  63933. // Determine the device specific folder based on the ID suffix
  63934. var device = 'default';
  63935. if (this.id && !forceDefault) {
  63936. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  63937. device = ((match && match[0]) || device);
  63938. }
  63939. // Hand
  63940. if (this.hand === 'left') {
  63941. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  63942. }
  63943. else {
  63944. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  63945. }
  63946. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  63947. }
  63948. else {
  63949. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  63950. path = BABYLON.GenericController.MODEL_BASE_URL;
  63951. filename = BABYLON.GenericController.MODEL_FILENAME;
  63952. }
  63953. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  63954. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  63955. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  63956. if (!_this._loadedMeshInfo) {
  63957. return;
  63958. }
  63959. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  63960. _this.attachToMesh(_this._defaultModel);
  63961. if (meshLoaded) {
  63962. meshLoaded(_this._defaultModel);
  63963. }
  63964. }, null, function (scene, message) {
  63965. BABYLON.Tools.Log(message);
  63966. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  63967. if (!forceDefault) {
  63968. _this.initControllerMesh(scene, meshLoaded, true);
  63969. }
  63970. });
  63971. };
  63972. /**
  63973. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  63974. * can be transformed by button presses and axes values, based on this._mapping.
  63975. *
  63976. * @param scene scene in which the meshes exist
  63977. * @param meshes list of meshes that make up the controller model to process
  63978. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  63979. */
  63980. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  63981. var loadedMeshInfo = null;
  63982. // Create a new mesh to contain the glTF hierarchy
  63983. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  63984. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  63985. var childMesh = null;
  63986. for (var i = 0; i < meshes.length; i++) {
  63987. var mesh = meshes[i];
  63988. if (!mesh.parent) {
  63989. // Exclude controller meshes from picking results
  63990. mesh.isPickable = false;
  63991. // Handle root node, attach to the new parentMesh
  63992. childMesh = mesh;
  63993. break;
  63994. }
  63995. }
  63996. if (childMesh) {
  63997. childMesh.setParent(parentMesh);
  63998. // Create our mesh info. Note that this method will always return non-null.
  63999. loadedMeshInfo = this.createMeshInfo(parentMesh);
  64000. }
  64001. else {
  64002. BABYLON.Tools.Warn('Could not find root node in model file.');
  64003. }
  64004. return loadedMeshInfo;
  64005. };
  64006. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  64007. var loadedMeshInfo = new LoadedMeshInfo();
  64008. var i;
  64009. loadedMeshInfo.rootNode = rootNode;
  64010. // Reset the caches
  64011. loadedMeshInfo.buttonMeshes = {};
  64012. loadedMeshInfo.axisMeshes = {};
  64013. // Button Meshes
  64014. for (i = 0; i < this._mapping.buttons.length; i++) {
  64015. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  64016. if (!buttonMeshName) {
  64017. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  64018. continue;
  64019. }
  64020. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  64021. if (!buttonMesh) {
  64022. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  64023. continue;
  64024. }
  64025. var buttonMeshInfo = {
  64026. index: i,
  64027. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  64028. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  64029. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  64030. };
  64031. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  64032. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  64033. }
  64034. else {
  64035. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  64036. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  64037. '(VALUE: ' + !!buttonMeshInfo.value +
  64038. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  64039. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  64040. ')');
  64041. }
  64042. }
  64043. // Axis Meshes
  64044. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  64045. var axisMeshName = this._mapping.axisMeshNames[i];
  64046. if (!axisMeshName) {
  64047. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  64048. continue;
  64049. }
  64050. var axisMesh = getChildByName(rootNode, axisMeshName);
  64051. if (!axisMesh) {
  64052. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  64053. continue;
  64054. }
  64055. var axisMeshInfo = {
  64056. index: i,
  64057. value: getImmediateChildByName(axisMesh, 'VALUE'),
  64058. min: getImmediateChildByName(axisMesh, 'MIN'),
  64059. max: getImmediateChildByName(axisMesh, 'MAX')
  64060. };
  64061. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  64062. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  64063. }
  64064. else {
  64065. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  64066. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  64067. '(VALUE: ' + !!axisMeshInfo.value +
  64068. ', MIN: ' + !!axisMeshInfo.min +
  64069. ', MAX:' + !!axisMeshInfo.max +
  64070. ')');
  64071. }
  64072. }
  64073. // Pointing Ray
  64074. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  64075. if (!loadedMeshInfo.pointingPoseNode) {
  64076. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  64077. }
  64078. return loadedMeshInfo;
  64079. // Look through all children recursively. This will return null if no mesh exists with the given name.
  64080. function getChildByName(node, name) {
  64081. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  64082. }
  64083. // Look through only immediate children. This will return null if no mesh exists with the given name.
  64084. function getImmediateChildByName(node, name) {
  64085. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  64086. }
  64087. };
  64088. WindowsMotionController.prototype.getForwardRay = function (length) {
  64089. if (length === void 0) { length = 100; }
  64090. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  64091. return _super.prototype.getForwardRay.call(this, length);
  64092. }
  64093. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  64094. var origin = m.getTranslation();
  64095. var forward = new BABYLON.Vector3(0, 0, -1);
  64096. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64097. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64098. return new BABYLON.Ray(origin, direction, length);
  64099. };
  64100. WindowsMotionController.prototype.dispose = function () {
  64101. _super.prototype.dispose.call(this);
  64102. this.onTrackpadChangedObservable.clear();
  64103. };
  64104. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  64105. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  64106. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  64107. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  64108. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  64109. return WindowsMotionController;
  64110. }(BABYLON.WebVRController));
  64111. BABYLON.WindowsMotionController = WindowsMotionController;
  64112. })(BABYLON || (BABYLON = {}));
  64113. //# sourceMappingURL=babylon.windowsMotionController.js.map
  64114. var BABYLON;
  64115. (function (BABYLON) {
  64116. var GearVRController = /** @class */ (function (_super) {
  64117. __extends(GearVRController, _super);
  64118. function GearVRController(vrGamepad) {
  64119. var _this = _super.call(this, vrGamepad) || this;
  64120. _this._buttonIndexToObservableNameMap = [
  64121. 'onTrackpadChangedObservable',
  64122. 'onTriggerStateChangedObservable' // Trigger
  64123. ];
  64124. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  64125. return _this;
  64126. }
  64127. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64128. var _this = this;
  64129. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  64130. _this._defaultModel = newMeshes[1];
  64131. _this.attachToMesh(_this._defaultModel);
  64132. if (meshLoaded) {
  64133. meshLoaded(_this._defaultModel);
  64134. }
  64135. });
  64136. };
  64137. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64138. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  64139. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  64140. // Only emit events for buttons that we know how to map from index to observable
  64141. var observable = this[observableName];
  64142. if (observable) {
  64143. observable.notifyObservers(state);
  64144. }
  64145. }
  64146. };
  64147. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64148. GearVRController.MODEL_FILENAME = 'generic.babylon';
  64149. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  64150. return GearVRController;
  64151. }(BABYLON.WebVRController));
  64152. BABYLON.GearVRController = GearVRController;
  64153. })(BABYLON || (BABYLON = {}));
  64154. //# sourceMappingURL=babylon.gearVRController.js.map
  64155. var BABYLON;
  64156. (function (BABYLON) {
  64157. var FollowCamera = /** @class */ (function (_super) {
  64158. __extends(FollowCamera, _super);
  64159. function FollowCamera(name, position, scene, lockedTarget) {
  64160. if (lockedTarget === void 0) { lockedTarget = null; }
  64161. var _this = _super.call(this, name, position, scene) || this;
  64162. _this.radius = 12;
  64163. _this.rotationOffset = 0;
  64164. _this.heightOffset = 4;
  64165. _this.cameraAcceleration = 0.05;
  64166. _this.maxCameraSpeed = 20;
  64167. _this.lockedTarget = lockedTarget;
  64168. return _this;
  64169. }
  64170. FollowCamera.prototype.getRadians = function (degrees) {
  64171. return degrees * Math.PI / 180;
  64172. };
  64173. FollowCamera.prototype.follow = function (cameraTarget) {
  64174. if (!cameraTarget)
  64175. return;
  64176. var yRotation;
  64177. if (cameraTarget.rotationQuaternion) {
  64178. var rotMatrix = new BABYLON.Matrix();
  64179. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  64180. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  64181. }
  64182. else {
  64183. yRotation = cameraTarget.rotation.y;
  64184. }
  64185. var radians = this.getRadians(this.rotationOffset) + yRotation;
  64186. var targetPosition = cameraTarget.getAbsolutePosition();
  64187. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  64188. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  64189. var dx = targetX - this.position.x;
  64190. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  64191. var dz = (targetZ) - this.position.z;
  64192. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  64193. var vy = dy * this.cameraAcceleration;
  64194. var vz = dz * this.cameraAcceleration * 2;
  64195. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  64196. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64197. }
  64198. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  64199. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64200. }
  64201. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  64202. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64203. }
  64204. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  64205. this.setTarget(targetPosition);
  64206. };
  64207. FollowCamera.prototype._checkInputs = function () {
  64208. _super.prototype._checkInputs.call(this);
  64209. if (this.lockedTarget) {
  64210. this.follow(this.lockedTarget);
  64211. }
  64212. };
  64213. FollowCamera.prototype.getClassName = function () {
  64214. return "FollowCamera";
  64215. };
  64216. __decorate([
  64217. BABYLON.serialize()
  64218. ], FollowCamera.prototype, "radius", void 0);
  64219. __decorate([
  64220. BABYLON.serialize()
  64221. ], FollowCamera.prototype, "rotationOffset", void 0);
  64222. __decorate([
  64223. BABYLON.serialize()
  64224. ], FollowCamera.prototype, "heightOffset", void 0);
  64225. __decorate([
  64226. BABYLON.serialize()
  64227. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  64228. __decorate([
  64229. BABYLON.serialize()
  64230. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  64231. __decorate([
  64232. BABYLON.serializeAsMeshReference("lockedTargetId")
  64233. ], FollowCamera.prototype, "lockedTarget", void 0);
  64234. return FollowCamera;
  64235. }(BABYLON.TargetCamera));
  64236. BABYLON.FollowCamera = FollowCamera;
  64237. var ArcFollowCamera = /** @class */ (function (_super) {
  64238. __extends(ArcFollowCamera, _super);
  64239. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  64240. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  64241. _this.alpha = alpha;
  64242. _this.beta = beta;
  64243. _this.radius = radius;
  64244. _this.target = target;
  64245. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  64246. _this.follow();
  64247. return _this;
  64248. }
  64249. ArcFollowCamera.prototype.follow = function () {
  64250. if (!this.target) {
  64251. return;
  64252. }
  64253. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  64254. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  64255. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  64256. var targetPosition = this.target.getAbsolutePosition();
  64257. this.position = targetPosition.add(this._cartesianCoordinates);
  64258. this.setTarget(targetPosition);
  64259. };
  64260. ArcFollowCamera.prototype._checkInputs = function () {
  64261. _super.prototype._checkInputs.call(this);
  64262. this.follow();
  64263. };
  64264. ArcFollowCamera.prototype.getClassName = function () {
  64265. return "ArcFollowCamera";
  64266. };
  64267. return ArcFollowCamera;
  64268. }(BABYLON.TargetCamera));
  64269. BABYLON.ArcFollowCamera = ArcFollowCamera;
  64270. })(BABYLON || (BABYLON = {}));
  64271. //# sourceMappingURL=babylon.followCamera.js.map
  64272. var BABYLON;
  64273. (function (BABYLON) {
  64274. // We're mainly based on the logic defined into the FreeCamera code
  64275. var UniversalCamera = /** @class */ (function (_super) {
  64276. __extends(UniversalCamera, _super);
  64277. //-- end properties for backward compatibility for inputs
  64278. function UniversalCamera(name, position, scene) {
  64279. var _this = _super.call(this, name, position, scene) || this;
  64280. _this.inputs.addGamepad();
  64281. return _this;
  64282. }
  64283. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  64284. //-- Begin properties for backward compatibility for inputs
  64285. get: function () {
  64286. var gamepad = this.inputs.attached["gamepad"];
  64287. if (gamepad)
  64288. return gamepad.gamepadAngularSensibility;
  64289. return 0;
  64290. },
  64291. set: function (value) {
  64292. var gamepad = this.inputs.attached["gamepad"];
  64293. if (gamepad)
  64294. gamepad.gamepadAngularSensibility = value;
  64295. },
  64296. enumerable: true,
  64297. configurable: true
  64298. });
  64299. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  64300. get: function () {
  64301. var gamepad = this.inputs.attached["gamepad"];
  64302. if (gamepad)
  64303. return gamepad.gamepadMoveSensibility;
  64304. return 0;
  64305. },
  64306. set: function (value) {
  64307. var gamepad = this.inputs.attached["gamepad"];
  64308. if (gamepad)
  64309. gamepad.gamepadMoveSensibility = value;
  64310. },
  64311. enumerable: true,
  64312. configurable: true
  64313. });
  64314. UniversalCamera.prototype.getClassName = function () {
  64315. return "UniversalCamera";
  64316. };
  64317. return UniversalCamera;
  64318. }(BABYLON.TouchCamera));
  64319. BABYLON.UniversalCamera = UniversalCamera;
  64320. })(BABYLON || (BABYLON = {}));
  64321. //# sourceMappingURL=babylon.universalCamera.js.map
  64322. var BABYLON;
  64323. (function (BABYLON) {
  64324. // We're mainly based on the logic defined into the FreeCamera code
  64325. var GamepadCamera = /** @class */ (function (_super) {
  64326. __extends(GamepadCamera, _super);
  64327. //-- end properties for backward compatibility for inputs
  64328. function GamepadCamera(name, position, scene) {
  64329. return _super.call(this, name, position, scene) || this;
  64330. }
  64331. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  64332. //-- Begin properties for backward compatibility for inputs
  64333. get: function () {
  64334. var gamepad = this.inputs.attached["gamepad"];
  64335. if (gamepad)
  64336. return gamepad.gamepadAngularSensibility;
  64337. return 0;
  64338. },
  64339. set: function (value) {
  64340. var gamepad = this.inputs.attached["gamepad"];
  64341. if (gamepad)
  64342. gamepad.gamepadAngularSensibility = value;
  64343. },
  64344. enumerable: true,
  64345. configurable: true
  64346. });
  64347. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  64348. get: function () {
  64349. var gamepad = this.inputs.attached["gamepad"];
  64350. if (gamepad)
  64351. return gamepad.gamepadMoveSensibility;
  64352. return 0;
  64353. },
  64354. set: function (value) {
  64355. var gamepad = this.inputs.attached["gamepad"];
  64356. if (gamepad)
  64357. gamepad.gamepadMoveSensibility = value;
  64358. },
  64359. enumerable: true,
  64360. configurable: true
  64361. });
  64362. GamepadCamera.prototype.getClassName = function () {
  64363. return "GamepadCamera";
  64364. };
  64365. return GamepadCamera;
  64366. }(BABYLON.UniversalCamera));
  64367. BABYLON.GamepadCamera = GamepadCamera;
  64368. })(BABYLON || (BABYLON = {}));
  64369. //# sourceMappingURL=babylon.gamepadCamera.js.map
  64370. var BABYLON;
  64371. (function (BABYLON) {
  64372. var PostProcessRenderPipelineManager = /** @class */ (function () {
  64373. function PostProcessRenderPipelineManager() {
  64374. this._renderPipelines = {};
  64375. }
  64376. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  64377. this._renderPipelines[renderPipeline._name] = renderPipeline;
  64378. };
  64379. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  64380. if (unique === void 0) { unique = false; }
  64381. var renderPipeline = this._renderPipelines[renderPipelineName];
  64382. if (!renderPipeline) {
  64383. return;
  64384. }
  64385. renderPipeline._attachCameras(cameras, unique);
  64386. };
  64387. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  64388. var renderPipeline = this._renderPipelines[renderPipelineName];
  64389. if (!renderPipeline) {
  64390. return;
  64391. }
  64392. renderPipeline._detachCameras(cameras);
  64393. };
  64394. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64395. var renderPipeline = this._renderPipelines[renderPipelineName];
  64396. if (!renderPipeline) {
  64397. return;
  64398. }
  64399. renderPipeline._enableEffect(renderEffectName, cameras);
  64400. };
  64401. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64402. var renderPipeline = this._renderPipelines[renderPipelineName];
  64403. if (!renderPipeline) {
  64404. return;
  64405. }
  64406. renderPipeline._disableEffect(renderEffectName, cameras);
  64407. };
  64408. PostProcessRenderPipelineManager.prototype.update = function () {
  64409. for (var renderPipelineName in this._renderPipelines) {
  64410. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64411. var pipeline = this._renderPipelines[renderPipelineName];
  64412. if (!pipeline.isSupported) {
  64413. pipeline.dispose();
  64414. delete this._renderPipelines[renderPipelineName];
  64415. }
  64416. else {
  64417. pipeline._update();
  64418. }
  64419. }
  64420. }
  64421. };
  64422. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  64423. for (var renderPipelineName in this._renderPipelines) {
  64424. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64425. var pipeline = this._renderPipelines[renderPipelineName];
  64426. pipeline._rebuild();
  64427. }
  64428. }
  64429. };
  64430. PostProcessRenderPipelineManager.prototype.dispose = function () {
  64431. for (var renderPipelineName in this._renderPipelines) {
  64432. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64433. var pipeline = this._renderPipelines[renderPipelineName];
  64434. pipeline.dispose();
  64435. }
  64436. }
  64437. };
  64438. return PostProcessRenderPipelineManager;
  64439. }());
  64440. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  64441. })(BABYLON || (BABYLON = {}));
  64442. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  64443. var BABYLON;
  64444. (function (BABYLON) {
  64445. /**
  64446. * This represents a set of one or more post processes in Babylon.
  64447. * A post process can be used to apply a shader to a texture after it is rendered.
  64448. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  64449. */
  64450. var PostProcessRenderEffect = /** @class */ (function () {
  64451. /**
  64452. * Instantiates a post process render effect.
  64453. * A post process can be used to apply a shader to a texture after it is rendered.
  64454. * @param engine The engine the effect is tied to
  64455. * @param name The name of the effect
  64456. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  64457. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  64458. */
  64459. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  64460. this._name = name;
  64461. this._singleInstance = singleInstance || true;
  64462. this._getPostProcesses = getPostProcesses;
  64463. this._cameras = {};
  64464. this._indicesForCamera = {};
  64465. this._postProcesses = {};
  64466. }
  64467. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  64468. /**
  64469. * Checks if all the post processes in the effect are supported.
  64470. */
  64471. get: function () {
  64472. for (var index in this._postProcesses) {
  64473. for (var ppIndex in this._postProcesses[index]) {
  64474. if (!this._postProcesses[index][ppIndex].isSupported) {
  64475. return false;
  64476. }
  64477. }
  64478. }
  64479. return true;
  64480. },
  64481. enumerable: true,
  64482. configurable: true
  64483. });
  64484. /**
  64485. * Updates the current state of the effect
  64486. */
  64487. PostProcessRenderEffect.prototype._update = function () {
  64488. };
  64489. /**
  64490. * Attaches the effect on cameras
  64491. * @param cameras The camera to attach to.
  64492. */
  64493. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  64494. var _this = this;
  64495. var cameraKey;
  64496. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64497. if (!cams) {
  64498. return;
  64499. }
  64500. for (var i = 0; i < cams.length; i++) {
  64501. var camera = cams[i];
  64502. var cameraName = camera.name;
  64503. if (this._singleInstance) {
  64504. cameraKey = 0;
  64505. }
  64506. else {
  64507. cameraKey = cameraName;
  64508. }
  64509. if (!this._postProcesses[cameraKey]) {
  64510. var postProcess = this._getPostProcesses();
  64511. if (postProcess) {
  64512. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  64513. }
  64514. }
  64515. if (!this._indicesForCamera[cameraName]) {
  64516. this._indicesForCamera[cameraName] = [];
  64517. }
  64518. this._postProcesses[cameraKey].forEach(function (postProcess) {
  64519. var index = camera.attachPostProcess(postProcess);
  64520. _this._indicesForCamera[cameraName].push(index);
  64521. });
  64522. if (!this._cameras[cameraName]) {
  64523. this._cameras[cameraName] = camera;
  64524. }
  64525. }
  64526. };
  64527. /**
  64528. * Detatches the effect on cameras
  64529. * @param cameras The camera to detatch from.
  64530. */
  64531. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  64532. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64533. if (!cams) {
  64534. return;
  64535. }
  64536. for (var i = 0; i < cams.length; i++) {
  64537. var camera = cams[i];
  64538. var cameraName = camera.name;
  64539. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64540. camera.detachPostProcess(postProcess);
  64541. });
  64542. if (this._cameras[cameraName]) {
  64543. //this._indicesForCamera.splice(index, 1);
  64544. this._cameras[cameraName] = null;
  64545. }
  64546. }
  64547. };
  64548. /**
  64549. * Enables the effect on given cameras
  64550. * @param cameras The camera to enable.
  64551. */
  64552. PostProcessRenderEffect.prototype._enable = function (cameras) {
  64553. var _this = this;
  64554. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64555. if (!cams) {
  64556. return;
  64557. }
  64558. for (var i = 0; i < cams.length; i++) {
  64559. var camera = cams[i];
  64560. var cameraName = camera.name;
  64561. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  64562. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  64563. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64564. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  64565. });
  64566. }
  64567. }
  64568. }
  64569. };
  64570. /**
  64571. * Disables the effect on the given cameras
  64572. * @param cameras The camera to disable.
  64573. */
  64574. PostProcessRenderEffect.prototype._disable = function (cameras) {
  64575. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64576. if (!cams) {
  64577. return;
  64578. }
  64579. for (var i = 0; i < cams.length; i++) {
  64580. var camera = cams[i];
  64581. var cameraName = camera.name;
  64582. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64583. camera.detachPostProcess(postProcess);
  64584. });
  64585. }
  64586. };
  64587. /**
  64588. * Gets a list of the post processes contained in the effect.
  64589. * @param camera The camera to get the post processes on.
  64590. * @returns The list of the post processes in the effect.
  64591. */
  64592. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  64593. if (this._singleInstance) {
  64594. return this._postProcesses[0];
  64595. }
  64596. else {
  64597. if (!camera) {
  64598. return null;
  64599. }
  64600. return this._postProcesses[camera.name];
  64601. }
  64602. };
  64603. return PostProcessRenderEffect;
  64604. }());
  64605. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  64606. })(BABYLON || (BABYLON = {}));
  64607. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  64608. var BABYLON;
  64609. (function (BABYLON) {
  64610. var PostProcessRenderPipeline = /** @class */ (function () {
  64611. function PostProcessRenderPipeline(engine, name) {
  64612. this._name = name;
  64613. this._renderEffects = {};
  64614. this._renderEffectsForIsolatedPass = new Array();
  64615. this._cameras = [];
  64616. }
  64617. PostProcessRenderPipeline.prototype.getClassName = function () {
  64618. return "PostProcessRenderPipeline";
  64619. };
  64620. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  64621. get: function () {
  64622. for (var renderEffectName in this._renderEffects) {
  64623. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64624. if (!this._renderEffects[renderEffectName].isSupported) {
  64625. return false;
  64626. }
  64627. }
  64628. }
  64629. return true;
  64630. },
  64631. enumerable: true,
  64632. configurable: true
  64633. });
  64634. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  64635. this._renderEffects[renderEffect._name] = renderEffect;
  64636. };
  64637. // private
  64638. PostProcessRenderPipeline.prototype._rebuild = function () {
  64639. };
  64640. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  64641. var renderEffects = this._renderEffects[renderEffectName];
  64642. if (!renderEffects) {
  64643. return;
  64644. }
  64645. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64646. };
  64647. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  64648. var renderEffects = this._renderEffects[renderEffectName];
  64649. if (!renderEffects) {
  64650. return;
  64651. }
  64652. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64653. };
  64654. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  64655. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64656. if (!cams) {
  64657. return;
  64658. }
  64659. var indicesToDelete = [];
  64660. var i;
  64661. for (i = 0; i < cams.length; i++) {
  64662. var camera = cams[i];
  64663. var cameraName = camera.name;
  64664. if (this._cameras.indexOf(camera) === -1) {
  64665. this._cameras[cameraName] = camera;
  64666. }
  64667. else if (unique) {
  64668. indicesToDelete.push(i);
  64669. }
  64670. }
  64671. for (i = 0; i < indicesToDelete.length; i++) {
  64672. cameras.splice(indicesToDelete[i], 1);
  64673. }
  64674. for (var renderEffectName in this._renderEffects) {
  64675. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64676. this._renderEffects[renderEffectName]._attachCameras(cams);
  64677. }
  64678. }
  64679. };
  64680. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  64681. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64682. if (!cams) {
  64683. return;
  64684. }
  64685. for (var renderEffectName in this._renderEffects) {
  64686. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64687. this._renderEffects[renderEffectName]._detachCameras(cams);
  64688. }
  64689. }
  64690. for (var i = 0; i < cams.length; i++) {
  64691. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  64692. }
  64693. };
  64694. PostProcessRenderPipeline.prototype._update = function () {
  64695. for (var renderEffectName in this._renderEffects) {
  64696. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64697. this._renderEffects[renderEffectName]._update();
  64698. }
  64699. }
  64700. for (var i = 0; i < this._cameras.length; i++) {
  64701. var cameraName = this._cameras[i].name;
  64702. if (this._renderEffectsForIsolatedPass[cameraName]) {
  64703. this._renderEffectsForIsolatedPass[cameraName]._update();
  64704. }
  64705. }
  64706. };
  64707. PostProcessRenderPipeline.prototype._reset = function () {
  64708. this._renderEffects = {};
  64709. this._renderEffectsForIsolatedPass = new Array();
  64710. };
  64711. PostProcessRenderPipeline.prototype.dispose = function () {
  64712. // Must be implemented by children
  64713. };
  64714. __decorate([
  64715. BABYLON.serialize()
  64716. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  64717. return PostProcessRenderPipeline;
  64718. }());
  64719. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  64720. })(BABYLON || (BABYLON = {}));
  64721. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  64722. var BABYLON;
  64723. (function (BABYLON) {
  64724. var DepthRenderer = /** @class */ (function () {
  64725. function DepthRenderer(scene, type) {
  64726. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64727. var _this = this;
  64728. this._scene = scene;
  64729. var engine = scene.getEngine();
  64730. // Render target
  64731. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  64732. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64733. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64734. this._depthMap.refreshRate = 1;
  64735. this._depthMap.renderParticles = false;
  64736. this._depthMap.renderList = null;
  64737. // set default depth value to 1.0 (far away)
  64738. this._depthMap.onClearObservable.add(function (engine) {
  64739. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  64740. });
  64741. // Custom render function
  64742. var renderSubMesh = function (subMesh) {
  64743. var mesh = subMesh.getRenderingMesh();
  64744. var scene = _this._scene;
  64745. var engine = scene.getEngine();
  64746. var material = subMesh.getMaterial();
  64747. if (!material) {
  64748. return;
  64749. }
  64750. // Culling and reverse (right handed system)
  64751. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64752. // Managing instances
  64753. var batch = mesh._getInstancesRenderList(subMesh._id);
  64754. if (batch.mustReturn) {
  64755. return;
  64756. }
  64757. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64758. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  64759. engine.enableEffect(_this._effect);
  64760. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64761. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64762. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  64763. // Alpha test
  64764. if (material && material.needAlphaTesting()) {
  64765. var alphaTexture = material.getAlphaTestTexture();
  64766. if (alphaTexture) {
  64767. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64768. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64769. }
  64770. }
  64771. // Bones
  64772. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64773. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64774. }
  64775. // Draw
  64776. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64777. }
  64778. };
  64779. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64780. var index;
  64781. if (depthOnlySubMeshes.length) {
  64782. engine.setColorWrite(false);
  64783. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64784. renderSubMesh(depthOnlySubMeshes.data[index]);
  64785. }
  64786. engine.setColorWrite(true);
  64787. }
  64788. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64789. renderSubMesh(opaqueSubMeshes.data[index]);
  64790. }
  64791. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64792. renderSubMesh(alphaTestSubMeshes.data[index]);
  64793. }
  64794. };
  64795. }
  64796. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  64797. var material = subMesh.getMaterial();
  64798. if (material.disableDepthWrite) {
  64799. return false;
  64800. }
  64801. var defines = [];
  64802. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64803. var mesh = subMesh.getMesh();
  64804. // Alpha test
  64805. if (material && material.needAlphaTesting()) {
  64806. defines.push("#define ALPHATEST");
  64807. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64808. attribs.push(BABYLON.VertexBuffer.UVKind);
  64809. defines.push("#define UV1");
  64810. }
  64811. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64812. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64813. defines.push("#define UV2");
  64814. }
  64815. }
  64816. // Bones
  64817. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64818. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64819. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64820. if (mesh.numBoneInfluencers > 4) {
  64821. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64822. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64823. }
  64824. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64825. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  64826. }
  64827. else {
  64828. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64829. }
  64830. // Instances
  64831. if (useInstances) {
  64832. defines.push("#define INSTANCES");
  64833. attribs.push("world0");
  64834. attribs.push("world1");
  64835. attribs.push("world2");
  64836. attribs.push("world3");
  64837. }
  64838. // Get correct effect
  64839. var join = defines.join("\n");
  64840. if (this._cachedDefines !== join) {
  64841. this._cachedDefines = join;
  64842. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  64843. }
  64844. return this._effect.isReady();
  64845. };
  64846. DepthRenderer.prototype.getDepthMap = function () {
  64847. return this._depthMap;
  64848. };
  64849. // Methods
  64850. DepthRenderer.prototype.dispose = function () {
  64851. this._depthMap.dispose();
  64852. };
  64853. return DepthRenderer;
  64854. }());
  64855. BABYLON.DepthRenderer = DepthRenderer;
  64856. })(BABYLON || (BABYLON = {}));
  64857. //# sourceMappingURL=babylon.depthRenderer.js.map
  64858. var BABYLON;
  64859. (function (BABYLON) {
  64860. var SSAORenderingPipeline = /** @class */ (function (_super) {
  64861. __extends(SSAORenderingPipeline, _super);
  64862. /**
  64863. * @constructor
  64864. * @param {string} name - The rendering pipeline name
  64865. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64866. * @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 }
  64867. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64868. */
  64869. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  64870. var _this = _super.call(this, scene.getEngine(), name) || this;
  64871. // Members
  64872. /**
  64873. * The PassPostProcess id in the pipeline that contains the original scene color
  64874. * @type {string}
  64875. */
  64876. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  64877. /**
  64878. * The SSAO PostProcess id in the pipeline
  64879. * @type {string}
  64880. */
  64881. _this.SSAORenderEffect = "SSAORenderEffect";
  64882. /**
  64883. * The horizontal blur PostProcess id in the pipeline
  64884. * @type {string}
  64885. */
  64886. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  64887. /**
  64888. * The vertical blur PostProcess id in the pipeline
  64889. * @type {string}
  64890. */
  64891. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  64892. /**
  64893. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  64894. * @type {string}
  64895. */
  64896. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  64897. /**
  64898. * The output strength of the SSAO post-process. Default value is 1.0.
  64899. * @type {number}
  64900. */
  64901. _this.totalStrength = 1.0;
  64902. /**
  64903. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  64904. * @type {number}
  64905. */
  64906. _this.radius = 0.0001;
  64907. /**
  64908. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  64909. * Must not be equal to fallOff and superior to fallOff.
  64910. * Default value is 0.975
  64911. * @type {number}
  64912. */
  64913. _this.area = 0.0075;
  64914. /**
  64915. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  64916. * Must not be equal to area and inferior to area.
  64917. * Default value is 0.0
  64918. * @type {number}
  64919. */
  64920. _this.fallOff = 0.000001;
  64921. /**
  64922. * The base color of the SSAO post-process
  64923. * The final result is "base + ssao" between [0, 1]
  64924. * @type {number}
  64925. */
  64926. _this.base = 0.5;
  64927. _this._firstUpdate = true;
  64928. _this._scene = scene;
  64929. // Set up assets
  64930. _this._createRandomTexture();
  64931. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  64932. var ssaoRatio = ratio.ssaoRatio || ratio;
  64933. var combineRatio = ratio.combineRatio || ratio;
  64934. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  64935. _this._createSSAOPostProcess(ssaoRatio);
  64936. _this._createBlurPostProcess(ssaoRatio);
  64937. _this._createSSAOCombinePostProcess(combineRatio);
  64938. // Set up pipeline
  64939. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  64940. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  64941. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  64942. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  64943. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  64944. // Finish
  64945. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64946. if (cameras)
  64947. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  64948. return _this;
  64949. }
  64950. // Public Methods
  64951. /**
  64952. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  64953. */
  64954. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  64955. if (disableDepthRender === void 0) { disableDepthRender = false; }
  64956. for (var i = 0; i < this._scene.cameras.length; i++) {
  64957. var camera = this._scene.cameras[i];
  64958. this._originalColorPostProcess.dispose(camera);
  64959. this._ssaoPostProcess.dispose(camera);
  64960. this._blurHPostProcess.dispose(camera);
  64961. this._blurVPostProcess.dispose(camera);
  64962. this._ssaoCombinePostProcess.dispose(camera);
  64963. }
  64964. this._randomTexture.dispose();
  64965. if (disableDepthRender)
  64966. this._scene.disableDepthRenderer();
  64967. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  64968. _super.prototype.dispose.call(this);
  64969. };
  64970. // Private Methods
  64971. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  64972. var _this = this;
  64973. var size = 16;
  64974. 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);
  64975. 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);
  64976. this._blurHPostProcess.onActivateObservable.add(function () {
  64977. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  64978. _this._blurHPostProcess.kernel = size * dw;
  64979. });
  64980. this._blurVPostProcess.onActivateObservable.add(function () {
  64981. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  64982. _this._blurVPostProcess.kernel = size * dw;
  64983. });
  64984. };
  64985. SSAORenderingPipeline.prototype._rebuild = function () {
  64986. this._firstUpdate = true;
  64987. _super.prototype._rebuild.call(this);
  64988. };
  64989. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  64990. var _this = this;
  64991. var numSamples = 16;
  64992. var sampleSphere = [
  64993. 0.5381, 0.1856, -0.4319,
  64994. 0.1379, 0.2486, 0.4430,
  64995. 0.3371, 0.5679, -0.0057,
  64996. -0.6999, -0.0451, -0.0019,
  64997. 0.0689, -0.1598, -0.8547,
  64998. 0.0560, 0.0069, -0.1843,
  64999. -0.0146, 0.1402, 0.0762,
  65000. 0.0100, -0.1924, -0.0344,
  65001. -0.3577, -0.5301, -0.4358,
  65002. -0.3169, 0.1063, 0.0158,
  65003. 0.0103, -0.5869, 0.0046,
  65004. -0.0897, -0.4940, 0.3287,
  65005. 0.7119, -0.0154, -0.0918,
  65006. -0.0533, 0.0596, -0.5411,
  65007. 0.0352, -0.0631, 0.5460,
  65008. -0.4776, 0.2847, -0.0271
  65009. ];
  65010. var samplesFactor = 1.0 / numSamples;
  65011. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  65012. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65013. "area", "fallOff", "base", "range", "viewport"
  65014. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65015. this._ssaoPostProcess.onApply = function (effect) {
  65016. if (_this._firstUpdate) {
  65017. effect.setArray3("sampleSphere", sampleSphere);
  65018. effect.setFloat("samplesFactor", samplesFactor);
  65019. effect.setFloat("randTextureTiles", 4.0);
  65020. }
  65021. effect.setFloat("totalStrength", _this.totalStrength);
  65022. effect.setFloat("radius", _this.radius);
  65023. effect.setFloat("area", _this.area);
  65024. effect.setFloat("fallOff", _this.fallOff);
  65025. effect.setFloat("base", _this.base);
  65026. effect.setTexture("textureSampler", _this._depthTexture);
  65027. effect.setTexture("randomSampler", _this._randomTexture);
  65028. };
  65029. };
  65030. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65031. var _this = this;
  65032. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65033. this._ssaoCombinePostProcess.onApply = function (effect) {
  65034. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65035. };
  65036. };
  65037. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  65038. var size = 512;
  65039. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65040. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65041. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65042. var context = this._randomTexture.getContext();
  65043. var rand = function (min, max) {
  65044. return Math.random() * (max - min) + min;
  65045. };
  65046. var randVector = BABYLON.Vector3.Zero();
  65047. for (var x = 0; x < size; x++) {
  65048. for (var y = 0; y < size; y++) {
  65049. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  65050. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  65051. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  65052. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65053. context.fillRect(x, y, 1, 1);
  65054. }
  65055. }
  65056. this._randomTexture.update(false);
  65057. };
  65058. __decorate([
  65059. BABYLON.serialize()
  65060. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  65061. __decorate([
  65062. BABYLON.serialize()
  65063. ], SSAORenderingPipeline.prototype, "radius", void 0);
  65064. __decorate([
  65065. BABYLON.serialize()
  65066. ], SSAORenderingPipeline.prototype, "area", void 0);
  65067. __decorate([
  65068. BABYLON.serialize()
  65069. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  65070. __decorate([
  65071. BABYLON.serialize()
  65072. ], SSAORenderingPipeline.prototype, "base", void 0);
  65073. return SSAORenderingPipeline;
  65074. }(BABYLON.PostProcessRenderPipeline));
  65075. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  65076. })(BABYLON || (BABYLON = {}));
  65077. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  65078. var BABYLON;
  65079. (function (BABYLON) {
  65080. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  65081. __extends(SSAO2RenderingPipeline, _super);
  65082. /**
  65083. * @constructor
  65084. * @param {string} name - The rendering pipeline name
  65085. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65086. * @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 }
  65087. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65088. */
  65089. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  65090. var _this = _super.call(this, scene.getEngine(), name) || this;
  65091. // Members
  65092. /**
  65093. * The PassPostProcess id in the pipeline that contains the original scene color
  65094. * @type {string}
  65095. */
  65096. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  65097. /**
  65098. * The SSAO PostProcess id in the pipeline
  65099. * @type {string}
  65100. */
  65101. _this.SSAORenderEffect = "SSAORenderEffect";
  65102. /**
  65103. * The horizontal blur PostProcess id in the pipeline
  65104. * @type {string}
  65105. */
  65106. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  65107. /**
  65108. * The vertical blur PostProcess id in the pipeline
  65109. * @type {string}
  65110. */
  65111. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  65112. /**
  65113. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  65114. * @type {string}
  65115. */
  65116. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  65117. /**
  65118. * The output strength of the SSAO post-process. Default value is 1.0.
  65119. * @type {number}
  65120. */
  65121. _this.totalStrength = 1.0;
  65122. /**
  65123. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  65124. * @type {number}
  65125. */
  65126. _this.maxZ = 100.0;
  65127. /**
  65128. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  65129. * @type {number}
  65130. */
  65131. _this.minZAspect = 0.2;
  65132. /**
  65133. * Number of samples used for the SSAO calculations. Default value is 8
  65134. * @type {number}
  65135. */
  65136. _this._samples = 8;
  65137. /**
  65138. * Are we using bilateral blur ?
  65139. * @type {boolean}
  65140. */
  65141. _this._expensiveBlur = true;
  65142. /**
  65143. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  65144. * @type {number}
  65145. */
  65146. _this.radius = 2.0;
  65147. /**
  65148. * The base color of the SSAO post-process
  65149. * The final result is "base + ssao" between [0, 1]
  65150. * @type {number}
  65151. */
  65152. _this.base = 0.1;
  65153. _this._firstUpdate = true;
  65154. _this._scene = scene;
  65155. if (!_this.isSupported) {
  65156. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  65157. return _this;
  65158. }
  65159. var ssaoRatio = ratio.ssaoRatio || ratio;
  65160. var blurRatio = ratio.blurRatio || ratio;
  65161. // Set up assets
  65162. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  65163. _this._createRandomTexture();
  65164. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  65165. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  65166. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  65167. _this._createSSAOPostProcess(1.0);
  65168. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  65169. _this._createSSAOCombinePostProcess(blurRatio);
  65170. // Set up pipeline
  65171. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  65172. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  65173. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  65174. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  65175. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  65176. // Finish
  65177. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65178. if (cameras)
  65179. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65180. return _this;
  65181. }
  65182. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  65183. get: function () {
  65184. return this._samples;
  65185. },
  65186. set: function (n) {
  65187. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  65188. this._samples = n;
  65189. this._sampleSphere = this._generateHemisphere();
  65190. this._firstUpdate = true;
  65191. },
  65192. enumerable: true,
  65193. configurable: true
  65194. });
  65195. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  65196. get: function () {
  65197. return this._expensiveBlur;
  65198. },
  65199. set: function (b) {
  65200. 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"]);
  65201. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  65202. this._expensiveBlur = b;
  65203. this._firstUpdate = true;
  65204. },
  65205. enumerable: true,
  65206. configurable: true
  65207. });
  65208. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  65209. /**
  65210. * Support test.
  65211. * @type {boolean}
  65212. */
  65213. get: function () {
  65214. var engine = BABYLON.Engine.LastCreatedEngine;
  65215. if (!engine) {
  65216. return false;
  65217. }
  65218. return engine.getCaps().drawBuffersExtension;
  65219. },
  65220. enumerable: true,
  65221. configurable: true
  65222. });
  65223. // Public Methods
  65224. /**
  65225. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  65226. */
  65227. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  65228. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  65229. for (var i = 0; i < this._scene.cameras.length; i++) {
  65230. var camera = this._scene.cameras[i];
  65231. this._originalColorPostProcess.dispose(camera);
  65232. this._ssaoPostProcess.dispose(camera);
  65233. this._blurHPostProcess.dispose(camera);
  65234. this._blurVPostProcess.dispose(camera);
  65235. this._ssaoCombinePostProcess.dispose(camera);
  65236. }
  65237. this._randomTexture.dispose();
  65238. if (disableGeometryBufferRenderer)
  65239. this._scene.disableGeometryBufferRenderer();
  65240. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65241. _super.prototype.dispose.call(this);
  65242. };
  65243. // Private Methods
  65244. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  65245. var _this = this;
  65246. this._samplerOffsets = [];
  65247. var expensive = this.expensiveBlur;
  65248. for (var i = -8; i < 8; i++) {
  65249. this._samplerOffsets.push(i * 2 + 0.5);
  65250. }
  65251. 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");
  65252. this._blurHPostProcess.onApply = function (effect) {
  65253. if (!_this._scene.activeCamera) {
  65254. return;
  65255. }
  65256. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  65257. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65258. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65259. effect.setFloat("radius", _this.radius);
  65260. effect.setTexture("depthSampler", _this._depthTexture);
  65261. if (_this._firstUpdate) {
  65262. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65263. }
  65264. };
  65265. 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");
  65266. this._blurVPostProcess.onApply = function (effect) {
  65267. if (!_this._scene.activeCamera) {
  65268. return;
  65269. }
  65270. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  65271. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65272. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65273. effect.setFloat("radius", _this.radius);
  65274. effect.setTexture("depthSampler", _this._depthTexture);
  65275. if (_this._firstUpdate) {
  65276. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65277. _this._firstUpdate = false;
  65278. }
  65279. };
  65280. };
  65281. SSAO2RenderingPipeline.prototype._rebuild = function () {
  65282. this._firstUpdate = true;
  65283. _super.prototype._rebuild.call(this);
  65284. };
  65285. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  65286. var numSamples = this.samples;
  65287. var result = [];
  65288. var vector, scale;
  65289. var rand = function (min, max) {
  65290. return Math.random() * (max - min) + min;
  65291. };
  65292. var i = 0;
  65293. while (i < numSamples) {
  65294. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  65295. vector.normalize();
  65296. scale = i / numSamples;
  65297. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  65298. vector.scaleInPlace(scale);
  65299. result.push(vector.x, vector.y, vector.z);
  65300. i++;
  65301. }
  65302. return result;
  65303. };
  65304. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65305. var _this = this;
  65306. var numSamples = this.samples;
  65307. this._sampleSphere = this._generateHemisphere();
  65308. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  65309. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65310. "base", "range", "projection", "near", "far", "texelSize",
  65311. "xViewport", "yViewport", "maxZ", "minZAspect"
  65312. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65313. this._ssaoPostProcess.onApply = function (effect) {
  65314. if (_this._firstUpdate) {
  65315. effect.setArray3("sampleSphere", _this._sampleSphere);
  65316. effect.setFloat("randTextureTiles", 4.0);
  65317. }
  65318. if (!_this._scene.activeCamera) {
  65319. return;
  65320. }
  65321. effect.setFloat("samplesFactor", 1 / _this.samples);
  65322. effect.setFloat("totalStrength", _this.totalStrength);
  65323. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  65324. effect.setFloat("radius", _this.radius);
  65325. effect.setFloat("maxZ", _this.maxZ);
  65326. effect.setFloat("minZAspect", _this.minZAspect);
  65327. effect.setFloat("base", _this.base);
  65328. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65329. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65330. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  65331. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  65332. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  65333. effect.setTexture("textureSampler", _this._depthTexture);
  65334. effect.setTexture("normalSampler", _this._normalTexture);
  65335. effect.setTexture("randomSampler", _this._randomTexture);
  65336. };
  65337. };
  65338. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65339. var _this = this;
  65340. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65341. this._ssaoCombinePostProcess.onApply = function (effect) {
  65342. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65343. };
  65344. };
  65345. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  65346. var size = 512;
  65347. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65348. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65349. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65350. var context = this._randomTexture.getContext();
  65351. var rand = function (min, max) {
  65352. return Math.random() * (max - min) + min;
  65353. };
  65354. var randVector = BABYLON.Vector3.Zero();
  65355. for (var x = 0; x < size; x++) {
  65356. for (var y = 0; y < size; y++) {
  65357. randVector.x = rand(0.0, 1.0);
  65358. randVector.y = rand(0.0, 1.0);
  65359. randVector.z = 0.0;
  65360. randVector.normalize();
  65361. randVector.scaleInPlace(255);
  65362. randVector.x = Math.floor(randVector.x);
  65363. randVector.y = Math.floor(randVector.y);
  65364. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65365. context.fillRect(x, y, 1, 1);
  65366. }
  65367. }
  65368. this._randomTexture.update(false);
  65369. };
  65370. __decorate([
  65371. BABYLON.serialize()
  65372. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  65373. __decorate([
  65374. BABYLON.serialize()
  65375. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  65376. __decorate([
  65377. BABYLON.serialize()
  65378. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  65379. __decorate([
  65380. BABYLON.serialize("samples")
  65381. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  65382. __decorate([
  65383. BABYLON.serialize("expensiveBlur")
  65384. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  65385. __decorate([
  65386. BABYLON.serialize()
  65387. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  65388. __decorate([
  65389. BABYLON.serialize()
  65390. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  65391. return SSAO2RenderingPipeline;
  65392. }(BABYLON.PostProcessRenderPipeline));
  65393. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  65394. })(BABYLON || (BABYLON = {}));
  65395. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  65396. // BABYLON.JS Chromatic Aberration GLSL Shader
  65397. // Author: Olivier Guyot
  65398. // Separates very slightly R, G and B colors on the edges of the screen
  65399. // Inspired by Francois Tarlier & Martins Upitis
  65400. var BABYLON;
  65401. (function (BABYLON) {
  65402. var LensRenderingPipeline = /** @class */ (function (_super) {
  65403. __extends(LensRenderingPipeline, _super);
  65404. /**
  65405. * @constructor
  65406. *
  65407. * Effect parameters are as follow:
  65408. * {
  65409. * chromatic_aberration: number; // from 0 to x (1 for realism)
  65410. * edge_blur: number; // from 0 to x (1 for realism)
  65411. * distortion: number; // from 0 to x (1 for realism)
  65412. * grain_amount: number; // from 0 to 1
  65413. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  65414. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  65415. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  65416. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  65417. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  65418. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  65419. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  65420. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  65421. * }
  65422. * Note: if an effect parameter is unset, effect is disabled
  65423. *
  65424. * @param {string} name - The rendering pipeline name
  65425. * @param {object} parameters - An object containing all parameters (see above)
  65426. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65427. * @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)
  65428. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65429. */
  65430. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  65431. if (ratio === void 0) { ratio = 1.0; }
  65432. var _this = _super.call(this, scene.getEngine(), name) || this;
  65433. // Lens effects can be of the following:
  65434. // - chromatic aberration (slight shift of RGB colors)
  65435. // - blur on the edge of the lens
  65436. // - lens distortion
  65437. // - depth-of-field blur & highlights enhancing
  65438. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  65439. // - grain effect (noise or custom texture)
  65440. // Two additional texture samplers are needed:
  65441. // - depth map (for depth-of-field)
  65442. // - grain texture
  65443. /**
  65444. * The chromatic aberration PostProcess id in the pipeline
  65445. * @type {string}
  65446. */
  65447. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  65448. /**
  65449. * The highlights enhancing PostProcess id in the pipeline
  65450. * @type {string}
  65451. */
  65452. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  65453. /**
  65454. * The depth-of-field PostProcess id in the pipeline
  65455. * @type {string}
  65456. */
  65457. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  65458. _this._scene = scene;
  65459. // Fetch texture samplers
  65460. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65461. if (parameters.grain_texture) {
  65462. _this._grainTexture = parameters.grain_texture;
  65463. }
  65464. else {
  65465. _this._createGrainTexture();
  65466. }
  65467. // save parameters
  65468. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  65469. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  65470. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  65471. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  65472. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  65473. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  65474. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  65475. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  65476. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  65477. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  65478. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  65479. // Create effects
  65480. _this._createChromaticAberrationPostProcess(ratio);
  65481. _this._createHighlightsPostProcess(ratio);
  65482. _this._createDepthOfFieldPostProcess(ratio / 4);
  65483. // Set up pipeline
  65484. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  65485. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  65486. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  65487. if (_this._highlightsGain === -1) {
  65488. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  65489. }
  65490. // Finish
  65491. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65492. if (cameras) {
  65493. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65494. }
  65495. return _this;
  65496. }
  65497. // public methods (self explanatory)
  65498. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  65499. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  65500. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  65501. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  65502. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  65503. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  65504. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  65505. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  65506. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  65507. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  65508. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  65509. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  65510. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  65511. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  65512. };
  65513. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  65514. this._highlightsPostProcess.updateEffect();
  65515. };
  65516. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  65517. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  65518. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  65519. this._highlightsGain = amount;
  65520. };
  65521. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  65522. if (this._highlightsGain === -1) {
  65523. this._highlightsGain = 1.0;
  65524. }
  65525. this._highlightsThreshold = amount;
  65526. };
  65527. LensRenderingPipeline.prototype.disableHighlights = function () {
  65528. this._highlightsGain = -1;
  65529. };
  65530. /**
  65531. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  65532. */
  65533. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65534. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65535. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65536. this._chromaticAberrationPostProcess = null;
  65537. this._highlightsPostProcess = null;
  65538. this._depthOfFieldPostProcess = null;
  65539. this._grainTexture.dispose();
  65540. if (disableDepthRender)
  65541. this._scene.disableDepthRenderer();
  65542. };
  65543. // colors shifting and distortion
  65544. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  65545. var _this = this;
  65546. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  65547. [], // samplers
  65548. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65549. this._chromaticAberrationPostProcess.onApply = function (effect) {
  65550. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  65551. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65552. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65553. };
  65554. };
  65555. // highlights enhancing
  65556. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  65557. var _this = this;
  65558. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  65559. [], // samplers
  65560. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  65561. this._highlightsPostProcess.onApply = function (effect) {
  65562. effect.setFloat('gain', _this._highlightsGain);
  65563. effect.setFloat('threshold', _this._highlightsThreshold);
  65564. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  65565. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65566. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65567. };
  65568. };
  65569. // colors shifting and distortion
  65570. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  65571. var _this = this;
  65572. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  65573. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  65574. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  65575. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65576. this._depthOfFieldPostProcess.onApply = function (effect) {
  65577. effect.setTexture("depthSampler", _this._depthTexture);
  65578. effect.setTexture("grainSampler", _this._grainTexture);
  65579. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  65580. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  65581. effect.setFloat('grain_amount', _this._grainAmount);
  65582. effect.setBool('blur_noise', _this._blurNoise);
  65583. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65584. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65585. effect.setFloat('distortion', _this._distortion);
  65586. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  65587. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  65588. effect.setFloat('aperture', _this._dofAperture);
  65589. effect.setFloat('darken', _this._dofDarken);
  65590. effect.setFloat('edge_blur', _this._edgeBlur);
  65591. effect.setBool('highlights', (_this._highlightsGain !== -1));
  65592. if (_this._scene.activeCamera) {
  65593. effect.setFloat('near', _this._scene.activeCamera.minZ);
  65594. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  65595. }
  65596. };
  65597. };
  65598. // creates a black and white random noise texture, 512x512
  65599. LensRenderingPipeline.prototype._createGrainTexture = function () {
  65600. var size = 512;
  65601. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65602. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65603. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65604. var context = this._grainTexture.getContext();
  65605. var rand = function (min, max) {
  65606. return Math.random() * (max - min) + min;
  65607. };
  65608. var value;
  65609. for (var x = 0; x < size; x++) {
  65610. for (var y = 0; y < size; y++) {
  65611. value = Math.floor(rand(0.42, 0.58) * 255);
  65612. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  65613. context.fillRect(x, y, 1, 1);
  65614. }
  65615. }
  65616. this._grainTexture.update(false);
  65617. };
  65618. return LensRenderingPipeline;
  65619. }(BABYLON.PostProcessRenderPipeline));
  65620. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  65621. })(BABYLON || (BABYLON = {}));
  65622. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  65623. var BABYLON;
  65624. (function (BABYLON) {
  65625. var StandardRenderingPipeline = /** @class */ (function (_super) {
  65626. __extends(StandardRenderingPipeline, _super);
  65627. /**
  65628. * @constructor
  65629. * @param {string} name - The rendering pipeline name
  65630. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65631. * @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)
  65632. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  65633. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65634. */
  65635. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  65636. if (originalPostProcess === void 0) { originalPostProcess = null; }
  65637. var _this = _super.call(this, scene.getEngine(), name) || this;
  65638. _this.downSampleX4PostProcess = null;
  65639. _this.brightPassPostProcess = null;
  65640. _this.blurHPostProcesses = [];
  65641. _this.blurVPostProcesses = [];
  65642. _this.textureAdderPostProcess = null;
  65643. _this.volumetricLightPostProcess = null;
  65644. _this.volumetricLightSmoothXPostProcess = null;
  65645. _this.volumetricLightSmoothYPostProcess = null;
  65646. _this.volumetricLightMergePostProces = null;
  65647. _this.volumetricLightFinalPostProcess = null;
  65648. _this.luminancePostProcess = null;
  65649. _this.luminanceDownSamplePostProcesses = [];
  65650. _this.hdrPostProcess = null;
  65651. _this.textureAdderFinalPostProcess = null;
  65652. _this.lensFlareFinalPostProcess = null;
  65653. _this.hdrFinalPostProcess = null;
  65654. _this.lensFlarePostProcess = null;
  65655. _this.lensFlareComposePostProcess = null;
  65656. _this.motionBlurPostProcess = null;
  65657. _this.depthOfFieldPostProcess = null;
  65658. // Values
  65659. _this.brightThreshold = 1.0;
  65660. _this.blurWidth = 512.0;
  65661. _this.horizontalBlur = false;
  65662. _this.exposure = 1.0;
  65663. _this.lensTexture = null;
  65664. _this.volumetricLightCoefficient = 0.2;
  65665. _this.volumetricLightPower = 4.0;
  65666. _this.volumetricLightBlurScale = 64.0;
  65667. _this.sourceLight = null;
  65668. _this.hdrMinimumLuminance = 1.0;
  65669. _this.hdrDecreaseRate = 0.5;
  65670. _this.hdrIncreaseRate = 0.5;
  65671. _this.lensColorTexture = null;
  65672. _this.lensFlareStrength = 20.0;
  65673. _this.lensFlareGhostDispersal = 1.4;
  65674. _this.lensFlareHaloWidth = 0.7;
  65675. _this.lensFlareDistortionStrength = 16.0;
  65676. _this.lensStarTexture = null;
  65677. _this.lensFlareDirtTexture = null;
  65678. _this.depthOfFieldDistance = 10.0;
  65679. _this.depthOfFieldBlurWidth = 64.0;
  65680. _this.motionStrength = 1.0;
  65681. // IAnimatable
  65682. _this.animations = [];
  65683. _this._currentDepthOfFieldSource = null;
  65684. _this._hdrCurrentLuminance = 1.0;
  65685. // Getters and setters
  65686. _this._bloomEnabled = true;
  65687. _this._depthOfFieldEnabled = false;
  65688. _this._vlsEnabled = false;
  65689. _this._lensFlareEnabled = false;
  65690. _this._hdrEnabled = false;
  65691. _this._motionBlurEnabled = false;
  65692. _this._motionBlurSamples = 64.0;
  65693. _this._volumetricLightStepsCount = 50.0;
  65694. _this._cameras = cameras || [];
  65695. // Initialize
  65696. _this._scene = scene;
  65697. _this._basePostProcess = originalPostProcess;
  65698. _this._ratio = ratio;
  65699. // Misc
  65700. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65701. // Finish
  65702. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65703. _this._buildPipeline();
  65704. return _this;
  65705. }
  65706. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  65707. get: function () {
  65708. return this._bloomEnabled;
  65709. },
  65710. set: function (enabled) {
  65711. if (this._bloomEnabled === enabled) {
  65712. return;
  65713. }
  65714. this._bloomEnabled = enabled;
  65715. this._buildPipeline();
  65716. },
  65717. enumerable: true,
  65718. configurable: true
  65719. });
  65720. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  65721. get: function () {
  65722. return this._depthOfFieldEnabled;
  65723. },
  65724. set: function (enabled) {
  65725. if (this._depthOfFieldEnabled === enabled) {
  65726. return;
  65727. }
  65728. this._depthOfFieldEnabled = enabled;
  65729. this._buildPipeline();
  65730. },
  65731. enumerable: true,
  65732. configurable: true
  65733. });
  65734. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  65735. get: function () {
  65736. return this._lensFlareEnabled;
  65737. },
  65738. set: function (enabled) {
  65739. if (this._lensFlareEnabled === enabled) {
  65740. return;
  65741. }
  65742. this._lensFlareEnabled = enabled;
  65743. this._buildPipeline();
  65744. },
  65745. enumerable: true,
  65746. configurable: true
  65747. });
  65748. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  65749. get: function () {
  65750. return this._hdrEnabled;
  65751. },
  65752. set: function (enabled) {
  65753. if (this._hdrEnabled === enabled) {
  65754. return;
  65755. }
  65756. this._hdrEnabled = enabled;
  65757. this._buildPipeline();
  65758. },
  65759. enumerable: true,
  65760. configurable: true
  65761. });
  65762. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  65763. get: function () {
  65764. return this._vlsEnabled;
  65765. },
  65766. set: function (enabled) {
  65767. if (this._vlsEnabled === enabled) {
  65768. return;
  65769. }
  65770. if (enabled) {
  65771. var geometry = this._scene.enableGeometryBufferRenderer();
  65772. if (!geometry) {
  65773. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  65774. return;
  65775. }
  65776. }
  65777. this._vlsEnabled = enabled;
  65778. this._buildPipeline();
  65779. },
  65780. enumerable: true,
  65781. configurable: true
  65782. });
  65783. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  65784. get: function () {
  65785. return this._motionBlurEnabled;
  65786. },
  65787. set: function (enabled) {
  65788. if (this._motionBlurEnabled === enabled) {
  65789. return;
  65790. }
  65791. this._motionBlurEnabled = enabled;
  65792. this._buildPipeline();
  65793. },
  65794. enumerable: true,
  65795. configurable: true
  65796. });
  65797. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  65798. get: function () {
  65799. return this._volumetricLightStepsCount;
  65800. },
  65801. set: function (count) {
  65802. if (this.volumetricLightPostProcess) {
  65803. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  65804. }
  65805. this._volumetricLightStepsCount = count;
  65806. },
  65807. enumerable: true,
  65808. configurable: true
  65809. });
  65810. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  65811. get: function () {
  65812. return this._motionBlurSamples;
  65813. },
  65814. set: function (samples) {
  65815. if (this.motionBlurPostProcess) {
  65816. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  65817. }
  65818. this._motionBlurSamples = samples;
  65819. },
  65820. enumerable: true,
  65821. configurable: true
  65822. });
  65823. StandardRenderingPipeline.prototype._buildPipeline = function () {
  65824. var _this = this;
  65825. var ratio = this._ratio;
  65826. var scene = this._scene;
  65827. this._disposePostProcesses();
  65828. this._reset();
  65829. // Create pass post-process
  65830. if (!this._basePostProcess) {
  65831. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  65832. this.originalPostProcess.onApply = function (effect) {
  65833. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  65834. };
  65835. }
  65836. else {
  65837. this.originalPostProcess = this._basePostProcess;
  65838. }
  65839. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  65840. this._currentDepthOfFieldSource = this.originalPostProcess;
  65841. if (this._vlsEnabled) {
  65842. // Create volumetric light
  65843. this._createVolumetricLightPostProcess(scene, ratio);
  65844. // Create volumetric light final post-process
  65845. 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);
  65846. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  65847. }
  65848. if (this._bloomEnabled) {
  65849. // Create down sample X4 post-process
  65850. this._createDownSampleX4PostProcess(scene, ratio / 2);
  65851. // Create bright pass post-process
  65852. this._createBrightPassPostProcess(scene, ratio / 2);
  65853. // Create gaussian blur post-processes (down sampling blurs)
  65854. this._createBlurPostProcesses(scene, ratio / 4, 1);
  65855. // Create texture adder post-process
  65856. this._createTextureAdderPostProcess(scene, ratio);
  65857. // Create depth-of-field source post-process
  65858. 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);
  65859. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  65860. }
  65861. if (this._lensFlareEnabled) {
  65862. // Create lens flare post-process
  65863. this._createLensFlarePostProcess(scene, ratio);
  65864. // Create depth-of-field source post-process post lens-flare and disable it now
  65865. 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);
  65866. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  65867. }
  65868. if (this._hdrEnabled) {
  65869. // Create luminance
  65870. this._createLuminancePostProcesses(scene, this._floatTextureType);
  65871. // Create HDR
  65872. this._createHdrPostProcess(scene, ratio);
  65873. // Create depth-of-field source post-process post hdr and disable it now
  65874. 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);
  65875. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  65876. }
  65877. if (this._depthOfFieldEnabled) {
  65878. // Create gaussian blur used by depth-of-field
  65879. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  65880. // Create depth-of-field post-process
  65881. this._createDepthOfFieldPostProcess(scene, ratio);
  65882. }
  65883. if (this._motionBlurEnabled) {
  65884. // Create motion blur post-process
  65885. this._createMotionBlurPostProcess(scene, ratio);
  65886. }
  65887. if (this._cameras !== null) {
  65888. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  65889. }
  65890. };
  65891. // Down Sample X4 Post-Processs
  65892. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  65893. var _this = this;
  65894. var downSampleX4Offsets = new Array(32);
  65895. 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);
  65896. this.downSampleX4PostProcess.onApply = function (effect) {
  65897. var id = 0;
  65898. var width = _this.downSampleX4PostProcess.width;
  65899. var height = _this.downSampleX4PostProcess.height;
  65900. for (var i = -2; i < 2; i++) {
  65901. for (var j = -2; j < 2; j++) {
  65902. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  65903. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  65904. id += 2;
  65905. }
  65906. }
  65907. effect.setArray2("dsOffsets", downSampleX4Offsets);
  65908. };
  65909. // Add to pipeline
  65910. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  65911. };
  65912. // Brightpass Post-Process
  65913. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  65914. var _this = this;
  65915. var brightOffsets = new Array(8);
  65916. 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);
  65917. this.brightPassPostProcess.onApply = function (effect) {
  65918. var sU = (1.0 / _this.brightPassPostProcess.width);
  65919. var sV = (1.0 / _this.brightPassPostProcess.height);
  65920. brightOffsets[0] = -0.5 * sU;
  65921. brightOffsets[1] = 0.5 * sV;
  65922. brightOffsets[2] = 0.5 * sU;
  65923. brightOffsets[3] = 0.5 * sV;
  65924. brightOffsets[4] = -0.5 * sU;
  65925. brightOffsets[5] = -0.5 * sV;
  65926. brightOffsets[6] = 0.5 * sU;
  65927. brightOffsets[7] = -0.5 * sV;
  65928. effect.setArray2("dsOffsets", brightOffsets);
  65929. effect.setFloat("brightThreshold", _this.brightThreshold);
  65930. };
  65931. // Add to pipeline
  65932. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  65933. };
  65934. // Create blur H&V post-processes
  65935. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  65936. var _this = this;
  65937. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  65938. var engine = scene.getEngine();
  65939. 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);
  65940. 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);
  65941. blurX.onActivateObservable.add(function () {
  65942. var dw = blurX.width / engine.getRenderWidth();
  65943. blurX.kernel = _this[blurWidthKey] * dw;
  65944. });
  65945. blurY.onActivateObservable.add(function () {
  65946. var dw = blurY.height / engine.getRenderHeight();
  65947. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  65948. });
  65949. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  65950. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  65951. this.blurHPostProcesses.push(blurX);
  65952. this.blurVPostProcesses.push(blurY);
  65953. };
  65954. // Create texture adder post-process
  65955. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  65956. var _this = this;
  65957. 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);
  65958. this.textureAdderPostProcess.onApply = function (effect) {
  65959. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  65960. effect.setTexture("lensSampler", _this.lensTexture);
  65961. effect.setFloat("exposure", _this.exposure);
  65962. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  65963. };
  65964. // Add to pipeline
  65965. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  65966. };
  65967. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  65968. var _this = this;
  65969. var geometryRenderer = scene.enableGeometryBufferRenderer();
  65970. geometryRenderer.enablePosition = true;
  65971. var geometry = geometryRenderer.getGBuffer();
  65972. // Base post-process
  65973. 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));
  65974. var depthValues = BABYLON.Vector2.Zero();
  65975. this.volumetricLightPostProcess.onApply = function (effect) {
  65976. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  65977. var generator = _this.sourceLight.getShadowGenerator();
  65978. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  65979. effect.setTexture("positionSampler", geometry.textures[2]);
  65980. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  65981. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  65982. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  65983. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  65984. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  65985. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  65986. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  65987. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  65988. effect.setVector2("depthValues", depthValues);
  65989. }
  65990. };
  65991. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  65992. // Smooth
  65993. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  65994. // Merge
  65995. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  65996. this.volumetricLightMergePostProces.onApply = function (effect) {
  65997. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  65998. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  65999. };
  66000. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  66001. };
  66002. // Create luminance
  66003. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  66004. var _this = this;
  66005. // Create luminance
  66006. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  66007. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  66008. var offsets = [];
  66009. this.luminancePostProcess.onApply = function (effect) {
  66010. var sU = (1.0 / _this.luminancePostProcess.width);
  66011. var sV = (1.0 / _this.luminancePostProcess.height);
  66012. offsets[0] = -0.5 * sU;
  66013. offsets[1] = 0.5 * sV;
  66014. offsets[2] = 0.5 * sU;
  66015. offsets[3] = 0.5 * sV;
  66016. offsets[4] = -0.5 * sU;
  66017. offsets[5] = -0.5 * sV;
  66018. offsets[6] = 0.5 * sU;
  66019. offsets[7] = -0.5 * sV;
  66020. effect.setArray2("lumOffsets", offsets);
  66021. };
  66022. // Add to pipeline
  66023. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  66024. // Create down sample luminance
  66025. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  66026. var size = Math.pow(3, i);
  66027. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  66028. if (i === 0) {
  66029. defines += "#define FINAL_DOWN_SAMPLER";
  66030. }
  66031. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  66032. this.luminanceDownSamplePostProcesses.push(postProcess);
  66033. }
  66034. // Create callbacks and add effects
  66035. var lastLuminance = this.luminancePostProcess;
  66036. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  66037. var downSampleOffsets = new Array(18);
  66038. pp.onApply = function (effect) {
  66039. if (!lastLuminance) {
  66040. return;
  66041. }
  66042. var id = 0;
  66043. for (var x = -1; x < 2; x++) {
  66044. for (var y = -1; y < 2; y++) {
  66045. downSampleOffsets[id] = x / lastLuminance.width;
  66046. downSampleOffsets[id + 1] = y / lastLuminance.height;
  66047. id += 2;
  66048. }
  66049. }
  66050. effect.setArray2("dsOffsets", downSampleOffsets);
  66051. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  66052. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  66053. lastLuminance = _this.luminancePostProcess;
  66054. }
  66055. else {
  66056. lastLuminance = pp;
  66057. }
  66058. };
  66059. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  66060. pp.onAfterRender = function (effect) {
  66061. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  66062. 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);
  66063. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  66064. };
  66065. }
  66066. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  66067. });
  66068. };
  66069. // Create HDR post-process
  66070. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  66071. var _this = this;
  66072. 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);
  66073. var outputLiminance = 1;
  66074. var time = 0;
  66075. var lastTime = 0;
  66076. this.hdrPostProcess.onApply = function (effect) {
  66077. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  66078. time += scene.getEngine().getDeltaTime();
  66079. if (outputLiminance < 0) {
  66080. outputLiminance = _this._hdrCurrentLuminance;
  66081. }
  66082. else {
  66083. var dt = (lastTime - time) / 1000.0;
  66084. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  66085. outputLiminance += _this.hdrDecreaseRate * dt;
  66086. }
  66087. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  66088. outputLiminance -= _this.hdrIncreaseRate * dt;
  66089. }
  66090. else {
  66091. outputLiminance = _this._hdrCurrentLuminance;
  66092. }
  66093. }
  66094. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  66095. effect.setFloat("averageLuminance", outputLiminance);
  66096. lastTime = time;
  66097. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  66098. };
  66099. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  66100. };
  66101. // Create lens flare post-process
  66102. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  66103. var _this = this;
  66104. 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);
  66105. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  66106. this._createBlurPostProcesses(scene, ratio / 4, 2);
  66107. 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);
  66108. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  66109. var resolution = new BABYLON.Vector2(0, 0);
  66110. // Lens flare
  66111. this.lensFlarePostProcess.onApply = function (effect) {
  66112. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  66113. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  66114. effect.setFloat("strength", _this.lensFlareStrength);
  66115. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  66116. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  66117. // Shift
  66118. resolution.x = _this.lensFlarePostProcess.width;
  66119. resolution.y = _this.lensFlarePostProcess.height;
  66120. effect.setVector2("resolution", resolution);
  66121. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  66122. };
  66123. // Compose
  66124. 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);
  66125. 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);
  66126. this.lensFlareComposePostProcess.onApply = function (effect) {
  66127. if (!_this._scene.activeCamera) {
  66128. return;
  66129. }
  66130. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66131. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  66132. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  66133. // Lens start rotation matrix
  66134. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  66135. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  66136. 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));
  66137. camRot *= 4.0;
  66138. 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);
  66139. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  66140. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  66141. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  66142. };
  66143. };
  66144. // Create depth-of-field post-process
  66145. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  66146. var _this = this;
  66147. 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);
  66148. this.depthOfFieldPostProcess.onApply = function (effect) {
  66149. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66150. effect.setTexture("depthSampler", _this._getDepthTexture());
  66151. effect.setFloat("distance", _this.depthOfFieldDistance);
  66152. };
  66153. // Add to pipeline
  66154. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  66155. };
  66156. // Create motion blur post-process
  66157. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  66158. var _this = this;
  66159. 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);
  66160. var motionScale = 0;
  66161. var prevViewProjection = BABYLON.Matrix.Identity();
  66162. var invViewProjection = BABYLON.Matrix.Identity();
  66163. var viewProjection = BABYLON.Matrix.Identity();
  66164. var screenSize = BABYLON.Vector2.Zero();
  66165. this.motionBlurPostProcess.onApply = function (effect) {
  66166. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  66167. viewProjection.invertToRef(invViewProjection);
  66168. effect.setMatrix("inverseViewProjection", invViewProjection);
  66169. effect.setMatrix("prevViewProjection", prevViewProjection);
  66170. prevViewProjection = viewProjection;
  66171. screenSize.x = _this.motionBlurPostProcess.width;
  66172. screenSize.y = _this.motionBlurPostProcess.height;
  66173. effect.setVector2("screenSize", screenSize);
  66174. motionScale = scene.getEngine().getFps() / 60.0;
  66175. effect.setFloat("motionScale", motionScale);
  66176. effect.setFloat("motionStrength", _this.motionStrength);
  66177. effect.setTexture("depthSampler", _this._getDepthTexture());
  66178. };
  66179. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  66180. };
  66181. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  66182. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  66183. var renderer = this._scene.enableGeometryBufferRenderer();
  66184. return renderer.getGBuffer().textures[0];
  66185. }
  66186. return this._scene.enableDepthRenderer().getDepthMap();
  66187. };
  66188. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  66189. for (var i = 0; i < this._cameras.length; i++) {
  66190. var camera = this._cameras[i];
  66191. if (this.originalPostProcess) {
  66192. this.originalPostProcess.dispose(camera);
  66193. }
  66194. if (this.downSampleX4PostProcess) {
  66195. this.downSampleX4PostProcess.dispose(camera);
  66196. }
  66197. if (this.brightPassPostProcess) {
  66198. this.brightPassPostProcess.dispose(camera);
  66199. }
  66200. if (this.textureAdderPostProcess) {
  66201. this.textureAdderPostProcess.dispose(camera);
  66202. }
  66203. if (this.textureAdderFinalPostProcess) {
  66204. this.textureAdderFinalPostProcess.dispose(camera);
  66205. }
  66206. if (this.volumetricLightPostProcess) {
  66207. this.volumetricLightPostProcess.dispose(camera);
  66208. }
  66209. if (this.volumetricLightSmoothXPostProcess) {
  66210. this.volumetricLightSmoothXPostProcess.dispose(camera);
  66211. }
  66212. if (this.volumetricLightSmoothYPostProcess) {
  66213. this.volumetricLightSmoothYPostProcess.dispose(camera);
  66214. }
  66215. if (this.volumetricLightMergePostProces) {
  66216. this.volumetricLightMergePostProces.dispose(camera);
  66217. }
  66218. if (this.volumetricLightFinalPostProcess) {
  66219. this.volumetricLightFinalPostProcess.dispose(camera);
  66220. }
  66221. if (this.lensFlarePostProcess) {
  66222. this.lensFlarePostProcess.dispose(camera);
  66223. }
  66224. if (this.lensFlareComposePostProcess) {
  66225. this.lensFlareComposePostProcess.dispose(camera);
  66226. }
  66227. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  66228. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  66229. }
  66230. if (this.luminancePostProcess) {
  66231. this.luminancePostProcess.dispose(camera);
  66232. }
  66233. if (this.hdrPostProcess) {
  66234. this.hdrPostProcess.dispose(camera);
  66235. }
  66236. if (this.hdrFinalPostProcess) {
  66237. this.hdrFinalPostProcess.dispose(camera);
  66238. }
  66239. if (this.depthOfFieldPostProcess) {
  66240. this.depthOfFieldPostProcess.dispose(camera);
  66241. }
  66242. if (this.motionBlurPostProcess) {
  66243. this.motionBlurPostProcess.dispose(camera);
  66244. }
  66245. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  66246. this.blurHPostProcesses[j].dispose(camera);
  66247. }
  66248. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  66249. this.blurVPostProcesses[j].dispose(camera);
  66250. }
  66251. }
  66252. this.originalPostProcess = null;
  66253. this.downSampleX4PostProcess = null;
  66254. this.brightPassPostProcess = null;
  66255. this.textureAdderPostProcess = null;
  66256. this.textureAdderFinalPostProcess = null;
  66257. this.volumetricLightPostProcess = null;
  66258. this.volumetricLightSmoothXPostProcess = null;
  66259. this.volumetricLightSmoothYPostProcess = null;
  66260. this.volumetricLightMergePostProces = null;
  66261. this.volumetricLightFinalPostProcess = null;
  66262. this.lensFlarePostProcess = null;
  66263. this.lensFlareComposePostProcess = null;
  66264. this.luminancePostProcess = null;
  66265. this.hdrPostProcess = null;
  66266. this.hdrFinalPostProcess = null;
  66267. this.depthOfFieldPostProcess = null;
  66268. this.motionBlurPostProcess = null;
  66269. this.luminanceDownSamplePostProcesses = [];
  66270. this.blurHPostProcesses = [];
  66271. this.blurVPostProcesses = [];
  66272. };
  66273. // Dispose
  66274. StandardRenderingPipeline.prototype.dispose = function () {
  66275. this._disposePostProcesses();
  66276. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66277. _super.prototype.dispose.call(this);
  66278. };
  66279. // Serialize rendering pipeline
  66280. StandardRenderingPipeline.prototype.serialize = function () {
  66281. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66282. serializationObject.customType = "StandardRenderingPipeline";
  66283. return serializationObject;
  66284. };
  66285. /**
  66286. * Static members
  66287. */
  66288. // Parse serialized pipeline
  66289. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66290. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  66291. };
  66292. // Luminance steps
  66293. StandardRenderingPipeline.LuminanceSteps = 6;
  66294. __decorate([
  66295. BABYLON.serialize()
  66296. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  66297. __decorate([
  66298. BABYLON.serialize()
  66299. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  66300. __decorate([
  66301. BABYLON.serialize()
  66302. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  66303. __decorate([
  66304. BABYLON.serialize()
  66305. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  66306. __decorate([
  66307. BABYLON.serializeAsTexture("lensTexture")
  66308. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  66309. __decorate([
  66310. BABYLON.serialize()
  66311. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  66312. __decorate([
  66313. BABYLON.serialize()
  66314. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  66315. __decorate([
  66316. BABYLON.serialize()
  66317. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  66318. __decorate([
  66319. BABYLON.serialize()
  66320. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  66321. __decorate([
  66322. BABYLON.serialize()
  66323. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  66324. __decorate([
  66325. BABYLON.serialize()
  66326. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  66327. __decorate([
  66328. BABYLON.serializeAsTexture("lensColorTexture")
  66329. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  66330. __decorate([
  66331. BABYLON.serialize()
  66332. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  66333. __decorate([
  66334. BABYLON.serialize()
  66335. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  66336. __decorate([
  66337. BABYLON.serialize()
  66338. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  66339. __decorate([
  66340. BABYLON.serialize()
  66341. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  66342. __decorate([
  66343. BABYLON.serializeAsTexture("lensStarTexture")
  66344. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  66345. __decorate([
  66346. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  66347. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  66348. __decorate([
  66349. BABYLON.serialize()
  66350. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  66351. __decorate([
  66352. BABYLON.serialize()
  66353. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  66354. __decorate([
  66355. BABYLON.serialize()
  66356. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  66357. __decorate([
  66358. BABYLON.serialize()
  66359. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  66360. __decorate([
  66361. BABYLON.serialize()
  66362. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  66363. __decorate([
  66364. BABYLON.serialize()
  66365. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  66366. __decorate([
  66367. BABYLON.serialize()
  66368. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  66369. __decorate([
  66370. BABYLON.serialize()
  66371. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  66372. __decorate([
  66373. BABYLON.serialize()
  66374. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  66375. __decorate([
  66376. BABYLON.serialize()
  66377. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  66378. __decorate([
  66379. BABYLON.serialize()
  66380. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  66381. __decorate([
  66382. BABYLON.serialize()
  66383. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  66384. return StandardRenderingPipeline;
  66385. }(BABYLON.PostProcessRenderPipeline));
  66386. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  66387. })(BABYLON || (BABYLON = {}));
  66388. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  66389. var BABYLON;
  66390. (function (BABYLON) {
  66391. var FxaaPostProcess = /** @class */ (function (_super) {
  66392. __extends(FxaaPostProcess, _super);
  66393. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  66394. if (camera === void 0) { camera = null; }
  66395. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66396. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  66397. _this.onApplyObservable.add(function (effect) {
  66398. var texelSize = _this.texelSize;
  66399. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  66400. });
  66401. return _this;
  66402. }
  66403. return FxaaPostProcess;
  66404. }(BABYLON.PostProcess));
  66405. BABYLON.FxaaPostProcess = FxaaPostProcess;
  66406. })(BABYLON || (BABYLON = {}));
  66407. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  66408. var BABYLON;
  66409. (function (BABYLON) {
  66410. /**
  66411. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  66412. */
  66413. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  66414. __extends(CircleOfConfusionPostProcess, _super);
  66415. /**
  66416. * Creates a new instance of @see CircleOfConfusionPostProcess
  66417. * @param name The name of the effect.
  66418. * @param scene The scene the effect belongs to.
  66419. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  66420. * @param options The required width/height ratio to downsize to before computing the render pass.
  66421. * @param camera The camera to apply the render pass to.
  66422. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66423. * @param engine The engine which the post process will be applied. (default: current engine)
  66424. * @param reusable If the post process can be reused on the same frame. (default: false)
  66425. * @param textureType Type of textures used when performing the post process. (default: 0)
  66426. */
  66427. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  66428. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66429. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  66430. /**
  66431. * 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.
  66432. */
  66433. _this.lensSize = 50;
  66434. /**
  66435. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66436. */
  66437. _this.fStop = 1.4;
  66438. /**
  66439. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66440. */
  66441. _this.focusDistance = 2000;
  66442. /**
  66443. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  66444. */
  66445. _this.focalLength = 50;
  66446. _this.onApplyObservable.add(function (effect) {
  66447. effect.setTexture("depthSampler", depthTexture);
  66448. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  66449. var aperture = _this.lensSize / _this.fStop;
  66450. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  66451. effect.setFloat('focusDistance', _this.focusDistance);
  66452. effect.setFloat('cocPrecalculation', cocPrecalculation);
  66453. if (scene.activeCamera) {
  66454. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  66455. }
  66456. });
  66457. return _this;
  66458. }
  66459. return CircleOfConfusionPostProcess;
  66460. }(BABYLON.PostProcess));
  66461. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  66462. })(BABYLON || (BABYLON = {}));
  66463. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  66464. var BABYLON;
  66465. (function (BABYLON) {
  66466. /**
  66467. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  66468. */
  66469. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  66470. __extends(DepthOfFieldMergePostProcess, _super);
  66471. /**
  66472. * Creates a new instance of @see CircleOfConfusionPostProcess
  66473. * @param name The name of the effect.
  66474. * @param original The non-blurred image to be modified
  66475. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  66476. * @param blurSteps Incrimental bluring post processes.
  66477. * @param options The required width/height ratio to downsize to before computing the render pass.
  66478. * @param camera The camera to apply the render pass to.
  66479. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66480. * @param engine The engine which the post process will be applied. (default: current engine)
  66481. * @param reusable If the post process can be reused on the same frame. (default: false)
  66482. * @param textureType Type of textures used when performing the post process. (default: 0)
  66483. */
  66484. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  66485. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66486. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  66487. _this.onApplyObservable.add(function (effect) {
  66488. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  66489. effect.setTextureFromPostProcess("originalSampler", original);
  66490. blurSteps.forEach(function (step, index) {
  66491. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  66492. });
  66493. });
  66494. return _this;
  66495. }
  66496. return DepthOfFieldMergePostProcess;
  66497. }(BABYLON.PostProcess));
  66498. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  66499. })(BABYLON || (BABYLON = {}));
  66500. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  66501. var BABYLON;
  66502. (function (BABYLON) {
  66503. /**
  66504. * Specifies the level of max blur that should be applied when using the depth of field effect
  66505. */
  66506. var DepthOfFieldEffectBlurLevel;
  66507. (function (DepthOfFieldEffectBlurLevel) {
  66508. /**
  66509. * Subtle blur
  66510. */
  66511. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  66512. /**
  66513. * Medium blur
  66514. */
  66515. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  66516. /**
  66517. * Large blur
  66518. */
  66519. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  66520. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  66521. ;
  66522. /**
  66523. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  66524. */
  66525. var DepthOfFieldEffect = /** @class */ (function (_super) {
  66526. __extends(DepthOfFieldEffect, _super);
  66527. /**
  66528. * Creates a new instance of @see DepthOfFieldEffect
  66529. * @param scene The scene the effect belongs to.
  66530. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  66531. */
  66532. function DepthOfFieldEffect(scene, blurLevel, pipelineTextureType) {
  66533. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  66534. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  66535. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  66536. // Enable and get current depth map
  66537. var depthMap = scene.enableDepthRenderer().getDepthMap();
  66538. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  66539. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66540. // Capture circle of confusion texture
  66541. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66542. _this._depthOfFieldPass.autoClear = false;
  66543. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  66544. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  66545. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  66546. _this._depthOfFieldBlurY = [];
  66547. _this._depthOfFieldBlurX = [];
  66548. var blurCount = 1;
  66549. var kernelSize = 15;
  66550. switch (blurLevel) {
  66551. case DepthOfFieldEffectBlurLevel.High: {
  66552. blurCount = 3;
  66553. kernelSize = 51;
  66554. break;
  66555. }
  66556. case DepthOfFieldEffectBlurLevel.Medium: {
  66557. blurCount = 2;
  66558. kernelSize = 31;
  66559. break;
  66560. }
  66561. default: {
  66562. kernelSize = 15;
  66563. blurCount = 1;
  66564. break;
  66565. }
  66566. }
  66567. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  66568. for (var i = 0; i < blurCount; i++) {
  66569. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66570. blurY.autoClear = false;
  66571. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66572. blurX.autoClear = false;
  66573. _this._depthOfFieldBlurY.push(blurY);
  66574. _this._depthOfFieldBlurX.push(blurX);
  66575. }
  66576. // Merge blurred images with original image based on circleOfConfusion
  66577. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66578. _this._depthOfFieldMerge.autoClear = false;
  66579. // Set all post processes on the effect.
  66580. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  66581. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  66582. effects.push(_this._depthOfFieldBlurY[i]);
  66583. effects.push(_this._depthOfFieldBlurX[i]);
  66584. }
  66585. effects.push(_this._depthOfFieldMerge);
  66586. return effects;
  66587. }, true) || this;
  66588. return _this;
  66589. }
  66590. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  66591. get: function () {
  66592. return this._circleOfConfusion.focalLength;
  66593. },
  66594. /**
  66595. * The focal the length of the camera used in the effect
  66596. */
  66597. set: function (value) {
  66598. this._circleOfConfusion.focalLength = value;
  66599. },
  66600. enumerable: true,
  66601. configurable: true
  66602. });
  66603. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  66604. get: function () {
  66605. return this._circleOfConfusion.fStop;
  66606. },
  66607. /**
  66608. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66609. */
  66610. set: function (value) {
  66611. this._circleOfConfusion.fStop = value;
  66612. },
  66613. enumerable: true,
  66614. configurable: true
  66615. });
  66616. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  66617. get: function () {
  66618. return this._circleOfConfusion.focusDistance;
  66619. },
  66620. /**
  66621. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66622. */
  66623. set: function (value) {
  66624. this._circleOfConfusion.focusDistance = value;
  66625. },
  66626. enumerable: true,
  66627. configurable: true
  66628. });
  66629. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  66630. get: function () {
  66631. return this._circleOfConfusion.lensSize;
  66632. },
  66633. /**
  66634. * 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.
  66635. */
  66636. set: function (value) {
  66637. this._circleOfConfusion.lensSize = value;
  66638. },
  66639. enumerable: true,
  66640. configurable: true
  66641. });
  66642. /**
  66643. * Disposes each of the internal effects for a given camera.
  66644. * @param camera The camera to dispose the effect on.
  66645. */
  66646. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  66647. this._depthOfFieldPass.dispose(camera);
  66648. this._circleOfConfusion.dispose(camera);
  66649. this._depthOfFieldBlurX.forEach(function (element) {
  66650. element.dispose(camera);
  66651. });
  66652. this._depthOfFieldBlurY.forEach(function (element) {
  66653. element.dispose(camera);
  66654. });
  66655. this._depthOfFieldMerge.dispose(camera);
  66656. };
  66657. return DepthOfFieldEffect;
  66658. }(BABYLON.PostProcessRenderEffect));
  66659. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  66660. })(BABYLON || (BABYLON = {}));
  66661. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  66662. var BABYLON;
  66663. (function (BABYLON) {
  66664. /**
  66665. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  66666. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  66667. */
  66668. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  66669. __extends(DefaultRenderingPipeline, _super);
  66670. /**
  66671. * @constructor
  66672. * @param {string} name - The rendering pipeline name
  66673. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66674. * @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)
  66675. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66676. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  66677. */
  66678. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  66679. if (automaticBuild === void 0) { automaticBuild = true; }
  66680. var _this = _super.call(this, scene.getEngine(), name) || this;
  66681. /**
  66682. * ID of the pass post process used for bloom,
  66683. */
  66684. _this.PassPostProcessId = "PassPostProcessEffect";
  66685. /**
  66686. * ID of the highlight post process used for bloom,
  66687. */
  66688. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  66689. /**
  66690. * ID of the blurX post process used for bloom,
  66691. */
  66692. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  66693. /**
  66694. * ID of the blurY post process used for bloom,
  66695. */
  66696. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  66697. /**
  66698. * ID of the copy back post process used for bloom,
  66699. */
  66700. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  66701. /**
  66702. * ID of the image processing post process;
  66703. */
  66704. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  66705. /**
  66706. * ID of the Fast Approximate Anti-Aliasing post process;
  66707. */
  66708. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  66709. /**
  66710. * ID of the final merge post process;
  66711. */
  66712. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  66713. /**
  66714. * Animations which can be used to tweak settings over a period of time
  66715. */
  66716. _this.animations = [];
  66717. // Values
  66718. _this._bloomEnabled = false;
  66719. _this._depthOfFieldEnabled = false;
  66720. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  66721. _this._fxaaEnabled = false;
  66722. _this._imageProcessingEnabled = true;
  66723. _this._bloomScale = 0.6;
  66724. _this._buildAllowed = true;
  66725. /**
  66726. * Specifies the size of the bloom blur kernel, relative to the final output size
  66727. */
  66728. _this.bloomKernel = 64;
  66729. /**
  66730. * Specifies the weight of the bloom in the final rendering
  66731. */
  66732. _this._bloomWeight = 0.15;
  66733. _this._cameras = cameras || [];
  66734. _this._buildAllowed = automaticBuild;
  66735. // Initialize
  66736. _this._scene = scene;
  66737. var caps = _this._scene.getEngine().getCaps();
  66738. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  66739. // Misc
  66740. if (_this._hdr) {
  66741. if (caps.textureHalfFloatRender) {
  66742. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66743. }
  66744. else if (caps.textureFloatRender) {
  66745. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66746. }
  66747. }
  66748. else {
  66749. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66750. }
  66751. // Attach
  66752. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66753. _this._buildPipeline();
  66754. return _this;
  66755. }
  66756. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  66757. get: function () {
  66758. return this._bloomWeight;
  66759. },
  66760. /**
  66761. * The strength of the bloom.
  66762. */
  66763. set: function (value) {
  66764. if (this._bloomWeight === value) {
  66765. return;
  66766. }
  66767. this._bloomWeight = value;
  66768. if (this._hdr && this.copyBack) {
  66769. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  66770. }
  66771. },
  66772. enumerable: true,
  66773. configurable: true
  66774. });
  66775. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  66776. get: function () {
  66777. return this._bloomScale;
  66778. },
  66779. /**
  66780. * The scale of the bloom, lower value will provide better performance.
  66781. */
  66782. set: function (value) {
  66783. if (this._bloomScale === value) {
  66784. return;
  66785. }
  66786. this._bloomScale = value;
  66787. this._buildPipeline();
  66788. },
  66789. enumerable: true,
  66790. configurable: true
  66791. });
  66792. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  66793. get: function () {
  66794. return this._bloomEnabled;
  66795. },
  66796. /**
  66797. * Enable or disable the bloom from the pipeline
  66798. */
  66799. set: function (enabled) {
  66800. if (this._bloomEnabled === enabled) {
  66801. return;
  66802. }
  66803. this._bloomEnabled = enabled;
  66804. this._buildPipeline();
  66805. },
  66806. enumerable: true,
  66807. configurable: true
  66808. });
  66809. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  66810. /**
  66811. * If the depth of field is enabled.
  66812. */
  66813. get: function () {
  66814. return this._depthOfFieldEnabled;
  66815. },
  66816. set: function (enabled) {
  66817. if (this._depthOfFieldEnabled === enabled) {
  66818. return;
  66819. }
  66820. this._depthOfFieldEnabled = enabled;
  66821. this._buildPipeline();
  66822. },
  66823. enumerable: true,
  66824. configurable: true
  66825. });
  66826. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  66827. /**
  66828. * Blur level of the depth of field effect. (Higher blur will effect performance)
  66829. */
  66830. get: function () {
  66831. return this._depthOfFieldBlurLevel;
  66832. },
  66833. set: function (value) {
  66834. if (this._depthOfFieldBlurLevel === value) {
  66835. return;
  66836. }
  66837. this._depthOfFieldBlurLevel = value;
  66838. this._buildPipeline();
  66839. },
  66840. enumerable: true,
  66841. configurable: true
  66842. });
  66843. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  66844. get: function () {
  66845. return this._fxaaEnabled;
  66846. },
  66847. /**
  66848. * If the anti aliasing is enabled.
  66849. */
  66850. set: function (enabled) {
  66851. if (this._fxaaEnabled === enabled) {
  66852. return;
  66853. }
  66854. this._fxaaEnabled = enabled;
  66855. this._buildPipeline();
  66856. },
  66857. enumerable: true,
  66858. configurable: true
  66859. });
  66860. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  66861. get: function () {
  66862. return this._imageProcessingEnabled;
  66863. },
  66864. /**
  66865. * If image processing is enabled.
  66866. */
  66867. set: function (enabled) {
  66868. if (this._imageProcessingEnabled === enabled) {
  66869. return;
  66870. }
  66871. this._imageProcessingEnabled = enabled;
  66872. this._buildPipeline();
  66873. },
  66874. enumerable: true,
  66875. configurable: true
  66876. });
  66877. /**
  66878. * Force the compilation of the entire pipeline.
  66879. */
  66880. DefaultRenderingPipeline.prototype.prepare = function () {
  66881. var previousState = this._buildAllowed;
  66882. this._buildAllowed = true;
  66883. this._buildPipeline();
  66884. this._buildAllowed = previousState;
  66885. };
  66886. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  66887. var _this = this;
  66888. if (!this._buildAllowed) {
  66889. return;
  66890. }
  66891. var engine = this._scene.getEngine();
  66892. this._disposePostProcesses();
  66893. this._reset();
  66894. if (this.depthOfFieldEnabled) {
  66895. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  66896. this.addEffect(this.depthOfField);
  66897. }
  66898. if (this.bloomEnabled) {
  66899. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66900. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  66901. if (!this._hdr) {
  66902. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66903. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  66904. this.highlights.autoClear = false;
  66905. this.highlights.alwaysForcePOT = true;
  66906. }
  66907. 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);
  66908. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  66909. this.blurX.alwaysForcePOT = true;
  66910. this.blurX.autoClear = false;
  66911. this.blurX.onActivateObservable.add(function () {
  66912. var dw = _this.blurX.width / engine.getRenderWidth(true);
  66913. _this.blurX.kernel = _this.bloomKernel * dw;
  66914. });
  66915. 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);
  66916. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  66917. this.blurY.alwaysForcePOT = true;
  66918. this.blurY.autoClear = false;
  66919. this.blurY.onActivateObservable.add(function () {
  66920. var dh = _this.blurY.height / engine.getRenderHeight(true);
  66921. _this.blurY.kernel = _this.bloomKernel * dh;
  66922. });
  66923. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66924. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  66925. this.copyBack.alwaysForcePOT = true;
  66926. if (this._hdr) {
  66927. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  66928. var w = this.bloomWeight;
  66929. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  66930. }
  66931. else {
  66932. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  66933. }
  66934. this.copyBack.autoClear = false;
  66935. }
  66936. if (this._imageProcessingEnabled) {
  66937. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66938. if (this._hdr) {
  66939. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  66940. }
  66941. else {
  66942. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  66943. }
  66944. }
  66945. if (this.fxaaEnabled) {
  66946. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66947. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  66948. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66949. }
  66950. else if (this._hdr && this.imageProcessing) {
  66951. this.finalMerge = this.imageProcessing;
  66952. }
  66953. else {
  66954. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66955. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  66956. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66957. }
  66958. if (this.bloomEnabled) {
  66959. if (this._hdr) {
  66960. this.copyBack.shareOutputWith(this.blurX);
  66961. if (this.imageProcessing) {
  66962. this.imageProcessing.shareOutputWith(this.pass);
  66963. this.imageProcessing.autoClear = false;
  66964. }
  66965. else if (this.fxaa) {
  66966. this.fxaa.shareOutputWith(this.pass);
  66967. }
  66968. else {
  66969. this.finalMerge.shareOutputWith(this.pass);
  66970. }
  66971. }
  66972. else {
  66973. if (this.fxaa) {
  66974. this.fxaa.shareOutputWith(this.pass);
  66975. }
  66976. else {
  66977. this.finalMerge.shareOutputWith(this.pass);
  66978. }
  66979. }
  66980. }
  66981. if (this._cameras !== null) {
  66982. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  66983. }
  66984. };
  66985. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  66986. for (var i = 0; i < this._cameras.length; i++) {
  66987. var camera = this._cameras[i];
  66988. if (this.pass) {
  66989. this.pass.dispose(camera);
  66990. }
  66991. if (this.highlights) {
  66992. this.highlights.dispose(camera);
  66993. }
  66994. if (this.blurX) {
  66995. this.blurX.dispose(camera);
  66996. }
  66997. if (this.blurY) {
  66998. this.blurY.dispose(camera);
  66999. }
  67000. if (this.copyBack) {
  67001. this.copyBack.dispose(camera);
  67002. }
  67003. if (this.imageProcessing) {
  67004. this.imageProcessing.dispose(camera);
  67005. }
  67006. if (this.fxaa) {
  67007. this.fxaa.dispose(camera);
  67008. }
  67009. if (this.finalMerge) {
  67010. this.finalMerge.dispose(camera);
  67011. }
  67012. if (this.depthOfField) {
  67013. this.depthOfField.disposeEffects(camera);
  67014. }
  67015. }
  67016. this.pass = null;
  67017. this.highlights = null;
  67018. this.blurX = null;
  67019. this.blurY = null;
  67020. this.copyBack = null;
  67021. this.imageProcessing = null;
  67022. this.fxaa = null;
  67023. this.finalMerge = null;
  67024. this.depthOfField = null;
  67025. };
  67026. /**
  67027. * Dispose of the pipeline and stop all post processes
  67028. */
  67029. DefaultRenderingPipeline.prototype.dispose = function () {
  67030. this._disposePostProcesses();
  67031. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67032. _super.prototype.dispose.call(this);
  67033. };
  67034. /**
  67035. * Serialize the rendering pipeline (Used when exporting)
  67036. * @returns the serialized object
  67037. */
  67038. DefaultRenderingPipeline.prototype.serialize = function () {
  67039. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67040. serializationObject.customType = "DefaultRenderingPipeline";
  67041. return serializationObject;
  67042. };
  67043. /**
  67044. * Parse the serialized pipeline
  67045. * @param source Source pipeline.
  67046. * @param scene The scene to load the pipeline to.
  67047. * @param rootUrl The URL of the serialized pipeline.
  67048. * @returns An instantiated pipeline from the serialized object.
  67049. */
  67050. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67051. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  67052. };
  67053. __decorate([
  67054. BABYLON.serialize()
  67055. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  67056. __decorate([
  67057. BABYLON.serialize()
  67058. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  67059. __decorate([
  67060. BABYLON.serialize()
  67061. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  67062. __decorate([
  67063. BABYLON.serialize()
  67064. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  67065. __decorate([
  67066. BABYLON.serialize()
  67067. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  67068. __decorate([
  67069. BABYLON.serialize()
  67070. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  67071. __decorate([
  67072. BABYLON.serialize()
  67073. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  67074. __decorate([
  67075. BABYLON.serialize()
  67076. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  67077. __decorate([
  67078. BABYLON.serialize()
  67079. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  67080. __decorate([
  67081. BABYLON.serialize()
  67082. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  67083. return DefaultRenderingPipeline;
  67084. }(BABYLON.PostProcessRenderPipeline));
  67085. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  67086. })(BABYLON || (BABYLON = {}));
  67087. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  67088. var BABYLON;
  67089. (function (BABYLON) {
  67090. /**
  67091. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  67092. */
  67093. var GeometryBufferRenderer = /** @class */ (function () {
  67094. /**
  67095. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  67096. * @param scene The scene the buffer belongs to
  67097. * @param ratio How big is the buffer related to the main canvas.
  67098. */
  67099. function GeometryBufferRenderer(scene, ratio) {
  67100. if (ratio === void 0) { ratio = 1; }
  67101. this._enablePosition = false;
  67102. this._scene = scene;
  67103. this._ratio = ratio;
  67104. // Render target
  67105. this._createRenderTargets();
  67106. }
  67107. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  67108. /**
  67109. * Set the render list (meshes to be rendered) used in the G buffer.
  67110. */
  67111. set: function (meshes) {
  67112. this._multiRenderTarget.renderList = meshes;
  67113. },
  67114. enumerable: true,
  67115. configurable: true
  67116. });
  67117. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  67118. /**
  67119. * Gets wether or not G buffer are supported by the running hardware.
  67120. * This requires draw buffer supports
  67121. */
  67122. get: function () {
  67123. return this._multiRenderTarget.isSupported;
  67124. },
  67125. enumerable: true,
  67126. configurable: true
  67127. });
  67128. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  67129. /**
  67130. * Gets wether or not position are enabled for the G buffer.
  67131. */
  67132. get: function () {
  67133. return this._enablePosition;
  67134. },
  67135. /**
  67136. * Sets wether or not position are enabled for the G buffer.
  67137. */
  67138. set: function (enable) {
  67139. this._enablePosition = enable;
  67140. this.dispose();
  67141. this._createRenderTargets();
  67142. },
  67143. enumerable: true,
  67144. configurable: true
  67145. });
  67146. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  67147. /**
  67148. * Gets the scene associated with the buffer.
  67149. */
  67150. get: function () {
  67151. return this._scene;
  67152. },
  67153. enumerable: true,
  67154. configurable: true
  67155. });
  67156. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  67157. /**
  67158. * Gets the ratio used by the buffer during its creation.
  67159. * How big is the buffer related to the main canvas.
  67160. */
  67161. get: function () {
  67162. return this._ratio;
  67163. },
  67164. enumerable: true,
  67165. configurable: true
  67166. });
  67167. /**
  67168. * Checks wether everything is ready to render a submesh to the G buffer.
  67169. * @param subMesh the submesh to check readiness for
  67170. * @param useInstances is the mesh drawn using instance or not
  67171. * @returns true if ready otherwise false
  67172. */
  67173. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  67174. var material = subMesh.getMaterial();
  67175. if (material && material.disableDepthWrite) {
  67176. return false;
  67177. }
  67178. var defines = [];
  67179. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  67180. var mesh = subMesh.getMesh();
  67181. // Alpha test
  67182. if (material && material.needAlphaTesting()) {
  67183. defines.push("#define ALPHATEST");
  67184. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67185. attribs.push(BABYLON.VertexBuffer.UVKind);
  67186. defines.push("#define UV1");
  67187. }
  67188. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67189. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67190. defines.push("#define UV2");
  67191. }
  67192. }
  67193. // Buffers
  67194. if (this._enablePosition) {
  67195. defines.push("#define POSITION");
  67196. }
  67197. // Bones
  67198. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67199. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67200. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67201. if (mesh.numBoneInfluencers > 4) {
  67202. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67203. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67204. }
  67205. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67206. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67207. }
  67208. else {
  67209. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67210. }
  67211. // Instances
  67212. if (useInstances) {
  67213. defines.push("#define INSTANCES");
  67214. attribs.push("world0");
  67215. attribs.push("world1");
  67216. attribs.push("world2");
  67217. attribs.push("world3");
  67218. }
  67219. // Get correct effect
  67220. var join = defines.join("\n");
  67221. if (this._cachedDefines !== join) {
  67222. this._cachedDefines = join;
  67223. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  67224. }
  67225. return this._effect.isReady();
  67226. };
  67227. /**
  67228. * Gets the current underlying G Buffer.
  67229. * @returns the buffer
  67230. */
  67231. GeometryBufferRenderer.prototype.getGBuffer = function () {
  67232. return this._multiRenderTarget;
  67233. };
  67234. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  67235. /**
  67236. * Gets the number of samples used to render the buffer (anti aliasing).
  67237. */
  67238. get: function () {
  67239. return this._multiRenderTarget.samples;
  67240. },
  67241. /**
  67242. * Sets the number of samples used to render the buffer (anti aliasing).
  67243. */
  67244. set: function (value) {
  67245. this._multiRenderTarget.samples = value;
  67246. },
  67247. enumerable: true,
  67248. configurable: true
  67249. });
  67250. /**
  67251. * Disposes the renderer and frees up associated resources.
  67252. */
  67253. GeometryBufferRenderer.prototype.dispose = function () {
  67254. this.getGBuffer().dispose();
  67255. };
  67256. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  67257. var _this = this;
  67258. var engine = this._scene.getEngine();
  67259. var count = this._enablePosition ? 3 : 2;
  67260. 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 });
  67261. if (!this.isSupported) {
  67262. return;
  67263. }
  67264. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67265. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67266. this._multiRenderTarget.refreshRate = 1;
  67267. this._multiRenderTarget.renderParticles = false;
  67268. this._multiRenderTarget.renderList = null;
  67269. // set default depth value to 1.0 (far away)
  67270. this._multiRenderTarget.onClearObservable.add(function (engine) {
  67271. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  67272. });
  67273. // Custom render function
  67274. var renderSubMesh = function (subMesh) {
  67275. var mesh = subMesh.getRenderingMesh();
  67276. var scene = _this._scene;
  67277. var engine = scene.getEngine();
  67278. var material = subMesh.getMaterial();
  67279. if (!material) {
  67280. return;
  67281. }
  67282. // Culling
  67283. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67284. // Managing instances
  67285. var batch = mesh._getInstancesRenderList(subMesh._id);
  67286. if (batch.mustReturn) {
  67287. return;
  67288. }
  67289. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67290. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  67291. engine.enableEffect(_this._effect);
  67292. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67293. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67294. _this._effect.setMatrix("view", scene.getViewMatrix());
  67295. // Alpha test
  67296. if (material && material.needAlphaTesting()) {
  67297. var alphaTexture = material.getAlphaTestTexture();
  67298. if (alphaTexture) {
  67299. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67300. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67301. }
  67302. }
  67303. // Bones
  67304. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67305. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67306. }
  67307. // Draw
  67308. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67309. }
  67310. };
  67311. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67312. var index;
  67313. if (depthOnlySubMeshes.length) {
  67314. engine.setColorWrite(false);
  67315. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67316. renderSubMesh(depthOnlySubMeshes.data[index]);
  67317. }
  67318. engine.setColorWrite(true);
  67319. }
  67320. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67321. renderSubMesh(opaqueSubMeshes.data[index]);
  67322. }
  67323. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67324. renderSubMesh(alphaTestSubMeshes.data[index]);
  67325. }
  67326. };
  67327. };
  67328. return GeometryBufferRenderer;
  67329. }());
  67330. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  67331. })(BABYLON || (BABYLON = {}));
  67332. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  67333. var BABYLON;
  67334. (function (BABYLON) {
  67335. var RefractionPostProcess = /** @class */ (function (_super) {
  67336. __extends(RefractionPostProcess, _super);
  67337. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  67338. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  67339. _this.color = color;
  67340. _this.depth = depth;
  67341. _this.colorLevel = colorLevel;
  67342. _this.onActivateObservable.add(function (cam) {
  67343. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  67344. });
  67345. _this.onApplyObservable.add(function (effect) {
  67346. effect.setColor3("baseColor", _this.color);
  67347. effect.setFloat("depth", _this.depth);
  67348. effect.setFloat("colorLevel", _this.colorLevel);
  67349. effect.setTexture("refractionSampler", _this._refRexture);
  67350. });
  67351. return _this;
  67352. }
  67353. // Methods
  67354. RefractionPostProcess.prototype.dispose = function (camera) {
  67355. if (this._refRexture) {
  67356. this._refRexture.dispose();
  67357. }
  67358. _super.prototype.dispose.call(this, camera);
  67359. };
  67360. return RefractionPostProcess;
  67361. }(BABYLON.PostProcess));
  67362. BABYLON.RefractionPostProcess = RefractionPostProcess;
  67363. })(BABYLON || (BABYLON = {}));
  67364. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  67365. var BABYLON;
  67366. (function (BABYLON) {
  67367. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  67368. __extends(BlackAndWhitePostProcess, _super);
  67369. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  67370. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  67371. _this.degree = 1;
  67372. _this.onApplyObservable.add(function (effect) {
  67373. effect.setFloat("degree", _this.degree);
  67374. });
  67375. return _this;
  67376. }
  67377. return BlackAndWhitePostProcess;
  67378. }(BABYLON.PostProcess));
  67379. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  67380. })(BABYLON || (BABYLON = {}));
  67381. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  67382. var BABYLON;
  67383. (function (BABYLON) {
  67384. var ConvolutionPostProcess = /** @class */ (function (_super) {
  67385. __extends(ConvolutionPostProcess, _super);
  67386. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  67387. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  67388. _this.kernel = kernel;
  67389. _this.onApply = function (effect) {
  67390. effect.setFloat2("screenSize", _this.width, _this.height);
  67391. effect.setArray("kernel", _this.kernel);
  67392. };
  67393. return _this;
  67394. }
  67395. // Statics
  67396. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  67397. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  67398. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  67399. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  67400. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  67401. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  67402. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  67403. return ConvolutionPostProcess;
  67404. }(BABYLON.PostProcess));
  67405. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  67406. })(BABYLON || (BABYLON = {}));
  67407. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  67408. var BABYLON;
  67409. (function (BABYLON) {
  67410. var FilterPostProcess = /** @class */ (function (_super) {
  67411. __extends(FilterPostProcess, _super);
  67412. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  67413. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  67414. _this.kernelMatrix = kernelMatrix;
  67415. _this.onApply = function (effect) {
  67416. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  67417. };
  67418. return _this;
  67419. }
  67420. return FilterPostProcess;
  67421. }(BABYLON.PostProcess));
  67422. BABYLON.FilterPostProcess = FilterPostProcess;
  67423. })(BABYLON || (BABYLON = {}));
  67424. //# sourceMappingURL=babylon.filterPostProcess.js.map
  67425. var BABYLON;
  67426. (function (BABYLON) {
  67427. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  67428. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  67429. __extends(VolumetricLightScatteringPostProcess, _super);
  67430. /**
  67431. * @constructor
  67432. * @param {string} name - The post-process name
  67433. * @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)
  67434. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  67435. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  67436. * @param {number} samples - The post-process quality, default 100
  67437. * @param {number} samplingMode - The post-process filtering mode
  67438. * @param {BABYLON.Engine} engine - The babylon engine
  67439. * @param {boolean} reusable - If the post-process is reusable
  67440. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  67441. */
  67442. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  67443. if (samples === void 0) { samples = 100; }
  67444. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67445. 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;
  67446. _this._screenCoordinates = BABYLON.Vector2.Zero();
  67447. /**
  67448. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  67449. * @type {Vector3}
  67450. */
  67451. _this.customMeshPosition = BABYLON.Vector3.Zero();
  67452. /**
  67453. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  67454. * @type {boolean}
  67455. */
  67456. _this.useCustomMeshPosition = false;
  67457. /**
  67458. * If the post-process should inverse the light scattering direction
  67459. * @type {boolean}
  67460. */
  67461. _this.invert = true;
  67462. /**
  67463. * Array containing the excluded meshes not rendered in the internal pass
  67464. */
  67465. _this.excludedMeshes = new Array();
  67466. /**
  67467. * Controls the overall intensity of the post-process
  67468. * @type {number}
  67469. */
  67470. _this.exposure = 0.3;
  67471. /**
  67472. * Dissipates each sample's contribution in range [0, 1]
  67473. * @type {number}
  67474. */
  67475. _this.decay = 0.96815;
  67476. /**
  67477. * Controls the overall intensity of each sample
  67478. * @type {number}
  67479. */
  67480. _this.weight = 0.58767;
  67481. /**
  67482. * Controls the density of each sample
  67483. * @type {number}
  67484. */
  67485. _this.density = 0.926;
  67486. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  67487. engine = scene.getEngine();
  67488. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  67489. // Configure mesh
  67490. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  67491. // Configure
  67492. _this._createPass(scene, ratio.passRatio || ratio);
  67493. _this.onActivate = function (camera) {
  67494. if (!_this.isSupported) {
  67495. _this.dispose(camera);
  67496. }
  67497. _this.onActivate = null;
  67498. };
  67499. _this.onApplyObservable.add(function (effect) {
  67500. _this._updateMeshScreenCoordinates(scene);
  67501. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  67502. effect.setFloat("exposure", _this.exposure);
  67503. effect.setFloat("decay", _this.decay);
  67504. effect.setFloat("weight", _this.weight);
  67505. effect.setFloat("density", _this.density);
  67506. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  67507. });
  67508. return _this;
  67509. }
  67510. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  67511. get: function () {
  67512. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67513. return false;
  67514. },
  67515. set: function (useDiffuseColor) {
  67516. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67517. },
  67518. enumerable: true,
  67519. configurable: true
  67520. });
  67521. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  67522. return "VolumetricLightScatteringPostProcess";
  67523. };
  67524. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  67525. var mesh = subMesh.getMesh();
  67526. // Render this.mesh as default
  67527. if (mesh === this.mesh && mesh.material) {
  67528. return mesh.material.isReady(mesh);
  67529. }
  67530. var defines = [];
  67531. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67532. var material = subMesh.getMaterial();
  67533. // Alpha test
  67534. if (material) {
  67535. if (material.needAlphaTesting()) {
  67536. defines.push("#define ALPHATEST");
  67537. }
  67538. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67539. attribs.push(BABYLON.VertexBuffer.UVKind);
  67540. defines.push("#define UV1");
  67541. }
  67542. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67543. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67544. defines.push("#define UV2");
  67545. }
  67546. }
  67547. // Bones
  67548. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67549. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67550. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67551. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67552. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  67553. }
  67554. else {
  67555. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67556. }
  67557. // Instances
  67558. if (useInstances) {
  67559. defines.push("#define INSTANCES");
  67560. attribs.push("world0");
  67561. attribs.push("world1");
  67562. attribs.push("world2");
  67563. attribs.push("world3");
  67564. }
  67565. // Get correct effect
  67566. var join = defines.join("\n");
  67567. if (this._cachedDefines !== join) {
  67568. this._cachedDefines = join;
  67569. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  67570. }
  67571. return this._volumetricLightScatteringPass.isReady();
  67572. };
  67573. /**
  67574. * Sets the new light position for light scattering effect
  67575. * @param {BABYLON.Vector3} The new custom light position
  67576. */
  67577. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  67578. this.customMeshPosition = position;
  67579. };
  67580. /**
  67581. * Returns the light position for light scattering effect
  67582. * @return {BABYLON.Vector3} The custom light position
  67583. */
  67584. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  67585. return this.customMeshPosition;
  67586. };
  67587. /**
  67588. * Disposes the internal assets and detaches the post-process from the camera
  67589. */
  67590. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  67591. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  67592. if (rttIndex !== -1) {
  67593. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  67594. }
  67595. this._volumetricLightScatteringRTT.dispose();
  67596. _super.prototype.dispose.call(this, camera);
  67597. };
  67598. /**
  67599. * Returns the render target texture used by the post-process
  67600. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  67601. */
  67602. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  67603. return this._volumetricLightScatteringRTT;
  67604. };
  67605. // Private methods
  67606. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  67607. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  67608. return true;
  67609. }
  67610. return false;
  67611. };
  67612. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  67613. var _this = this;
  67614. var engine = scene.getEngine();
  67615. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67616. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67617. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67618. this._volumetricLightScatteringRTT.renderList = null;
  67619. this._volumetricLightScatteringRTT.renderParticles = false;
  67620. var camera = this.getCamera();
  67621. if (camera) {
  67622. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67623. }
  67624. else {
  67625. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67626. }
  67627. // Custom render function for submeshes
  67628. var renderSubMesh = function (subMesh) {
  67629. var mesh = subMesh.getRenderingMesh();
  67630. if (_this._meshExcluded(mesh)) {
  67631. return;
  67632. }
  67633. var material = subMesh.getMaterial();
  67634. if (!material) {
  67635. return;
  67636. }
  67637. var scene = mesh.getScene();
  67638. var engine = scene.getEngine();
  67639. // Culling
  67640. engine.setState(material.backFaceCulling);
  67641. // Managing instances
  67642. var batch = mesh._getInstancesRenderList(subMesh._id);
  67643. if (batch.mustReturn) {
  67644. return;
  67645. }
  67646. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67647. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  67648. var effect = _this._volumetricLightScatteringPass;
  67649. if (mesh === _this.mesh) {
  67650. if (subMesh.effect) {
  67651. effect = subMesh.effect;
  67652. }
  67653. else {
  67654. effect = material.getEffect();
  67655. }
  67656. }
  67657. engine.enableEffect(effect);
  67658. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  67659. if (mesh === _this.mesh) {
  67660. material.bind(mesh.getWorldMatrix(), mesh);
  67661. }
  67662. else {
  67663. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  67664. // Alpha test
  67665. if (material && material.needAlphaTesting()) {
  67666. var alphaTexture = material.getAlphaTestTexture();
  67667. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  67668. if (alphaTexture) {
  67669. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67670. }
  67671. }
  67672. // Bones
  67673. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67674. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67675. }
  67676. }
  67677. // Draw
  67678. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  67679. }
  67680. };
  67681. // Render target texture callbacks
  67682. var savedSceneClearColor;
  67683. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  67684. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  67685. savedSceneClearColor = scene.clearColor;
  67686. scene.clearColor = sceneClearColor;
  67687. });
  67688. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  67689. scene.clearColor = savedSceneClearColor;
  67690. });
  67691. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67692. var engine = scene.getEngine();
  67693. var index;
  67694. if (depthOnlySubMeshes.length) {
  67695. engine.setColorWrite(false);
  67696. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67697. renderSubMesh(depthOnlySubMeshes.data[index]);
  67698. }
  67699. engine.setColorWrite(true);
  67700. }
  67701. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67702. renderSubMesh(opaqueSubMeshes.data[index]);
  67703. }
  67704. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67705. renderSubMesh(alphaTestSubMeshes.data[index]);
  67706. }
  67707. if (transparentSubMeshes.length) {
  67708. // Sort sub meshes
  67709. for (index = 0; index < transparentSubMeshes.length; index++) {
  67710. var submesh = transparentSubMeshes.data[index];
  67711. var boundingInfo = submesh.getBoundingInfo();
  67712. if (boundingInfo && scene.activeCamera) {
  67713. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  67714. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  67715. }
  67716. }
  67717. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  67718. sortedArray.sort(function (a, b) {
  67719. // Alpha index first
  67720. if (a._alphaIndex > b._alphaIndex) {
  67721. return 1;
  67722. }
  67723. if (a._alphaIndex < b._alphaIndex) {
  67724. return -1;
  67725. }
  67726. // Then distance to camera
  67727. if (a._distanceToCamera < b._distanceToCamera) {
  67728. return 1;
  67729. }
  67730. if (a._distanceToCamera > b._distanceToCamera) {
  67731. return -1;
  67732. }
  67733. return 0;
  67734. });
  67735. // Render sub meshes
  67736. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67737. for (index = 0; index < sortedArray.length; index++) {
  67738. renderSubMesh(sortedArray[index]);
  67739. }
  67740. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67741. }
  67742. };
  67743. };
  67744. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  67745. var transform = scene.getTransformMatrix();
  67746. var meshPosition;
  67747. if (this.useCustomMeshPosition) {
  67748. meshPosition = this.customMeshPosition;
  67749. }
  67750. else if (this.attachedNode) {
  67751. meshPosition = this.attachedNode.position;
  67752. }
  67753. else {
  67754. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  67755. }
  67756. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  67757. this._screenCoordinates.x = pos.x / this._viewPort.width;
  67758. this._screenCoordinates.y = pos.y / this._viewPort.height;
  67759. if (this.invert)
  67760. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  67761. };
  67762. // Static methods
  67763. /**
  67764. * Creates a default mesh for the Volumeric Light Scattering post-process
  67765. * @param {string} The mesh name
  67766. * @param {BABYLON.Scene} The scene where to create the mesh
  67767. * @return {BABYLON.Mesh} the default mesh
  67768. */
  67769. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  67770. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  67771. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  67772. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  67773. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  67774. mesh.material = material;
  67775. return mesh;
  67776. };
  67777. __decorate([
  67778. BABYLON.serializeAsVector3()
  67779. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  67780. __decorate([
  67781. BABYLON.serialize()
  67782. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  67783. __decorate([
  67784. BABYLON.serialize()
  67785. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  67786. __decorate([
  67787. BABYLON.serializeAsMeshReference()
  67788. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  67789. __decorate([
  67790. BABYLON.serialize()
  67791. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  67792. __decorate([
  67793. BABYLON.serialize()
  67794. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  67795. __decorate([
  67796. BABYLON.serialize()
  67797. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  67798. __decorate([
  67799. BABYLON.serialize()
  67800. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  67801. __decorate([
  67802. BABYLON.serialize()
  67803. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  67804. return VolumetricLightScatteringPostProcess;
  67805. }(BABYLON.PostProcess));
  67806. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  67807. })(BABYLON || (BABYLON = {}));
  67808. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  67809. //
  67810. // This post-process allows the modification of rendered colors by using
  67811. // a 'look-up table' (LUT). This effect is also called Color Grading.
  67812. //
  67813. // The object needs to be provided an url to a texture containing the color
  67814. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  67815. // Use an image editing software to tweak the LUT to match your needs.
  67816. //
  67817. // For an example of a color LUT, see here:
  67818. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  67819. // For explanations on color grading, see here:
  67820. // http://udn.epicgames.com/Three/ColorGrading.html
  67821. //
  67822. var BABYLON;
  67823. (function (BABYLON) {
  67824. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  67825. __extends(ColorCorrectionPostProcess, _super);
  67826. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  67827. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  67828. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67829. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  67830. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67831. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67832. _this.onApply = function (effect) {
  67833. effect.setTexture("colorTable", _this._colorTableTexture);
  67834. };
  67835. return _this;
  67836. }
  67837. return ColorCorrectionPostProcess;
  67838. }(BABYLON.PostProcess));
  67839. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  67840. })(BABYLON || (BABYLON = {}));
  67841. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  67842. var BABYLON;
  67843. (function (BABYLON) {
  67844. var TonemappingOperator;
  67845. (function (TonemappingOperator) {
  67846. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  67847. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  67848. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  67849. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  67850. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  67851. ;
  67852. var TonemapPostProcess = /** @class */ (function (_super) {
  67853. __extends(TonemapPostProcess, _super);
  67854. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  67855. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67856. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67857. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  67858. _this._operator = _operator;
  67859. _this.exposureAdjustment = exposureAdjustment;
  67860. var defines = "#define ";
  67861. if (_this._operator === TonemappingOperator.Hable)
  67862. defines += "HABLE_TONEMAPPING";
  67863. else if (_this._operator === TonemappingOperator.Reinhard)
  67864. defines += "REINHARD_TONEMAPPING";
  67865. else if (_this._operator === TonemappingOperator.HejiDawson)
  67866. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  67867. else if (_this._operator === TonemappingOperator.Photographic)
  67868. defines += "PHOTOGRAPHIC_TONEMAPPING";
  67869. //sadly a second call to create the effect.
  67870. _this.updateEffect(defines);
  67871. _this.onApply = function (effect) {
  67872. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  67873. };
  67874. return _this;
  67875. }
  67876. return TonemapPostProcess;
  67877. }(BABYLON.PostProcess));
  67878. BABYLON.TonemapPostProcess = TonemapPostProcess;
  67879. })(BABYLON || (BABYLON = {}));
  67880. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  67881. var BABYLON;
  67882. (function (BABYLON) {
  67883. var DisplayPassPostProcess = /** @class */ (function (_super) {
  67884. __extends(DisplayPassPostProcess, _super);
  67885. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  67886. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  67887. }
  67888. return DisplayPassPostProcess;
  67889. }(BABYLON.PostProcess));
  67890. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  67891. })(BABYLON || (BABYLON = {}));
  67892. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  67893. var BABYLON;
  67894. (function (BABYLON) {
  67895. var HighlightsPostProcess = /** @class */ (function (_super) {
  67896. __extends(HighlightsPostProcess, _super);
  67897. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67898. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67899. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67900. }
  67901. return HighlightsPostProcess;
  67902. }(BABYLON.PostProcess));
  67903. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  67904. })(BABYLON || (BABYLON = {}));
  67905. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  67906. var BABYLON;
  67907. (function (BABYLON) {
  67908. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  67909. __extends(ImageProcessingPostProcess, _super);
  67910. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  67911. if (camera === void 0) { camera = null; }
  67912. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67913. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  67914. _this._fromLinearSpace = true;
  67915. /**
  67916. * Defines cache preventing GC.
  67917. */
  67918. _this._defines = {
  67919. IMAGEPROCESSING: false,
  67920. VIGNETTE: false,
  67921. VIGNETTEBLENDMODEMULTIPLY: false,
  67922. VIGNETTEBLENDMODEOPAQUE: false,
  67923. TONEMAPPING: false,
  67924. CONTRAST: false,
  67925. COLORCURVES: false,
  67926. COLORGRADING: false,
  67927. COLORGRADING3D: false,
  67928. FROMLINEARSPACE: false,
  67929. SAMPLER3DGREENDEPTH: false,
  67930. SAMPLER3DBGRMAP: false,
  67931. IMAGEPROCESSINGPOSTPROCESS: false,
  67932. EXPOSURE: false,
  67933. };
  67934. // Setup the configuration as forced by the constructor. This would then not force the
  67935. // scene materials output in linear space and let untouched the default forward pass.
  67936. if (imageProcessingConfiguration) {
  67937. imageProcessingConfiguration.applyByPostProcess = true;
  67938. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  67939. // This will cause the shader to be compiled
  67940. _this.fromLinearSpace = false;
  67941. }
  67942. else {
  67943. _this._attachImageProcessingConfiguration(null, true);
  67944. _this.imageProcessingConfiguration.applyByPostProcess = true;
  67945. }
  67946. _this.onApply = function (effect) {
  67947. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  67948. };
  67949. return _this;
  67950. }
  67951. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  67952. /**
  67953. * Gets the image processing configuration used either in this material.
  67954. */
  67955. get: function () {
  67956. return this._imageProcessingConfiguration;
  67957. },
  67958. /**
  67959. * Sets the Default image processing configuration used either in the this material.
  67960. *
  67961. * If sets to null, the scene one is in use.
  67962. */
  67963. set: function (value) {
  67964. this._attachImageProcessingConfiguration(value);
  67965. },
  67966. enumerable: true,
  67967. configurable: true
  67968. });
  67969. /**
  67970. * Attaches a new image processing configuration to the PBR Material.
  67971. * @param configuration
  67972. */
  67973. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  67974. var _this = this;
  67975. if (doNotBuild === void 0) { doNotBuild = false; }
  67976. if (configuration === this._imageProcessingConfiguration) {
  67977. return;
  67978. }
  67979. // Detaches observer.
  67980. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  67981. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  67982. }
  67983. // Pick the scene configuration if needed.
  67984. if (!configuration) {
  67985. var scene = null;
  67986. var engine = this.getEngine();
  67987. var camera = this.getCamera();
  67988. if (camera) {
  67989. scene = camera.getScene();
  67990. }
  67991. else if (engine && engine.scenes) {
  67992. var scenes = engine.scenes;
  67993. scene = scenes[scenes.length - 1];
  67994. }
  67995. else {
  67996. scene = BABYLON.Engine.LastCreatedScene;
  67997. }
  67998. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  67999. }
  68000. else {
  68001. this._imageProcessingConfiguration = configuration;
  68002. }
  68003. // Attaches observer.
  68004. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  68005. _this._updateParameters();
  68006. });
  68007. // Ensure the effect will be rebuilt.
  68008. if (!doNotBuild) {
  68009. this._updateParameters();
  68010. }
  68011. };
  68012. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  68013. /**
  68014. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  68015. */
  68016. get: function () {
  68017. return this.imageProcessingConfiguration.colorCurves;
  68018. },
  68019. /**
  68020. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  68021. */
  68022. set: function (value) {
  68023. this.imageProcessingConfiguration.colorCurves = value;
  68024. },
  68025. enumerable: true,
  68026. configurable: true
  68027. });
  68028. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  68029. /**
  68030. * Gets wether the color curves effect is enabled.
  68031. */
  68032. get: function () {
  68033. return this.imageProcessingConfiguration.colorCurvesEnabled;
  68034. },
  68035. /**
  68036. * Sets wether the color curves effect is enabled.
  68037. */
  68038. set: function (value) {
  68039. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  68040. },
  68041. enumerable: true,
  68042. configurable: true
  68043. });
  68044. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  68045. /**
  68046. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  68047. */
  68048. get: function () {
  68049. return this.imageProcessingConfiguration.colorGradingTexture;
  68050. },
  68051. /**
  68052. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  68053. */
  68054. set: function (value) {
  68055. this.imageProcessingConfiguration.colorGradingTexture = value;
  68056. },
  68057. enumerable: true,
  68058. configurable: true
  68059. });
  68060. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  68061. /**
  68062. * Gets wether the color grading effect is enabled.
  68063. */
  68064. get: function () {
  68065. return this.imageProcessingConfiguration.colorGradingEnabled;
  68066. },
  68067. /**
  68068. * Gets wether the color grading effect is enabled.
  68069. */
  68070. set: function (value) {
  68071. this.imageProcessingConfiguration.colorGradingEnabled = value;
  68072. },
  68073. enumerable: true,
  68074. configurable: true
  68075. });
  68076. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  68077. /**
  68078. * Gets exposure used in the effect.
  68079. */
  68080. get: function () {
  68081. return this.imageProcessingConfiguration.exposure;
  68082. },
  68083. /**
  68084. * Sets exposure used in the effect.
  68085. */
  68086. set: function (value) {
  68087. this.imageProcessingConfiguration.exposure = value;
  68088. },
  68089. enumerable: true,
  68090. configurable: true
  68091. });
  68092. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  68093. /**
  68094. * Gets wether tonemapping is enabled or not.
  68095. */
  68096. get: function () {
  68097. return this._imageProcessingConfiguration.toneMappingEnabled;
  68098. },
  68099. /**
  68100. * Sets wether tonemapping is enabled or not
  68101. */
  68102. set: function (value) {
  68103. this._imageProcessingConfiguration.toneMappingEnabled = value;
  68104. },
  68105. enumerable: true,
  68106. configurable: true
  68107. });
  68108. ;
  68109. ;
  68110. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  68111. /**
  68112. * Gets contrast used in the effect.
  68113. */
  68114. get: function () {
  68115. return this.imageProcessingConfiguration.contrast;
  68116. },
  68117. /**
  68118. * Sets contrast used in the effect.
  68119. */
  68120. set: function (value) {
  68121. this.imageProcessingConfiguration.contrast = value;
  68122. },
  68123. enumerable: true,
  68124. configurable: true
  68125. });
  68126. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  68127. /**
  68128. * Gets Vignette stretch size.
  68129. */
  68130. get: function () {
  68131. return this.imageProcessingConfiguration.vignetteStretch;
  68132. },
  68133. /**
  68134. * Sets Vignette stretch size.
  68135. */
  68136. set: function (value) {
  68137. this.imageProcessingConfiguration.vignetteStretch = value;
  68138. },
  68139. enumerable: true,
  68140. configurable: true
  68141. });
  68142. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  68143. /**
  68144. * Gets Vignette centre X Offset.
  68145. */
  68146. get: function () {
  68147. return this.imageProcessingConfiguration.vignetteCentreX;
  68148. },
  68149. /**
  68150. * Sets Vignette centre X Offset.
  68151. */
  68152. set: function (value) {
  68153. this.imageProcessingConfiguration.vignetteCentreX = value;
  68154. },
  68155. enumerable: true,
  68156. configurable: true
  68157. });
  68158. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  68159. /**
  68160. * Gets Vignette centre Y Offset.
  68161. */
  68162. get: function () {
  68163. return this.imageProcessingConfiguration.vignetteCentreY;
  68164. },
  68165. /**
  68166. * Sets Vignette centre Y Offset.
  68167. */
  68168. set: function (value) {
  68169. this.imageProcessingConfiguration.vignetteCentreY = value;
  68170. },
  68171. enumerable: true,
  68172. configurable: true
  68173. });
  68174. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  68175. /**
  68176. * Gets Vignette weight or intensity of the vignette effect.
  68177. */
  68178. get: function () {
  68179. return this.imageProcessingConfiguration.vignetteWeight;
  68180. },
  68181. /**
  68182. * Sets Vignette weight or intensity of the vignette effect.
  68183. */
  68184. set: function (value) {
  68185. this.imageProcessingConfiguration.vignetteWeight = value;
  68186. },
  68187. enumerable: true,
  68188. configurable: true
  68189. });
  68190. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  68191. /**
  68192. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68193. * if vignetteEnabled is set to true.
  68194. */
  68195. get: function () {
  68196. return this.imageProcessingConfiguration.vignetteColor;
  68197. },
  68198. /**
  68199. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68200. * if vignetteEnabled is set to true.
  68201. */
  68202. set: function (value) {
  68203. this.imageProcessingConfiguration.vignetteColor = value;
  68204. },
  68205. enumerable: true,
  68206. configurable: true
  68207. });
  68208. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  68209. /**
  68210. * Gets Camera field of view used by the Vignette effect.
  68211. */
  68212. get: function () {
  68213. return this.imageProcessingConfiguration.vignetteCameraFov;
  68214. },
  68215. /**
  68216. * Sets Camera field of view used by the Vignette effect.
  68217. */
  68218. set: function (value) {
  68219. this.imageProcessingConfiguration.vignetteCameraFov = value;
  68220. },
  68221. enumerable: true,
  68222. configurable: true
  68223. });
  68224. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  68225. /**
  68226. * Gets the vignette blend mode allowing different kind of effect.
  68227. */
  68228. get: function () {
  68229. return this.imageProcessingConfiguration.vignetteBlendMode;
  68230. },
  68231. /**
  68232. * Sets the vignette blend mode allowing different kind of effect.
  68233. */
  68234. set: function (value) {
  68235. this.imageProcessingConfiguration.vignetteBlendMode = value;
  68236. },
  68237. enumerable: true,
  68238. configurable: true
  68239. });
  68240. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  68241. /**
  68242. * Gets wether the vignette effect is enabled.
  68243. */
  68244. get: function () {
  68245. return this.imageProcessingConfiguration.vignetteEnabled;
  68246. },
  68247. /**
  68248. * Sets wether the vignette effect is enabled.
  68249. */
  68250. set: function (value) {
  68251. this.imageProcessingConfiguration.vignetteEnabled = value;
  68252. },
  68253. enumerable: true,
  68254. configurable: true
  68255. });
  68256. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  68257. /**
  68258. * Gets wether the input of the processing is in Gamma or Linear Space.
  68259. */
  68260. get: function () {
  68261. return this._fromLinearSpace;
  68262. },
  68263. /**
  68264. * Sets wether the input of the processing is in Gamma or Linear Space.
  68265. */
  68266. set: function (value) {
  68267. if (this._fromLinearSpace === value) {
  68268. return;
  68269. }
  68270. this._fromLinearSpace = value;
  68271. this._updateParameters();
  68272. },
  68273. enumerable: true,
  68274. configurable: true
  68275. });
  68276. ImageProcessingPostProcess.prototype.getClassName = function () {
  68277. return "ImageProcessingPostProcess";
  68278. };
  68279. ImageProcessingPostProcess.prototype._updateParameters = function () {
  68280. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  68281. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  68282. var defines = "";
  68283. for (var define in this._defines) {
  68284. if (this._defines[define]) {
  68285. defines += "#define " + define + ";\r\n";
  68286. }
  68287. }
  68288. var samplers = ["textureSampler"];
  68289. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  68290. var uniforms = ["scale"];
  68291. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  68292. this.updateEffect(defines, uniforms, samplers);
  68293. };
  68294. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  68295. _super.prototype.dispose.call(this, camera);
  68296. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68297. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68298. }
  68299. this.imageProcessingConfiguration.applyByPostProcess = false;
  68300. };
  68301. __decorate([
  68302. BABYLON.serialize()
  68303. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  68304. return ImageProcessingPostProcess;
  68305. }(BABYLON.PostProcess));
  68306. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  68307. })(BABYLON || (BABYLON = {}));
  68308. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  68309. var BABYLON;
  68310. (function (BABYLON) {
  68311. /**
  68312. * The Blur Post Process which blurs an image based on a kernel and direction.
  68313. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68314. */
  68315. var BlurPostProcess = /** @class */ (function (_super) {
  68316. __extends(BlurPostProcess, _super);
  68317. /**
  68318. * Creates a new instance of @see BlurPostProcess
  68319. * @param name The name of the effect.
  68320. * @param direction The direction in which to blur the image.
  68321. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
  68322. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68323. * @param camera The camera to apply the render pass to.
  68324. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68325. * @param engine The engine which the post process will be applied. (default: current engine)
  68326. * @param reusable If the post process can be reused on the same frame. (default: false)
  68327. * @param textureType Type of textures used when performing the post process. (default: 0)
  68328. */
  68329. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  68330. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68331. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68332. if (defines === void 0) { defines = ""; }
  68333. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  68334. _this.direction = direction;
  68335. _this._packedFloat = false;
  68336. _this._staticDefines = "";
  68337. _this._staticDefines = defines;
  68338. _this.onApplyObservable.add(function (effect) {
  68339. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68340. });
  68341. _this.kernel = kernel;
  68342. return _this;
  68343. }
  68344. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68345. /**
  68346. * Gets the length in pixels of the blur sample region
  68347. */
  68348. get: function () {
  68349. return this._idealKernel;
  68350. },
  68351. /**
  68352. * Sets the length in pixels of the blur sample region
  68353. */
  68354. set: function (v) {
  68355. if (this._idealKernel === v) {
  68356. return;
  68357. }
  68358. v = Math.max(v, 1);
  68359. this._idealKernel = v;
  68360. this._kernel = this._nearestBestKernel(v);
  68361. this._updateParameters();
  68362. },
  68363. enumerable: true,
  68364. configurable: true
  68365. });
  68366. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68367. /**
  68368. * Gets wether or not the blur is unpacking/repacking floats
  68369. */
  68370. get: function () {
  68371. return this._packedFloat;
  68372. },
  68373. /**
  68374. * Sets wether or not the blur needs to unpack/repack floats
  68375. */
  68376. set: function (v) {
  68377. if (this._packedFloat === v) {
  68378. return;
  68379. }
  68380. this._packedFloat = v;
  68381. this._updateParameters();
  68382. },
  68383. enumerable: true,
  68384. configurable: true
  68385. });
  68386. BlurPostProcess.prototype._updateParameters = function () {
  68387. // Generate sampling offsets and weights
  68388. var N = this._kernel;
  68389. var centerIndex = (N - 1) / 2;
  68390. // Generate Gaussian sampling weights over kernel
  68391. var offsets = [];
  68392. var weights = [];
  68393. var totalWeight = 0;
  68394. for (var i = 0; i < N; i++) {
  68395. var u = i / (N - 1);
  68396. var w = this._gaussianWeight(u * 2.0 - 1);
  68397. offsets[i] = (i - centerIndex);
  68398. weights[i] = w;
  68399. totalWeight += w;
  68400. }
  68401. // Normalize weights
  68402. for (var i = 0; i < weights.length; i++) {
  68403. weights[i] /= totalWeight;
  68404. }
  68405. // Optimize: combine samples to take advantage of hardware linear sampling
  68406. // Walk from left to center, combining pairs (symmetrically)
  68407. var linearSamplingWeights = [];
  68408. var linearSamplingOffsets = [];
  68409. var linearSamplingMap = [];
  68410. for (var i = 0; i <= centerIndex; i += 2) {
  68411. var j = Math.min(i + 1, Math.floor(centerIndex));
  68412. var singleCenterSample = i === j;
  68413. if (singleCenterSample) {
  68414. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68415. }
  68416. else {
  68417. var sharedCell = j === centerIndex;
  68418. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68419. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68420. if (offsetLinear === 0) {
  68421. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68422. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68423. }
  68424. else {
  68425. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68426. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68427. }
  68428. }
  68429. }
  68430. for (var i = 0; i < linearSamplingMap.length; i++) {
  68431. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68432. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68433. }
  68434. // Replace with optimized
  68435. offsets = linearSamplingOffsets;
  68436. weights = linearSamplingWeights;
  68437. // Generate shaders
  68438. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68439. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68440. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68441. var defines = "";
  68442. defines += this._staticDefines;
  68443. for (var i = 0; i < varyingCount; i++) {
  68444. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68445. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68446. }
  68447. var depCount = 0;
  68448. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68449. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68450. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68451. depCount++;
  68452. }
  68453. if (this.packedFloat) {
  68454. defines += "#define PACKEDFLOAT 1";
  68455. }
  68456. this.updateEffect(defines, null, null, {
  68457. varyingCount: varyingCount,
  68458. depCount: depCount
  68459. });
  68460. };
  68461. /**
  68462. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68463. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68464. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68465. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68466. * The gaps between physical kernels are compensated for in the weighting of the samples
  68467. * @param idealKernel Ideal blur kernel.
  68468. * @return Nearest best kernel.
  68469. */
  68470. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68471. var v = Math.round(idealKernel);
  68472. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68473. var k = _a[_i];
  68474. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68475. return Math.max(k, 3);
  68476. }
  68477. }
  68478. return Math.max(v, 3);
  68479. };
  68480. /**
  68481. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68482. * @param x The point on the Gaussian distribution to sample.
  68483. * @return the value of the Gaussian function at x.
  68484. */
  68485. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68486. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68487. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68488. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68489. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68490. // truncated at around 1.3% of peak strength.
  68491. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68492. var sigma = (1 / 3);
  68493. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68494. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68495. var weight = (1.0 / denominator) * Math.exp(exponent);
  68496. return weight;
  68497. };
  68498. /**
  68499. * Generates a string that can be used as a floating point number in GLSL.
  68500. * @param x Value to print.
  68501. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68502. * @return GLSL float string.
  68503. */
  68504. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68505. if (decimalFigures === void 0) { decimalFigures = 8; }
  68506. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68507. };
  68508. return BlurPostProcess;
  68509. }(BABYLON.PostProcess));
  68510. BABYLON.BlurPostProcess = BlurPostProcess;
  68511. })(BABYLON || (BABYLON = {}));
  68512. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68513. var BABYLON;
  68514. (function (BABYLON) {
  68515. var Bone = /** @class */ (function (_super) {
  68516. __extends(Bone, _super);
  68517. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  68518. if (parentBone === void 0) { parentBone = null; }
  68519. if (localMatrix === void 0) { localMatrix = null; }
  68520. if (restPose === void 0) { restPose = null; }
  68521. if (baseMatrix === void 0) { baseMatrix = null; }
  68522. if (index === void 0) { index = null; }
  68523. var _this = _super.call(this, name, skeleton.getScene()) || this;
  68524. _this.name = name;
  68525. _this.children = new Array();
  68526. _this.animations = new Array();
  68527. // Set this value to map this bone to a different index in the transform matrices.
  68528. // Set this value to -1 to exclude the bone from the transform matrices.
  68529. _this._index = null;
  68530. _this._worldTransform = new BABYLON.Matrix();
  68531. _this._absoluteTransform = new BABYLON.Matrix();
  68532. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  68533. _this._scaleMatrix = BABYLON.Matrix.Identity();
  68534. _this._scaleVector = BABYLON.Vector3.One();
  68535. _this._negateScaleChildren = BABYLON.Vector3.One();
  68536. _this._scalingDeterminant = 1;
  68537. _this._skeleton = skeleton;
  68538. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  68539. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  68540. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  68541. _this._index = index;
  68542. skeleton.bones.push(_this);
  68543. _this.setParent(parentBone, false);
  68544. _this._updateDifferenceMatrix();
  68545. return _this;
  68546. }
  68547. Object.defineProperty(Bone.prototype, "_matrix", {
  68548. get: function () {
  68549. return this._localMatrix;
  68550. },
  68551. set: function (val) {
  68552. if (this._localMatrix) {
  68553. this._localMatrix.copyFrom(val);
  68554. }
  68555. else {
  68556. this._localMatrix = val;
  68557. }
  68558. },
  68559. enumerable: true,
  68560. configurable: true
  68561. });
  68562. // Members
  68563. Bone.prototype.getSkeleton = function () {
  68564. return this._skeleton;
  68565. };
  68566. Bone.prototype.getParent = function () {
  68567. return this._parent;
  68568. };
  68569. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  68570. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68571. if (this._parent === parent) {
  68572. return;
  68573. }
  68574. if (this._parent) {
  68575. var index = this._parent.children.indexOf(this);
  68576. if (index !== -1) {
  68577. this._parent.children.splice(index, 1);
  68578. }
  68579. }
  68580. this._parent = parent;
  68581. if (this._parent) {
  68582. this._parent.children.push(this);
  68583. }
  68584. if (updateDifferenceMatrix) {
  68585. this._updateDifferenceMatrix();
  68586. }
  68587. };
  68588. Bone.prototype.getLocalMatrix = function () {
  68589. return this._localMatrix;
  68590. };
  68591. Bone.prototype.getBaseMatrix = function () {
  68592. return this._baseMatrix;
  68593. };
  68594. Bone.prototype.getRestPose = function () {
  68595. return this._restPose;
  68596. };
  68597. Bone.prototype.returnToRest = function () {
  68598. this.updateMatrix(this._restPose.clone());
  68599. };
  68600. Bone.prototype.getWorldMatrix = function () {
  68601. return this._worldTransform;
  68602. };
  68603. Bone.prototype.getInvertedAbsoluteTransform = function () {
  68604. return this._invertedAbsoluteTransform;
  68605. };
  68606. Bone.prototype.getAbsoluteTransform = function () {
  68607. return this._absoluteTransform;
  68608. };
  68609. Object.defineProperty(Bone.prototype, "position", {
  68610. // Properties (matches AbstractMesh properties)
  68611. get: function () {
  68612. return this.getPosition();
  68613. },
  68614. set: function (newPosition) {
  68615. this.setPosition(newPosition);
  68616. },
  68617. enumerable: true,
  68618. configurable: true
  68619. });
  68620. Object.defineProperty(Bone.prototype, "rotation", {
  68621. get: function () {
  68622. return this.getRotation();
  68623. },
  68624. set: function (newRotation) {
  68625. this.setRotation(newRotation);
  68626. },
  68627. enumerable: true,
  68628. configurable: true
  68629. });
  68630. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  68631. get: function () {
  68632. return this.getRotationQuaternion();
  68633. },
  68634. set: function (newRotation) {
  68635. this.setRotationQuaternion(newRotation);
  68636. },
  68637. enumerable: true,
  68638. configurable: true
  68639. });
  68640. Object.defineProperty(Bone.prototype, "scaling", {
  68641. get: function () {
  68642. return this.getScale();
  68643. },
  68644. set: function (newScaling) {
  68645. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  68646. },
  68647. enumerable: true,
  68648. configurable: true
  68649. });
  68650. // Methods
  68651. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  68652. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68653. this._baseMatrix = matrix.clone();
  68654. this._localMatrix = matrix.clone();
  68655. this._skeleton._markAsDirty();
  68656. if (updateDifferenceMatrix) {
  68657. this._updateDifferenceMatrix();
  68658. }
  68659. };
  68660. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  68661. if (!rootMatrix) {
  68662. rootMatrix = this._baseMatrix;
  68663. }
  68664. if (this._parent) {
  68665. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  68666. }
  68667. else {
  68668. this._absoluteTransform.copyFrom(rootMatrix);
  68669. }
  68670. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  68671. for (var index = 0; index < this.children.length; index++) {
  68672. this.children[index]._updateDifferenceMatrix();
  68673. }
  68674. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  68675. };
  68676. Bone.prototype.markAsDirty = function () {
  68677. this._currentRenderId++;
  68678. this._skeleton._markAsDirty();
  68679. };
  68680. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  68681. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  68682. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  68683. // all animation may be coming from a library skeleton, so may need to create animation
  68684. if (this.animations.length === 0) {
  68685. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  68686. this.animations[0].setKeys([]);
  68687. }
  68688. // get animation info / verify there is such a range from the source bone
  68689. var sourceRange = source.animations[0].getRange(rangeName);
  68690. if (!sourceRange) {
  68691. return false;
  68692. }
  68693. var from = sourceRange.from;
  68694. var to = sourceRange.to;
  68695. var sourceKeys = source.animations[0].getKeys();
  68696. // rescaling prep
  68697. var sourceBoneLength = source.length;
  68698. var sourceParent = source.getParent();
  68699. var parent = this.getParent();
  68700. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  68701. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  68702. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  68703. var destKeys = this.animations[0].getKeys();
  68704. // loop vars declaration
  68705. var orig;
  68706. var origTranslation;
  68707. var mat;
  68708. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  68709. orig = sourceKeys[key];
  68710. if (orig.frame >= from && orig.frame <= to) {
  68711. if (rescaleAsRequired) {
  68712. mat = orig.value.clone();
  68713. // scale based on parent ratio, when bone has parent
  68714. if (parentScalingReqd) {
  68715. origTranslation = mat.getTranslation();
  68716. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  68717. // scale based on skeleton dimension ratio when root bone, and value is passed
  68718. }
  68719. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  68720. origTranslation = mat.getTranslation();
  68721. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  68722. // use original when root bone, and no data for skelDimensionsRatio
  68723. }
  68724. else {
  68725. mat = orig.value;
  68726. }
  68727. }
  68728. else {
  68729. mat = orig.value;
  68730. }
  68731. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  68732. }
  68733. }
  68734. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  68735. return true;
  68736. };
  68737. /**
  68738. * Translate the bone in local or world space.
  68739. * @param vec The amount to translate the bone.
  68740. * @param space The space that the translation is in.
  68741. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68742. */
  68743. Bone.prototype.translate = function (vec, space, mesh) {
  68744. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68745. var lm = this.getLocalMatrix();
  68746. if (space == BABYLON.Space.LOCAL) {
  68747. lm.m[12] += vec.x;
  68748. lm.m[13] += vec.y;
  68749. lm.m[14] += vec.z;
  68750. }
  68751. else {
  68752. var wm = null;
  68753. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68754. if (mesh) {
  68755. wm = mesh.getWorldMatrix();
  68756. }
  68757. this._skeleton.computeAbsoluteTransforms();
  68758. var tmat = Bone._tmpMats[0];
  68759. var tvec = Bone._tmpVecs[0];
  68760. if (this._parent) {
  68761. if (mesh && wm) {
  68762. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68763. tmat.multiplyToRef(wm, tmat);
  68764. }
  68765. else {
  68766. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68767. }
  68768. }
  68769. tmat.m[12] = 0;
  68770. tmat.m[13] = 0;
  68771. tmat.m[14] = 0;
  68772. tmat.invert();
  68773. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  68774. lm.m[12] += tvec.x;
  68775. lm.m[13] += tvec.y;
  68776. lm.m[14] += tvec.z;
  68777. }
  68778. this.markAsDirty();
  68779. };
  68780. /**
  68781. * Set the postion of the bone in local or world space.
  68782. * @param position The position to set the bone.
  68783. * @param space The space that the position is in.
  68784. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68785. */
  68786. Bone.prototype.setPosition = function (position, space, mesh) {
  68787. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68788. var lm = this.getLocalMatrix();
  68789. if (space == BABYLON.Space.LOCAL) {
  68790. lm.m[12] = position.x;
  68791. lm.m[13] = position.y;
  68792. lm.m[14] = position.z;
  68793. }
  68794. else {
  68795. var wm = null;
  68796. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68797. if (mesh) {
  68798. wm = mesh.getWorldMatrix();
  68799. }
  68800. this._skeleton.computeAbsoluteTransforms();
  68801. var tmat = Bone._tmpMats[0];
  68802. var vec = Bone._tmpVecs[0];
  68803. if (this._parent) {
  68804. if (mesh && wm) {
  68805. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68806. tmat.multiplyToRef(wm, tmat);
  68807. }
  68808. else {
  68809. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68810. }
  68811. }
  68812. tmat.invert();
  68813. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  68814. lm.m[12] = vec.x;
  68815. lm.m[13] = vec.y;
  68816. lm.m[14] = vec.z;
  68817. }
  68818. this.markAsDirty();
  68819. };
  68820. /**
  68821. * Set the absolute postion of the bone (world space).
  68822. * @param position The position to set the bone.
  68823. * @param mesh The mesh that this bone is attached to.
  68824. */
  68825. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  68826. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  68827. };
  68828. /**
  68829. * Set the scale of the bone on the x, y and z axes.
  68830. * @param x The scale of the bone on the x axis.
  68831. * @param x The scale of the bone on the y axis.
  68832. * @param z The scale of the bone on the z axis.
  68833. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68834. */
  68835. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  68836. if (scaleChildren === void 0) { scaleChildren = false; }
  68837. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  68838. if (!scaleChildren) {
  68839. this._negateScaleChildren.x = 1 / x;
  68840. this._negateScaleChildren.y = 1 / y;
  68841. this._negateScaleChildren.z = 1 / z;
  68842. }
  68843. this._syncScaleVector();
  68844. }
  68845. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  68846. };
  68847. /**
  68848. * Scale the bone on the x, y and z axes.
  68849. * @param x The amount to scale the bone on the x axis.
  68850. * @param x The amount to scale the bone on the y axis.
  68851. * @param z The amount to scale the bone on the z axis.
  68852. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68853. */
  68854. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  68855. if (scaleChildren === void 0) { scaleChildren = false; }
  68856. var locMat = this.getLocalMatrix();
  68857. var origLocMat = Bone._tmpMats[0];
  68858. origLocMat.copyFrom(locMat);
  68859. var origLocMatInv = Bone._tmpMats[1];
  68860. origLocMatInv.copyFrom(origLocMat);
  68861. origLocMatInv.invert();
  68862. var scaleMat = Bone._tmpMats[2];
  68863. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  68864. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  68865. this._scaleVector.x *= x;
  68866. this._scaleVector.y *= y;
  68867. this._scaleVector.z *= z;
  68868. locMat.multiplyToRef(origLocMatInv, locMat);
  68869. locMat.multiplyToRef(scaleMat, locMat);
  68870. locMat.multiplyToRef(origLocMat, locMat);
  68871. var parent = this.getParent();
  68872. if (parent) {
  68873. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  68874. }
  68875. else {
  68876. this.getAbsoluteTransform().copyFrom(locMat);
  68877. }
  68878. var len = this.children.length;
  68879. scaleMat.invert();
  68880. for (var i = 0; i < len; i++) {
  68881. var child = this.children[i];
  68882. var cm = child.getLocalMatrix();
  68883. cm.multiplyToRef(scaleMat, cm);
  68884. var lm = child.getLocalMatrix();
  68885. lm.m[12] *= x;
  68886. lm.m[13] *= y;
  68887. lm.m[14] *= z;
  68888. }
  68889. this.computeAbsoluteTransforms();
  68890. if (scaleChildren) {
  68891. for (var i = 0; i < len; i++) {
  68892. this.children[i].scale(x, y, z, scaleChildren);
  68893. }
  68894. }
  68895. this.markAsDirty();
  68896. };
  68897. /**
  68898. * Set the yaw, pitch, and roll of the bone in local or world space.
  68899. * @param yaw The rotation of the bone on the y axis.
  68900. * @param pitch The rotation of the bone on the x axis.
  68901. * @param roll The rotation of the bone on the z axis.
  68902. * @param space The space that the axes of rotation are in.
  68903. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68904. */
  68905. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  68906. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68907. var rotMat = Bone._tmpMats[0];
  68908. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  68909. var rotMatInv = Bone._tmpMats[1];
  68910. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68911. rotMatInv.multiplyToRef(rotMat, rotMat);
  68912. this._rotateWithMatrix(rotMat, space, mesh);
  68913. };
  68914. /**
  68915. * Rotate the bone on an axis in local or world space.
  68916. * @param axis The axis to rotate the bone on.
  68917. * @param amount The amount to rotate the bone.
  68918. * @param space The space that the axis is in.
  68919. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68920. */
  68921. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  68922. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68923. var rmat = Bone._tmpMats[0];
  68924. rmat.m[12] = 0;
  68925. rmat.m[13] = 0;
  68926. rmat.m[14] = 0;
  68927. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  68928. this._rotateWithMatrix(rmat, space, mesh);
  68929. };
  68930. /**
  68931. * Set the rotation of the bone to a particular axis angle in local or world space.
  68932. * @param axis The axis to rotate the bone on.
  68933. * @param angle The angle that the bone should be rotated to.
  68934. * @param space The space that the axis is in.
  68935. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68936. */
  68937. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  68938. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68939. var rotMat = Bone._tmpMats[0];
  68940. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  68941. var rotMatInv = Bone._tmpMats[1];
  68942. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68943. rotMatInv.multiplyToRef(rotMat, rotMat);
  68944. this._rotateWithMatrix(rotMat, space, mesh);
  68945. };
  68946. /**
  68947. * Set the euler rotation of the bone in local of world space.
  68948. * @param rotation The euler rotation that the bone should be set to.
  68949. * @param space The space that the rotation is in.
  68950. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68951. */
  68952. Bone.prototype.setRotation = function (rotation, space, mesh) {
  68953. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68954. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  68955. };
  68956. /**
  68957. * Set the quaternion rotation of the bone in local of world space.
  68958. * @param quat The quaternion rotation that the bone should be set to.
  68959. * @param space The space that the rotation is in.
  68960. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68961. */
  68962. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  68963. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68964. var rotMatInv = Bone._tmpMats[0];
  68965. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68966. var rotMat = Bone._tmpMats[1];
  68967. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  68968. rotMatInv.multiplyToRef(rotMat, rotMat);
  68969. this._rotateWithMatrix(rotMat, space, mesh);
  68970. };
  68971. /**
  68972. * Set the rotation matrix of the bone in local of world space.
  68973. * @param rotMat The rotation matrix that the bone should be set to.
  68974. * @param space The space that the rotation is in.
  68975. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68976. */
  68977. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  68978. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68979. var rotMatInv = Bone._tmpMats[0];
  68980. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68981. var rotMat2 = Bone._tmpMats[1];
  68982. rotMat2.copyFrom(rotMat);
  68983. rotMatInv.multiplyToRef(rotMat, rotMat2);
  68984. this._rotateWithMatrix(rotMat2, space, mesh);
  68985. };
  68986. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  68987. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68988. var lmat = this.getLocalMatrix();
  68989. var lx = lmat.m[12];
  68990. var ly = lmat.m[13];
  68991. var lz = lmat.m[14];
  68992. var parent = this.getParent();
  68993. var parentScale = Bone._tmpMats[3];
  68994. var parentScaleInv = Bone._tmpMats[4];
  68995. if (parent) {
  68996. if (space == BABYLON.Space.WORLD) {
  68997. if (mesh) {
  68998. parentScale.copyFrom(mesh.getWorldMatrix());
  68999. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  69000. }
  69001. else {
  69002. parentScale.copyFrom(parent.getAbsoluteTransform());
  69003. }
  69004. }
  69005. else {
  69006. parentScale = parent._scaleMatrix;
  69007. }
  69008. parentScaleInv.copyFrom(parentScale);
  69009. parentScaleInv.invert();
  69010. lmat.multiplyToRef(parentScale, lmat);
  69011. lmat.multiplyToRef(rmat, lmat);
  69012. lmat.multiplyToRef(parentScaleInv, lmat);
  69013. }
  69014. else {
  69015. if (space == BABYLON.Space.WORLD && mesh) {
  69016. parentScale.copyFrom(mesh.getWorldMatrix());
  69017. parentScaleInv.copyFrom(parentScale);
  69018. parentScaleInv.invert();
  69019. lmat.multiplyToRef(parentScale, lmat);
  69020. lmat.multiplyToRef(rmat, lmat);
  69021. lmat.multiplyToRef(parentScaleInv, lmat);
  69022. }
  69023. else {
  69024. lmat.multiplyToRef(rmat, lmat);
  69025. }
  69026. }
  69027. lmat.m[12] = lx;
  69028. lmat.m[13] = ly;
  69029. lmat.m[14] = lz;
  69030. this.computeAbsoluteTransforms();
  69031. this.markAsDirty();
  69032. };
  69033. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  69034. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69035. if (space == BABYLON.Space.WORLD) {
  69036. var scaleMatrix = Bone._tmpMats[2];
  69037. scaleMatrix.copyFrom(this._scaleMatrix);
  69038. rotMatInv.copyFrom(this.getAbsoluteTransform());
  69039. if (mesh) {
  69040. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  69041. var meshScale = Bone._tmpMats[3];
  69042. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  69043. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  69044. }
  69045. rotMatInv.invert();
  69046. scaleMatrix.m[0] *= this._scalingDeterminant;
  69047. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  69048. }
  69049. else {
  69050. rotMatInv.copyFrom(this.getLocalMatrix());
  69051. rotMatInv.invert();
  69052. var scaleMatrix = Bone._tmpMats[2];
  69053. scaleMatrix.copyFrom(this._scaleMatrix);
  69054. if (this._parent) {
  69055. var pscaleMatrix = Bone._tmpMats[3];
  69056. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  69057. pscaleMatrix.invert();
  69058. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  69059. }
  69060. else {
  69061. scaleMatrix.m[0] *= this._scalingDeterminant;
  69062. }
  69063. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  69064. }
  69065. };
  69066. /**
  69067. * Get the scale of the bone
  69068. * @returns the scale of the bone
  69069. */
  69070. Bone.prototype.getScale = function () {
  69071. return this._scaleVector.clone();
  69072. };
  69073. /**
  69074. * Copy the scale of the bone to a vector3.
  69075. * @param result The vector3 to copy the scale to
  69076. */
  69077. Bone.prototype.getScaleToRef = function (result) {
  69078. result.copyFrom(this._scaleVector);
  69079. };
  69080. /**
  69081. * Get the position of the bone in local or world space.
  69082. * @param space The space that the returned position is in.
  69083. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69084. * @returns The position of the bone
  69085. */
  69086. Bone.prototype.getPosition = function (space, mesh) {
  69087. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69088. if (mesh === void 0) { mesh = null; }
  69089. var pos = BABYLON.Vector3.Zero();
  69090. this.getPositionToRef(space, mesh, pos);
  69091. return pos;
  69092. };
  69093. /**
  69094. * Copy the position of the bone to a vector3 in local or world space.
  69095. * @param space The space that the returned position is in.
  69096. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69097. * @param result The vector3 to copy the position to.
  69098. */
  69099. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  69100. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69101. if (space == BABYLON.Space.LOCAL) {
  69102. var lm = this.getLocalMatrix();
  69103. result.x = lm.m[12];
  69104. result.y = lm.m[13];
  69105. result.z = lm.m[14];
  69106. }
  69107. else {
  69108. var wm = null;
  69109. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69110. if (mesh) {
  69111. wm = mesh.getWorldMatrix();
  69112. }
  69113. this._skeleton.computeAbsoluteTransforms();
  69114. var tmat = Bone._tmpMats[0];
  69115. if (mesh && wm) {
  69116. tmat.copyFrom(this.getAbsoluteTransform());
  69117. tmat.multiplyToRef(wm, tmat);
  69118. }
  69119. else {
  69120. tmat = this.getAbsoluteTransform();
  69121. }
  69122. result.x = tmat.m[12];
  69123. result.y = tmat.m[13];
  69124. result.z = tmat.m[14];
  69125. }
  69126. };
  69127. /**
  69128. * Get the absolute position of the bone (world space).
  69129. * @param mesh The mesh that this bone is attached to.
  69130. * @returns The absolute position of the bone
  69131. */
  69132. Bone.prototype.getAbsolutePosition = function (mesh) {
  69133. if (mesh === void 0) { mesh = null; }
  69134. var pos = BABYLON.Vector3.Zero();
  69135. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  69136. return pos;
  69137. };
  69138. /**
  69139. * Copy the absolute position of the bone (world space) to the result param.
  69140. * @param mesh The mesh that this bone is attached to.
  69141. * @param result The vector3 to copy the absolute position to.
  69142. */
  69143. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  69144. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  69145. };
  69146. /**
  69147. * Compute the absolute transforms of this bone and its children.
  69148. */
  69149. Bone.prototype.computeAbsoluteTransforms = function () {
  69150. if (this._parent) {
  69151. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  69152. }
  69153. else {
  69154. this._absoluteTransform.copyFrom(this._localMatrix);
  69155. var poseMatrix = this._skeleton.getPoseMatrix();
  69156. if (poseMatrix) {
  69157. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  69158. }
  69159. }
  69160. var children = this.children;
  69161. var len = children.length;
  69162. for (var i = 0; i < len; i++) {
  69163. children[i].computeAbsoluteTransforms();
  69164. }
  69165. };
  69166. Bone.prototype._syncScaleVector = function () {
  69167. var lm = this.getLocalMatrix();
  69168. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  69169. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  69170. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  69171. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  69172. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  69173. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  69174. this._scaleVector.x = xs * Math.sqrt(xsq);
  69175. this._scaleVector.y = ys * Math.sqrt(ysq);
  69176. this._scaleVector.z = zs * Math.sqrt(zsq);
  69177. if (this._parent) {
  69178. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  69179. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  69180. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  69181. }
  69182. 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);
  69183. };
  69184. /**
  69185. * Get the world direction from an axis that is in the local space of the bone.
  69186. * @param localAxis The local direction that is used to compute the world direction.
  69187. * @param mesh The mesh that this bone is attached to.
  69188. * @returns The world direction
  69189. */
  69190. Bone.prototype.getDirection = function (localAxis, mesh) {
  69191. if (mesh === void 0) { mesh = null; }
  69192. var result = BABYLON.Vector3.Zero();
  69193. this.getDirectionToRef(localAxis, mesh, result);
  69194. return result;
  69195. };
  69196. /**
  69197. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  69198. * @param localAxis The local direction that is used to compute the world direction.
  69199. * @param mesh The mesh that this bone is attached to.
  69200. * @param result The vector3 that the world direction will be copied to.
  69201. */
  69202. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  69203. if (mesh === void 0) { mesh = null; }
  69204. var wm = null;
  69205. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69206. if (mesh) {
  69207. wm = mesh.getWorldMatrix();
  69208. }
  69209. this._skeleton.computeAbsoluteTransforms();
  69210. var mat = Bone._tmpMats[0];
  69211. mat.copyFrom(this.getAbsoluteTransform());
  69212. if (mesh && wm) {
  69213. mat.multiplyToRef(wm, mat);
  69214. }
  69215. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  69216. result.normalize();
  69217. };
  69218. /**
  69219. * Get the euler rotation of the bone in local or world space.
  69220. * @param space The space that the rotation should be in.
  69221. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69222. * @returns The euler rotation
  69223. */
  69224. Bone.prototype.getRotation = function (space, mesh) {
  69225. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69226. if (mesh === void 0) { mesh = null; }
  69227. var result = BABYLON.Vector3.Zero();
  69228. this.getRotationToRef(space, mesh, result);
  69229. return result;
  69230. };
  69231. /**
  69232. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  69233. * @param space The space that the rotation should be in.
  69234. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69235. * @param result The vector3 that the rotation should be copied to.
  69236. */
  69237. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  69238. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69239. if (mesh === void 0) { mesh = null; }
  69240. var quat = Bone._tmpQuat;
  69241. this.getRotationQuaternionToRef(space, mesh, quat);
  69242. quat.toEulerAnglesToRef(result);
  69243. };
  69244. /**
  69245. * Get the quaternion rotation of the bone in either local or world space.
  69246. * @param space The space that the rotation should be in.
  69247. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69248. * @returns The quaternion rotation
  69249. */
  69250. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  69251. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69252. if (mesh === void 0) { mesh = null; }
  69253. var result = BABYLON.Quaternion.Identity();
  69254. this.getRotationQuaternionToRef(space, mesh, result);
  69255. return result;
  69256. };
  69257. /**
  69258. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  69259. * @param space The space that the rotation should be in.
  69260. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69261. * @param result The quaternion that the rotation should be copied to.
  69262. */
  69263. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  69264. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69265. if (mesh === void 0) { mesh = null; }
  69266. if (space == BABYLON.Space.LOCAL) {
  69267. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69268. }
  69269. else {
  69270. var mat = Bone._tmpMats[0];
  69271. var amat = this.getAbsoluteTransform();
  69272. if (mesh) {
  69273. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69274. }
  69275. else {
  69276. mat.copyFrom(amat);
  69277. }
  69278. mat.m[0] *= this._scalingDeterminant;
  69279. mat.m[1] *= this._scalingDeterminant;
  69280. mat.m[2] *= this._scalingDeterminant;
  69281. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69282. }
  69283. };
  69284. /**
  69285. * Get the rotation matrix of the bone in local or world space.
  69286. * @param space The space that the rotation should be in.
  69287. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69288. * @returns The rotation matrix
  69289. */
  69290. Bone.prototype.getRotationMatrix = function (space, mesh) {
  69291. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69292. var result = BABYLON.Matrix.Identity();
  69293. this.getRotationMatrixToRef(space, mesh, result);
  69294. return result;
  69295. };
  69296. /**
  69297. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  69298. * @param space The space that the rotation should be in.
  69299. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69300. * @param result The quaternion that the rotation should be copied to.
  69301. */
  69302. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  69303. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69304. if (space == BABYLON.Space.LOCAL) {
  69305. this.getLocalMatrix().getRotationMatrixToRef(result);
  69306. }
  69307. else {
  69308. var mat = Bone._tmpMats[0];
  69309. var amat = this.getAbsoluteTransform();
  69310. if (mesh) {
  69311. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69312. }
  69313. else {
  69314. mat.copyFrom(amat);
  69315. }
  69316. mat.m[0] *= this._scalingDeterminant;
  69317. mat.m[1] *= this._scalingDeterminant;
  69318. mat.m[2] *= this._scalingDeterminant;
  69319. mat.getRotationMatrixToRef(result);
  69320. }
  69321. };
  69322. /**
  69323. * Get the world position of a point that is in the local space of the bone.
  69324. * @param position The local position
  69325. * @param mesh The mesh that this bone is attached to.
  69326. * @returns The world position
  69327. */
  69328. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  69329. if (mesh === void 0) { mesh = null; }
  69330. var result = BABYLON.Vector3.Zero();
  69331. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  69332. return result;
  69333. };
  69334. /**
  69335. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  69336. * @param position The local position
  69337. * @param mesh The mesh that this bone is attached to.
  69338. * @param result The vector3 that the world position should be copied to.
  69339. */
  69340. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  69341. if (mesh === void 0) { mesh = null; }
  69342. var wm = null;
  69343. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69344. if (mesh) {
  69345. wm = mesh.getWorldMatrix();
  69346. }
  69347. this._skeleton.computeAbsoluteTransforms();
  69348. var tmat = Bone._tmpMats[0];
  69349. if (mesh && wm) {
  69350. tmat.copyFrom(this.getAbsoluteTransform());
  69351. tmat.multiplyToRef(wm, tmat);
  69352. }
  69353. else {
  69354. tmat = this.getAbsoluteTransform();
  69355. }
  69356. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69357. };
  69358. /**
  69359. * Get the local position of a point that is in world space.
  69360. * @param position The world position
  69361. * @param mesh The mesh that this bone is attached to.
  69362. * @returns The local position
  69363. */
  69364. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  69365. if (mesh === void 0) { mesh = null; }
  69366. var result = BABYLON.Vector3.Zero();
  69367. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  69368. return result;
  69369. };
  69370. /**
  69371. * Get the local position of a point that is in world space and copy it to the result param.
  69372. * @param position The world position
  69373. * @param mesh The mesh that this bone is attached to.
  69374. * @param result The vector3 that the local position should be copied to.
  69375. */
  69376. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  69377. if (mesh === void 0) { mesh = null; }
  69378. var wm = null;
  69379. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69380. if (mesh) {
  69381. wm = mesh.getWorldMatrix();
  69382. }
  69383. this._skeleton.computeAbsoluteTransforms();
  69384. var tmat = Bone._tmpMats[0];
  69385. tmat.copyFrom(this.getAbsoluteTransform());
  69386. if (mesh && wm) {
  69387. tmat.multiplyToRef(wm, tmat);
  69388. }
  69389. tmat.invert();
  69390. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69391. };
  69392. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69393. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  69394. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69395. return Bone;
  69396. }(BABYLON.Node));
  69397. BABYLON.Bone = Bone;
  69398. })(BABYLON || (BABYLON = {}));
  69399. //# sourceMappingURL=babylon.bone.js.map
  69400. var BABYLON;
  69401. (function (BABYLON) {
  69402. var BoneIKController = /** @class */ (function () {
  69403. function BoneIKController(mesh, bone, options) {
  69404. this.targetPosition = BABYLON.Vector3.Zero();
  69405. this.poleTargetPosition = BABYLON.Vector3.Zero();
  69406. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  69407. this.poleAngle = 0;
  69408. this.slerpAmount = 1;
  69409. this._bone1Quat = BABYLON.Quaternion.Identity();
  69410. this._bone1Mat = BABYLON.Matrix.Identity();
  69411. this._bone2Ang = Math.PI;
  69412. this._maxAngle = Math.PI;
  69413. this._rightHandedSystem = false;
  69414. this._bendAxis = BABYLON.Vector3.Right();
  69415. this._slerping = false;
  69416. this._adjustRoll = 0;
  69417. this._bone2 = bone;
  69418. this._bone1 = bone.getParent();
  69419. if (!this._bone1) {
  69420. return;
  69421. }
  69422. this.mesh = mesh;
  69423. var bonePos = bone.getPosition();
  69424. if (bone.getAbsoluteTransform().determinant() > 0) {
  69425. this._rightHandedSystem = true;
  69426. this._bendAxis.x = 0;
  69427. this._bendAxis.y = 0;
  69428. this._bendAxis.z = -1;
  69429. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  69430. this._adjustRoll = Math.PI * .5;
  69431. this._bendAxis.z = 1;
  69432. }
  69433. }
  69434. if (this._bone1.length) {
  69435. var boneScale1 = this._bone1.getScale();
  69436. var boneScale2 = this._bone2.getScale();
  69437. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  69438. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  69439. }
  69440. else if (this._bone1.children[0]) {
  69441. mesh.computeWorldMatrix(true);
  69442. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  69443. var pos2 = this._bone2.getAbsolutePosition(mesh);
  69444. var pos3 = this._bone1.getAbsolutePosition(mesh);
  69445. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  69446. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  69447. }
  69448. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  69449. this.maxAngle = Math.PI;
  69450. if (options) {
  69451. if (options.targetMesh) {
  69452. this.targetMesh = options.targetMesh;
  69453. this.targetMesh.computeWorldMatrix(true);
  69454. }
  69455. if (options.poleTargetMesh) {
  69456. this.poleTargetMesh = options.poleTargetMesh;
  69457. this.poleTargetMesh.computeWorldMatrix(true);
  69458. }
  69459. else if (options.poleTargetBone) {
  69460. this.poleTargetBone = options.poleTargetBone;
  69461. }
  69462. else if (this._bone1.getParent()) {
  69463. this.poleTargetBone = this._bone1.getParent();
  69464. }
  69465. if (options.poleTargetLocalOffset) {
  69466. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  69467. }
  69468. if (options.poleAngle) {
  69469. this.poleAngle = options.poleAngle;
  69470. }
  69471. if (options.bendAxis) {
  69472. this._bendAxis.copyFrom(options.bendAxis);
  69473. }
  69474. if (options.maxAngle) {
  69475. this.maxAngle = options.maxAngle;
  69476. }
  69477. if (options.slerpAmount) {
  69478. this.slerpAmount = options.slerpAmount;
  69479. }
  69480. }
  69481. }
  69482. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  69483. get: function () {
  69484. return this._maxAngle;
  69485. },
  69486. set: function (value) {
  69487. this._setMaxAngle(value);
  69488. },
  69489. enumerable: true,
  69490. configurable: true
  69491. });
  69492. BoneIKController.prototype._setMaxAngle = function (ang) {
  69493. if (ang < 0) {
  69494. ang = 0;
  69495. }
  69496. if (ang > Math.PI || ang == undefined) {
  69497. ang = Math.PI;
  69498. }
  69499. this._maxAngle = ang;
  69500. var a = this._bone1Length;
  69501. var b = this._bone2Length;
  69502. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  69503. };
  69504. BoneIKController.prototype.update = function () {
  69505. var bone1 = this._bone1;
  69506. if (!bone1) {
  69507. return;
  69508. }
  69509. var target = this.targetPosition;
  69510. var poleTarget = this.poleTargetPosition;
  69511. var mat1 = BoneIKController._tmpMats[0];
  69512. var mat2 = BoneIKController._tmpMats[1];
  69513. if (this.targetMesh) {
  69514. target.copyFrom(this.targetMesh.getAbsolutePosition());
  69515. }
  69516. if (this.poleTargetBone) {
  69517. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  69518. }
  69519. else if (this.poleTargetMesh) {
  69520. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  69521. }
  69522. var bonePos = BoneIKController._tmpVecs[0];
  69523. var zaxis = BoneIKController._tmpVecs[1];
  69524. var xaxis = BoneIKController._tmpVecs[2];
  69525. var yaxis = BoneIKController._tmpVecs[3];
  69526. var upAxis = BoneIKController._tmpVecs[4];
  69527. var _tmpQuat = BoneIKController._tmpQuat;
  69528. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  69529. poleTarget.subtractToRef(bonePos, upAxis);
  69530. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  69531. upAxis.y = 1;
  69532. }
  69533. else {
  69534. upAxis.normalize();
  69535. }
  69536. target.subtractToRef(bonePos, yaxis);
  69537. yaxis.normalize();
  69538. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  69539. zaxis.normalize();
  69540. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  69541. xaxis.normalize();
  69542. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  69543. var a = this._bone1Length;
  69544. var b = this._bone2Length;
  69545. var c = BABYLON.Vector3.Distance(bonePos, target);
  69546. if (this._maxReach > 0) {
  69547. c = Math.min(this._maxReach, c);
  69548. }
  69549. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  69550. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  69551. if (acosa > 1) {
  69552. acosa = 1;
  69553. }
  69554. if (acosb > 1) {
  69555. acosb = 1;
  69556. }
  69557. if (acosa < -1) {
  69558. acosa = -1;
  69559. }
  69560. if (acosb < -1) {
  69561. acosb = -1;
  69562. }
  69563. var angA = Math.acos(acosa);
  69564. var angB = Math.acos(acosb);
  69565. var angC = -angA - angB;
  69566. if (this._rightHandedSystem) {
  69567. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  69568. mat2.multiplyToRef(mat1, mat1);
  69569. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  69570. mat2.multiplyToRef(mat1, mat1);
  69571. }
  69572. else {
  69573. var _tmpVec = BoneIKController._tmpVecs[5];
  69574. _tmpVec.copyFrom(this._bendAxis);
  69575. _tmpVec.x *= -1;
  69576. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  69577. mat2.multiplyToRef(mat1, mat1);
  69578. }
  69579. if (this.poleAngle) {
  69580. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  69581. mat1.multiplyToRef(mat2, mat1);
  69582. }
  69583. if (this._bone1) {
  69584. if (this.slerpAmount < 1) {
  69585. if (!this._slerping) {
  69586. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  69587. }
  69588. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  69589. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  69590. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  69591. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  69592. this._slerping = true;
  69593. }
  69594. else {
  69595. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  69596. this._bone1Mat.copyFrom(mat1);
  69597. this._slerping = false;
  69598. }
  69599. }
  69600. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  69601. this._bone2Ang = angC;
  69602. };
  69603. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69604. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  69605. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69606. return BoneIKController;
  69607. }());
  69608. BABYLON.BoneIKController = BoneIKController;
  69609. })(BABYLON || (BABYLON = {}));
  69610. //# sourceMappingURL=babylon.boneIKController.js.map
  69611. var BABYLON;
  69612. (function (BABYLON) {
  69613. var BoneLookController = /** @class */ (function () {
  69614. /**
  69615. * Create a BoneLookController
  69616. * @param mesh the mesh that the bone belongs to
  69617. * @param bone the bone that will be looking to the target
  69618. * @param target the target Vector3 to look at
  69619. * @param settings optional settings:
  69620. * - maxYaw: the maximum angle the bone will yaw to
  69621. * - minYaw: the minimum angle the bone will yaw to
  69622. * - maxPitch: the maximum angle the bone will pitch to
  69623. * - minPitch: the minimum angle the bone will yaw to
  69624. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  69625. * - upAxis: the up axis of the coordinate system
  69626. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69627. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  69628. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  69629. * - adjustYaw: used to make an adjustment to the yaw of the bone
  69630. * - adjustPitch: used to make an adjustment to the pitch of the bone
  69631. * - adjustRoll: used to make an adjustment to the roll of the bone
  69632. **/
  69633. function BoneLookController(mesh, bone, target, options) {
  69634. /**
  69635. * The up axis of the coordinate system that is used when the bone is rotated.
  69636. */
  69637. this.upAxis = BABYLON.Vector3.Up();
  69638. /**
  69639. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69640. */
  69641. this.upAxisSpace = BABYLON.Space.LOCAL;
  69642. /**
  69643. * Used to make an adjustment to the yaw of the bone.
  69644. */
  69645. this.adjustYaw = 0;
  69646. /**
  69647. * Used to make an adjustment to the pitch of the bone.
  69648. */
  69649. this.adjustPitch = 0;
  69650. /**
  69651. * Used to make an adjustment to the roll of the bone.
  69652. */
  69653. this.adjustRoll = 0;
  69654. /**
  69655. * 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).
  69656. */
  69657. this.slerpAmount = 1;
  69658. this._boneQuat = BABYLON.Quaternion.Identity();
  69659. this._slerping = false;
  69660. this._firstFrameSkipped = false;
  69661. this._fowardAxis = BABYLON.Vector3.Forward();
  69662. this.mesh = mesh;
  69663. this.bone = bone;
  69664. this.target = target;
  69665. if (options) {
  69666. if (options.adjustYaw) {
  69667. this.adjustYaw = options.adjustYaw;
  69668. }
  69669. if (options.adjustPitch) {
  69670. this.adjustPitch = options.adjustPitch;
  69671. }
  69672. if (options.adjustRoll) {
  69673. this.adjustRoll = options.adjustRoll;
  69674. }
  69675. if (options.maxYaw != null) {
  69676. this.maxYaw = options.maxYaw;
  69677. }
  69678. else {
  69679. this.maxYaw = Math.PI;
  69680. }
  69681. if (options.minYaw != null) {
  69682. this.minYaw = options.minYaw;
  69683. }
  69684. else {
  69685. this.minYaw = -Math.PI;
  69686. }
  69687. if (options.maxPitch != null) {
  69688. this.maxPitch = options.maxPitch;
  69689. }
  69690. else {
  69691. this.maxPitch = Math.PI;
  69692. }
  69693. if (options.minPitch != null) {
  69694. this.minPitch = options.minPitch;
  69695. }
  69696. else {
  69697. this.minPitch = -Math.PI;
  69698. }
  69699. if (options.slerpAmount != null) {
  69700. this.slerpAmount = options.slerpAmount;
  69701. }
  69702. if (options.upAxis != null) {
  69703. this.upAxis = options.upAxis;
  69704. }
  69705. if (options.upAxisSpace != null) {
  69706. this.upAxisSpace = options.upAxisSpace;
  69707. }
  69708. if (options.yawAxis != null || options.pitchAxis != null) {
  69709. var newYawAxis = BABYLON.Axis.Y;
  69710. var newPitchAxis = BABYLON.Axis.X;
  69711. if (options.yawAxis != null) {
  69712. newYawAxis = options.yawAxis.clone();
  69713. newYawAxis.normalize();
  69714. }
  69715. if (options.pitchAxis != null) {
  69716. newPitchAxis = options.pitchAxis.clone();
  69717. newPitchAxis.normalize();
  69718. }
  69719. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  69720. this._transformYawPitch = BABYLON.Matrix.Identity();
  69721. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  69722. this._transformYawPitchInv = this._transformYawPitch.clone();
  69723. this._transformYawPitch.invert();
  69724. }
  69725. }
  69726. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  69727. this.upAxisSpace = BABYLON.Space.LOCAL;
  69728. }
  69729. }
  69730. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  69731. /**
  69732. * Get/set the minimum yaw angle that the bone can look to.
  69733. */
  69734. get: function () {
  69735. return this._minYaw;
  69736. },
  69737. set: function (value) {
  69738. this._minYaw = value;
  69739. this._minYawSin = Math.sin(value);
  69740. this._minYawCos = Math.cos(value);
  69741. if (this._maxYaw != null) {
  69742. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69743. this._yawRange = this._maxYaw - this._minYaw;
  69744. }
  69745. },
  69746. enumerable: true,
  69747. configurable: true
  69748. });
  69749. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  69750. /**
  69751. * Get/set the maximum yaw angle that the bone can look to.
  69752. */
  69753. get: function () {
  69754. return this._maxYaw;
  69755. },
  69756. set: function (value) {
  69757. this._maxYaw = value;
  69758. this._maxYawSin = Math.sin(value);
  69759. this._maxYawCos = Math.cos(value);
  69760. if (this._minYaw != null) {
  69761. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69762. this._yawRange = this._maxYaw - this._minYaw;
  69763. }
  69764. },
  69765. enumerable: true,
  69766. configurable: true
  69767. });
  69768. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  69769. /**
  69770. * Get/set the minimum pitch angle that the bone can look to.
  69771. */
  69772. get: function () {
  69773. return this._minPitch;
  69774. },
  69775. set: function (value) {
  69776. this._minPitch = value;
  69777. this._minPitchTan = Math.tan(value);
  69778. },
  69779. enumerable: true,
  69780. configurable: true
  69781. });
  69782. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  69783. /**
  69784. * Get/set the maximum pitch angle that the bone can look to.
  69785. */
  69786. get: function () {
  69787. return this._maxPitch;
  69788. },
  69789. set: function (value) {
  69790. this._maxPitch = value;
  69791. this._maxPitchTan = Math.tan(value);
  69792. },
  69793. enumerable: true,
  69794. configurable: true
  69795. });
  69796. /**
  69797. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  69798. */
  69799. BoneLookController.prototype.update = function () {
  69800. //skip the first frame when slerping so that the mesh rotation is correct
  69801. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  69802. this._firstFrameSkipped = true;
  69803. return;
  69804. }
  69805. var bone = this.bone;
  69806. var bonePos = BoneLookController._tmpVecs[0];
  69807. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  69808. var target = this.target;
  69809. var _tmpMat1 = BoneLookController._tmpMats[0];
  69810. var _tmpMat2 = BoneLookController._tmpMats[1];
  69811. var mesh = this.mesh;
  69812. var parentBone = bone.getParent();
  69813. var upAxis = BoneLookController._tmpVecs[1];
  69814. upAxis.copyFrom(this.upAxis);
  69815. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  69816. if (this._transformYawPitch) {
  69817. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  69818. }
  69819. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  69820. }
  69821. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  69822. mesh.getDirectionToRef(upAxis, upAxis);
  69823. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  69824. upAxis.normalize();
  69825. }
  69826. }
  69827. var checkYaw = false;
  69828. var checkPitch = false;
  69829. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  69830. checkYaw = true;
  69831. }
  69832. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  69833. checkPitch = true;
  69834. }
  69835. if (checkYaw || checkPitch) {
  69836. var spaceMat = BoneLookController._tmpMats[2];
  69837. var spaceMatInv = BoneLookController._tmpMats[3];
  69838. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  69839. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  69840. }
  69841. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  69842. spaceMat.copyFrom(mesh.getWorldMatrix());
  69843. }
  69844. else {
  69845. var forwardAxis = BoneLookController._tmpVecs[2];
  69846. forwardAxis.copyFrom(this._fowardAxis);
  69847. if (this._transformYawPitch) {
  69848. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  69849. }
  69850. if (parentBone) {
  69851. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  69852. }
  69853. else {
  69854. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  69855. }
  69856. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  69857. rightAxis.normalize();
  69858. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  69859. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  69860. }
  69861. spaceMat.invertToRef(spaceMatInv);
  69862. var xzlen = null;
  69863. if (checkPitch) {
  69864. var localTarget = BoneLookController._tmpVecs[3];
  69865. target.subtractToRef(bonePos, localTarget);
  69866. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69867. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69868. var pitch = Math.atan2(localTarget.y, xzlen);
  69869. var newPitch = pitch;
  69870. if (pitch > this._maxPitch) {
  69871. localTarget.y = this._maxPitchTan * xzlen;
  69872. newPitch = this._maxPitch;
  69873. }
  69874. else if (pitch < this._minPitch) {
  69875. localTarget.y = this._minPitchTan * xzlen;
  69876. newPitch = this._minPitch;
  69877. }
  69878. if (pitch != newPitch) {
  69879. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69880. localTarget.addInPlace(bonePos);
  69881. target = localTarget;
  69882. }
  69883. }
  69884. if (checkYaw) {
  69885. var localTarget = BoneLookController._tmpVecs[4];
  69886. target.subtractToRef(bonePos, localTarget);
  69887. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69888. var yaw = Math.atan2(localTarget.x, localTarget.z);
  69889. var newYaw = yaw;
  69890. if (yaw > this._maxYaw || yaw < this._minYaw) {
  69891. if (xzlen == null) {
  69892. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69893. }
  69894. if (this._yawRange > Math.PI) {
  69895. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  69896. localTarget.z = this._maxYawCos * xzlen;
  69897. localTarget.x = this._maxYawSin * xzlen;
  69898. newYaw = this._maxYaw;
  69899. }
  69900. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  69901. localTarget.z = this._minYawCos * xzlen;
  69902. localTarget.x = this._minYawSin * xzlen;
  69903. newYaw = this._minYaw;
  69904. }
  69905. }
  69906. else {
  69907. if (yaw > this._maxYaw) {
  69908. localTarget.z = this._maxYawCos * xzlen;
  69909. localTarget.x = this._maxYawSin * xzlen;
  69910. newYaw = this._maxYaw;
  69911. }
  69912. else if (yaw < this._minYaw) {
  69913. localTarget.z = this._minYawCos * xzlen;
  69914. localTarget.x = this._minYawSin * xzlen;
  69915. newYaw = this._minYaw;
  69916. }
  69917. }
  69918. }
  69919. if (this._slerping && this._yawRange > Math.PI) {
  69920. //are we going to be crossing into the min/max region?
  69921. var boneFwd = BoneLookController._tmpVecs[8];
  69922. boneFwd.copyFrom(BABYLON.Axis.Z);
  69923. if (this._transformYawPitch) {
  69924. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  69925. }
  69926. var boneRotMat = BoneLookController._tmpMats[4];
  69927. this._boneQuat.toRotationMatrix(boneRotMat);
  69928. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  69929. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  69930. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  69931. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  69932. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  69933. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  69934. if (angBtwTar > angBtwMidYaw) {
  69935. if (xzlen == null) {
  69936. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69937. }
  69938. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  69939. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  69940. if (angBtwMin < angBtwMax) {
  69941. newYaw = boneYaw + Math.PI * .75;
  69942. localTarget.z = Math.cos(newYaw) * xzlen;
  69943. localTarget.x = Math.sin(newYaw) * xzlen;
  69944. }
  69945. else {
  69946. newYaw = boneYaw - Math.PI * .75;
  69947. localTarget.z = Math.cos(newYaw) * xzlen;
  69948. localTarget.x = Math.sin(newYaw) * xzlen;
  69949. }
  69950. }
  69951. }
  69952. if (yaw != newYaw) {
  69953. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69954. localTarget.addInPlace(bonePos);
  69955. target = localTarget;
  69956. }
  69957. }
  69958. }
  69959. var zaxis = BoneLookController._tmpVecs[5];
  69960. var xaxis = BoneLookController._tmpVecs[6];
  69961. var yaxis = BoneLookController._tmpVecs[7];
  69962. var _tmpQuat = BoneLookController._tmpQuat;
  69963. target.subtractToRef(bonePos, zaxis);
  69964. zaxis.normalize();
  69965. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  69966. xaxis.normalize();
  69967. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  69968. yaxis.normalize();
  69969. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  69970. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  69971. return;
  69972. }
  69973. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  69974. return;
  69975. }
  69976. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  69977. return;
  69978. }
  69979. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  69980. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  69981. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  69982. }
  69983. if (this.slerpAmount < 1) {
  69984. if (!this._slerping) {
  69985. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  69986. }
  69987. if (this._transformYawPitch) {
  69988. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  69989. }
  69990. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  69991. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  69992. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  69993. this._slerping = true;
  69994. }
  69995. else {
  69996. if (this._transformYawPitch) {
  69997. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  69998. }
  69999. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  70000. this._slerping = false;
  70001. }
  70002. };
  70003. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  70004. var angDiff = ang2 - ang1;
  70005. angDiff %= Math.PI * 2;
  70006. if (angDiff > Math.PI) {
  70007. angDiff -= Math.PI * 2;
  70008. }
  70009. else if (angDiff < -Math.PI) {
  70010. angDiff += Math.PI * 2;
  70011. }
  70012. return angDiff;
  70013. };
  70014. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  70015. ang1 %= (2 * Math.PI);
  70016. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  70017. ang2 %= (2 * Math.PI);
  70018. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  70019. var ab = 0;
  70020. if (ang1 < ang2) {
  70021. ab = ang2 - ang1;
  70022. }
  70023. else {
  70024. ab = ang1 - ang2;
  70025. }
  70026. if (ab > Math.PI) {
  70027. ab = Math.PI * 2 - ab;
  70028. }
  70029. return ab;
  70030. };
  70031. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  70032. ang %= (2 * Math.PI);
  70033. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  70034. ang1 %= (2 * Math.PI);
  70035. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  70036. ang2 %= (2 * Math.PI);
  70037. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  70038. if (ang1 < ang2) {
  70039. if (ang > ang1 && ang < ang2) {
  70040. return true;
  70041. }
  70042. }
  70043. else {
  70044. if (ang > ang2 && ang < ang1) {
  70045. return true;
  70046. }
  70047. }
  70048. return false;
  70049. };
  70050. 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()];
  70051. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  70052. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70053. return BoneLookController;
  70054. }());
  70055. BABYLON.BoneLookController = BoneLookController;
  70056. })(BABYLON || (BABYLON = {}));
  70057. //# sourceMappingURL=babylon.boneLookController.js.map
  70058. var BABYLON;
  70059. (function (BABYLON) {
  70060. var Skeleton = /** @class */ (function () {
  70061. function Skeleton(name, id, scene) {
  70062. this.name = name;
  70063. this.id = id;
  70064. this.bones = new Array();
  70065. this.needInitialSkinMatrix = false;
  70066. this._isDirty = true;
  70067. this._meshesWithPoseMatrix = new Array();
  70068. this._identity = BABYLON.Matrix.Identity();
  70069. this._ranges = {};
  70070. this._lastAbsoluteTransformsUpdateId = -1;
  70071. // Events
  70072. /**
  70073. * An event triggered before computing the skeleton's matrices
  70074. * @type {BABYLON.Observable}
  70075. */
  70076. this.onBeforeComputeObservable = new BABYLON.Observable();
  70077. this.bones = [];
  70078. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70079. scene.skeletons.push(this);
  70080. //make sure it will recalculate the matrix next time prepare is called.
  70081. this._isDirty = true;
  70082. }
  70083. // Members
  70084. Skeleton.prototype.getTransformMatrices = function (mesh) {
  70085. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  70086. return mesh._bonesTransformMatrices;
  70087. }
  70088. if (!this._transformMatrices) {
  70089. this.prepare();
  70090. }
  70091. return this._transformMatrices;
  70092. };
  70093. Skeleton.prototype.getScene = function () {
  70094. return this._scene;
  70095. };
  70096. // Methods
  70097. /**
  70098. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  70099. */
  70100. Skeleton.prototype.toString = function (fullDetails) {
  70101. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  70102. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  70103. if (fullDetails) {
  70104. ret += ", Ranges: {";
  70105. var first = true;
  70106. for (var name_1 in this._ranges) {
  70107. if (first) {
  70108. ret += ", ";
  70109. first = false;
  70110. }
  70111. ret += name_1;
  70112. }
  70113. ret += "}";
  70114. }
  70115. return ret;
  70116. };
  70117. /**
  70118. * Get bone's index searching by name
  70119. * @param {string} name is bone's name to search for
  70120. * @return {number} Indice of the bone. Returns -1 if not found
  70121. */
  70122. Skeleton.prototype.getBoneIndexByName = function (name) {
  70123. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  70124. if (this.bones[boneIndex].name === name) {
  70125. return boneIndex;
  70126. }
  70127. }
  70128. return -1;
  70129. };
  70130. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  70131. // check name not already in use
  70132. if (!this._ranges[name]) {
  70133. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  70134. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70135. if (this.bones[i].animations[0]) {
  70136. this.bones[i].animations[0].createRange(name, from, to);
  70137. }
  70138. }
  70139. }
  70140. };
  70141. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  70142. if (deleteFrames === void 0) { deleteFrames = true; }
  70143. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70144. if (this.bones[i].animations[0]) {
  70145. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  70146. }
  70147. }
  70148. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  70149. };
  70150. Skeleton.prototype.getAnimationRange = function (name) {
  70151. return this._ranges[name];
  70152. };
  70153. /**
  70154. * Returns as an Array, all AnimationRanges defined on this skeleton
  70155. */
  70156. Skeleton.prototype.getAnimationRanges = function () {
  70157. var animationRanges = [];
  70158. var name;
  70159. var i = 0;
  70160. for (name in this._ranges) {
  70161. animationRanges[i] = this._ranges[name];
  70162. i++;
  70163. }
  70164. return animationRanges;
  70165. };
  70166. /**
  70167. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  70168. */
  70169. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  70170. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70171. if (this._ranges[name] || !source.getAnimationRange(name)) {
  70172. return false;
  70173. }
  70174. var ret = true;
  70175. var frameOffset = this._getHighestAnimationFrame() + 1;
  70176. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  70177. var boneDict = {};
  70178. var sourceBones = source.bones;
  70179. var nBones;
  70180. var i;
  70181. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  70182. boneDict[sourceBones[i].name] = sourceBones[i];
  70183. }
  70184. if (this.bones.length !== sourceBones.length) {
  70185. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  70186. ret = false;
  70187. }
  70188. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  70189. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  70190. var boneName = this.bones[i].name;
  70191. var sourceBone = boneDict[boneName];
  70192. if (sourceBone) {
  70193. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  70194. }
  70195. else {
  70196. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  70197. ret = false;
  70198. }
  70199. }
  70200. // do not call createAnimationRange(), since it also is done to bones, which was already done
  70201. var range = source.getAnimationRange(name);
  70202. if (range) {
  70203. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  70204. }
  70205. return ret;
  70206. };
  70207. Skeleton.prototype.returnToRest = function () {
  70208. for (var index = 0; index < this.bones.length; index++) {
  70209. this.bones[index].returnToRest();
  70210. }
  70211. };
  70212. Skeleton.prototype._getHighestAnimationFrame = function () {
  70213. var ret = 0;
  70214. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70215. if (this.bones[i].animations[0]) {
  70216. var highest = this.bones[i].animations[0].getHighestFrame();
  70217. if (ret < highest) {
  70218. ret = highest;
  70219. }
  70220. }
  70221. }
  70222. return ret;
  70223. };
  70224. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  70225. var range = this.getAnimationRange(name);
  70226. if (!range) {
  70227. return null;
  70228. }
  70229. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  70230. };
  70231. Skeleton.prototype._markAsDirty = function () {
  70232. this._isDirty = true;
  70233. };
  70234. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  70235. this._meshesWithPoseMatrix.push(mesh);
  70236. };
  70237. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  70238. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  70239. if (index > -1) {
  70240. this._meshesWithPoseMatrix.splice(index, 1);
  70241. }
  70242. };
  70243. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  70244. this.onBeforeComputeObservable.notifyObservers(this);
  70245. for (var index = 0; index < this.bones.length; index++) {
  70246. var bone = this.bones[index];
  70247. var parentBone = bone.getParent();
  70248. if (parentBone) {
  70249. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  70250. }
  70251. else {
  70252. if (initialSkinMatrix) {
  70253. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  70254. }
  70255. else {
  70256. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  70257. }
  70258. }
  70259. if (bone._index !== -1) {
  70260. var mappedIndex = bone._index === null ? index : bone._index;
  70261. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  70262. }
  70263. }
  70264. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  70265. };
  70266. Skeleton.prototype.prepare = function () {
  70267. if (!this._isDirty) {
  70268. return;
  70269. }
  70270. if (this.needInitialSkinMatrix) {
  70271. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  70272. var mesh = this._meshesWithPoseMatrix[index];
  70273. var poseMatrix = mesh.getPoseMatrix();
  70274. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  70275. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70276. }
  70277. if (this._synchronizedWithMesh !== mesh) {
  70278. this._synchronizedWithMesh = mesh;
  70279. // Prepare bones
  70280. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  70281. var bone = this.bones[boneIndex];
  70282. if (!bone.getParent()) {
  70283. var matrix = bone.getBaseMatrix();
  70284. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  70285. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  70286. }
  70287. }
  70288. }
  70289. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  70290. }
  70291. }
  70292. else {
  70293. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  70294. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70295. }
  70296. this._computeTransformMatrices(this._transformMatrices, null);
  70297. }
  70298. this._isDirty = false;
  70299. this._scene._activeBones.addCount(this.bones.length, false);
  70300. };
  70301. Skeleton.prototype.getAnimatables = function () {
  70302. if (!this._animatables || this._animatables.length !== this.bones.length) {
  70303. this._animatables = [];
  70304. for (var index = 0; index < this.bones.length; index++) {
  70305. this._animatables.push(this.bones[index]);
  70306. }
  70307. }
  70308. return this._animatables;
  70309. };
  70310. Skeleton.prototype.clone = function (name, id) {
  70311. var result = new Skeleton(name, id || name, this._scene);
  70312. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70313. for (var index = 0; index < this.bones.length; index++) {
  70314. var source = this.bones[index];
  70315. var parentBone = null;
  70316. var parent_1 = source.getParent();
  70317. if (parent_1) {
  70318. var parentIndex = this.bones.indexOf(parent_1);
  70319. parentBone = result.bones[parentIndex];
  70320. }
  70321. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  70322. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  70323. }
  70324. if (this._ranges) {
  70325. result._ranges = {};
  70326. for (var rangeName in this._ranges) {
  70327. var range = this._ranges[rangeName];
  70328. if (range) {
  70329. result._ranges[rangeName] = range.clone();
  70330. }
  70331. }
  70332. }
  70333. this._isDirty = true;
  70334. return result;
  70335. };
  70336. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  70337. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  70338. this.bones.forEach(function (bone) {
  70339. bone.animations.forEach(function (animation) {
  70340. animation.enableBlending = true;
  70341. animation.blendingSpeed = blendingSpeed;
  70342. });
  70343. });
  70344. };
  70345. Skeleton.prototype.dispose = function () {
  70346. this._meshesWithPoseMatrix = [];
  70347. // Animations
  70348. this.getScene().stopAnimation(this);
  70349. // Remove from scene
  70350. this.getScene().removeSkeleton(this);
  70351. };
  70352. Skeleton.prototype.serialize = function () {
  70353. var serializationObject = {};
  70354. serializationObject.name = this.name;
  70355. serializationObject.id = this.id;
  70356. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  70357. serializationObject.bones = [];
  70358. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70359. for (var index = 0; index < this.bones.length; index++) {
  70360. var bone = this.bones[index];
  70361. var parent_2 = bone.getParent();
  70362. var serializedBone = {
  70363. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  70364. name: bone.name,
  70365. matrix: bone.getBaseMatrix().toArray(),
  70366. rest: bone.getRestPose().toArray()
  70367. };
  70368. serializationObject.bones.push(serializedBone);
  70369. if (bone.length) {
  70370. serializedBone.length = bone.length;
  70371. }
  70372. if (bone.animations && bone.animations.length > 0) {
  70373. serializedBone.animation = bone.animations[0].serialize();
  70374. }
  70375. serializationObject.ranges = [];
  70376. for (var name in this._ranges) {
  70377. var source = this._ranges[name];
  70378. if (!source) {
  70379. continue;
  70380. }
  70381. var range = {};
  70382. range.name = name;
  70383. range.from = source.from;
  70384. range.to = source.to;
  70385. serializationObject.ranges.push(range);
  70386. }
  70387. }
  70388. return serializationObject;
  70389. };
  70390. Skeleton.Parse = function (parsedSkeleton, scene) {
  70391. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  70392. if (parsedSkeleton.dimensionsAtRest) {
  70393. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  70394. }
  70395. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  70396. var index;
  70397. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  70398. var parsedBone = parsedSkeleton.bones[index];
  70399. var parentBone = null;
  70400. if (parsedBone.parentBoneIndex > -1) {
  70401. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  70402. }
  70403. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  70404. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  70405. if (parsedBone.length) {
  70406. bone.length = parsedBone.length;
  70407. }
  70408. if (parsedBone.animation) {
  70409. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  70410. }
  70411. }
  70412. // placed after bones, so createAnimationRange can cascade down
  70413. if (parsedSkeleton.ranges) {
  70414. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  70415. var data = parsedSkeleton.ranges[index];
  70416. skeleton.createAnimationRange(data.name, data.from, data.to);
  70417. }
  70418. }
  70419. return skeleton;
  70420. };
  70421. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  70422. if (forceUpdate === void 0) { forceUpdate = false; }
  70423. var renderId = this._scene.getRenderId();
  70424. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  70425. this.bones[0].computeAbsoluteTransforms();
  70426. this._lastAbsoluteTransformsUpdateId = renderId;
  70427. }
  70428. };
  70429. Skeleton.prototype.getPoseMatrix = function () {
  70430. var poseMatrix = null;
  70431. if (this._meshesWithPoseMatrix.length > 0) {
  70432. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  70433. }
  70434. return poseMatrix;
  70435. };
  70436. Skeleton.prototype.sortBones = function () {
  70437. var bones = new Array();
  70438. var visited = new Array(this.bones.length);
  70439. for (var index = 0; index < this.bones.length; index++) {
  70440. this._sortBones(index, bones, visited);
  70441. }
  70442. this.bones = bones;
  70443. };
  70444. Skeleton.prototype._sortBones = function (index, bones, visited) {
  70445. if (visited[index]) {
  70446. return;
  70447. }
  70448. visited[index] = true;
  70449. var bone = this.bones[index];
  70450. if (bone._index === undefined) {
  70451. bone._index = index;
  70452. }
  70453. var parentBone = bone.getParent();
  70454. if (parentBone) {
  70455. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  70456. }
  70457. bones.push(bone);
  70458. };
  70459. return Skeleton;
  70460. }());
  70461. BABYLON.Skeleton = Skeleton;
  70462. })(BABYLON || (BABYLON = {}));
  70463. //# sourceMappingURL=babylon.skeleton.js.map
  70464. var BABYLON;
  70465. (function (BABYLON) {
  70466. var SphericalPolynomial = /** @class */ (function () {
  70467. function SphericalPolynomial() {
  70468. this.x = BABYLON.Vector3.Zero();
  70469. this.y = BABYLON.Vector3.Zero();
  70470. this.z = BABYLON.Vector3.Zero();
  70471. this.xx = BABYLON.Vector3.Zero();
  70472. this.yy = BABYLON.Vector3.Zero();
  70473. this.zz = BABYLON.Vector3.Zero();
  70474. this.xy = BABYLON.Vector3.Zero();
  70475. this.yz = BABYLON.Vector3.Zero();
  70476. this.zx = BABYLON.Vector3.Zero();
  70477. }
  70478. SphericalPolynomial.prototype.addAmbient = function (color) {
  70479. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70480. this.xx = this.xx.add(colorVector);
  70481. this.yy = this.yy.add(colorVector);
  70482. this.zz = this.zz.add(colorVector);
  70483. };
  70484. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  70485. var result = new SphericalPolynomial();
  70486. result.x = harmonics.L11.scale(1.02333);
  70487. result.y = harmonics.L1_1.scale(1.02333);
  70488. result.z = harmonics.L10.scale(1.02333);
  70489. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  70490. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  70491. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  70492. result.yz = harmonics.L2_1.scale(0.858086);
  70493. result.zx = harmonics.L21.scale(0.858086);
  70494. result.xy = harmonics.L2_2.scale(0.858086);
  70495. result.scale(1.0 / Math.PI);
  70496. return result;
  70497. };
  70498. SphericalPolynomial.prototype.scale = function (scale) {
  70499. this.x = this.x.scale(scale);
  70500. this.y = this.y.scale(scale);
  70501. this.z = this.z.scale(scale);
  70502. this.xx = this.xx.scale(scale);
  70503. this.yy = this.yy.scale(scale);
  70504. this.zz = this.zz.scale(scale);
  70505. this.yz = this.yz.scale(scale);
  70506. this.zx = this.zx.scale(scale);
  70507. this.xy = this.xy.scale(scale);
  70508. };
  70509. return SphericalPolynomial;
  70510. }());
  70511. BABYLON.SphericalPolynomial = SphericalPolynomial;
  70512. var SphericalHarmonics = /** @class */ (function () {
  70513. function SphericalHarmonics() {
  70514. this.L00 = BABYLON.Vector3.Zero();
  70515. this.L1_1 = BABYLON.Vector3.Zero();
  70516. this.L10 = BABYLON.Vector3.Zero();
  70517. this.L11 = BABYLON.Vector3.Zero();
  70518. this.L2_2 = BABYLON.Vector3.Zero();
  70519. this.L2_1 = BABYLON.Vector3.Zero();
  70520. this.L20 = BABYLON.Vector3.Zero();
  70521. this.L21 = BABYLON.Vector3.Zero();
  70522. this.L22 = BABYLON.Vector3.Zero();
  70523. }
  70524. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  70525. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70526. var c = colorVector.scale(deltaSolidAngle);
  70527. this.L00 = this.L00.add(c.scale(0.282095));
  70528. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  70529. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  70530. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  70531. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  70532. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  70533. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  70534. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  70535. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  70536. };
  70537. SphericalHarmonics.prototype.scale = function (scale) {
  70538. this.L00 = this.L00.scale(scale);
  70539. this.L1_1 = this.L1_1.scale(scale);
  70540. this.L10 = this.L10.scale(scale);
  70541. this.L11 = this.L11.scale(scale);
  70542. this.L2_2 = this.L2_2.scale(scale);
  70543. this.L2_1 = this.L2_1.scale(scale);
  70544. this.L20 = this.L20.scale(scale);
  70545. this.L21 = this.L21.scale(scale);
  70546. this.L22 = this.L22.scale(scale);
  70547. };
  70548. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  70549. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  70550. //
  70551. // E_lm = A_l * L_lm
  70552. //
  70553. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  70554. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  70555. // the scaling factors are given in equation 9.
  70556. // Constant (Band 0)
  70557. this.L00 = this.L00.scale(3.141593);
  70558. // Linear (Band 1)
  70559. this.L1_1 = this.L1_1.scale(2.094395);
  70560. this.L10 = this.L10.scale(2.094395);
  70561. this.L11 = this.L11.scale(2.094395);
  70562. // Quadratic (Band 2)
  70563. this.L2_2 = this.L2_2.scale(0.785398);
  70564. this.L2_1 = this.L2_1.scale(0.785398);
  70565. this.L20 = this.L20.scale(0.785398);
  70566. this.L21 = this.L21.scale(0.785398);
  70567. this.L22 = this.L22.scale(0.785398);
  70568. };
  70569. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  70570. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  70571. // L = (1/pi) * E * rho
  70572. //
  70573. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  70574. this.scale(1.0 / Math.PI);
  70575. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  70576. // (The pixel shader must apply albedo after texture fetches, etc).
  70577. };
  70578. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  70579. var result = new SphericalHarmonics();
  70580. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  70581. result.L1_1 = polynomial.y.scale(0.977204);
  70582. result.L10 = polynomial.z.scale(0.977204);
  70583. result.L11 = polynomial.x.scale(0.977204);
  70584. result.L2_2 = polynomial.xy.scale(1.16538);
  70585. result.L2_1 = polynomial.yz.scale(1.16538);
  70586. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  70587. result.L21 = polynomial.zx.scale(1.16538);
  70588. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  70589. result.scale(Math.PI);
  70590. return result;
  70591. };
  70592. return SphericalHarmonics;
  70593. }());
  70594. BABYLON.SphericalHarmonics = SphericalHarmonics;
  70595. })(BABYLON || (BABYLON = {}));
  70596. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  70597. var BABYLON;
  70598. (function (BABYLON) {
  70599. var FileFaceOrientation = /** @class */ (function () {
  70600. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  70601. this.name = name;
  70602. this.worldAxisForNormal = worldAxisForNormal;
  70603. this.worldAxisForFileX = worldAxisForFileX;
  70604. this.worldAxisForFileY = worldAxisForFileY;
  70605. }
  70606. return FileFaceOrientation;
  70607. }());
  70608. ;
  70609. /**
  70610. * Helper class dealing with the extraction of spherical polynomial dataArray
  70611. * from a cube map.
  70612. */
  70613. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  70614. function CubeMapToSphericalPolynomialTools() {
  70615. }
  70616. /**
  70617. * Converts a texture to the according Spherical Polynomial data.
  70618. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70619. *
  70620. * @param texture The texture to extract the information from.
  70621. * @return The Spherical Polynomial data.
  70622. */
  70623. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  70624. if (!texture.isCube) {
  70625. // Only supports cube Textures currently.
  70626. return null;
  70627. }
  70628. var size = texture.getSize().width;
  70629. var right = texture.readPixels(0);
  70630. var left = texture.readPixels(1);
  70631. var up;
  70632. var down;
  70633. if (texture.isRenderTarget) {
  70634. up = texture.readPixels(3);
  70635. down = texture.readPixels(2);
  70636. }
  70637. else {
  70638. up = texture.readPixels(2);
  70639. down = texture.readPixels(3);
  70640. }
  70641. var front = texture.readPixels(4);
  70642. var back = texture.readPixels(5);
  70643. var gammaSpace = texture.gammaSpace;
  70644. // Always read as RGBA.
  70645. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  70646. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70647. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70648. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70649. }
  70650. var cubeInfo = {
  70651. size: size,
  70652. right: right,
  70653. left: left,
  70654. up: up,
  70655. down: down,
  70656. front: front,
  70657. back: back,
  70658. format: format,
  70659. type: type,
  70660. gammaSpace: gammaSpace,
  70661. };
  70662. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  70663. };
  70664. /**
  70665. * Converts a cubemap to the according Spherical Polynomial data.
  70666. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70667. *
  70668. * @param cubeInfo The Cube map to extract the information from.
  70669. * @return The Spherical Polynomial data.
  70670. */
  70671. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  70672. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  70673. var totalSolidAngle = 0.0;
  70674. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  70675. var du = 2.0 / cubeInfo.size;
  70676. var dv = du;
  70677. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  70678. var minUV = du * 0.5 - 1.0;
  70679. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70680. var fileFace = this.FileFaces[faceIndex];
  70681. var dataArray = cubeInfo[fileFace.name];
  70682. var v = minUV;
  70683. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  70684. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  70685. // Because SP is still linear, so summation is fine in that basis.
  70686. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  70687. for (var y = 0; y < cubeInfo.size; y++) {
  70688. var u = minUV;
  70689. for (var x = 0; x < cubeInfo.size; x++) {
  70690. // World direction (not normalised)
  70691. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  70692. worldDirection.normalize();
  70693. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  70694. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  70695. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  70696. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  70697. // Handle Integer types.
  70698. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70699. r /= 255;
  70700. g /= 255;
  70701. b /= 255;
  70702. }
  70703. // Handle Gamma space textures.
  70704. if (cubeInfo.gammaSpace) {
  70705. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  70706. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  70707. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  70708. }
  70709. var color = new BABYLON.Color3(r, g, b);
  70710. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  70711. totalSolidAngle += deltaSolidAngle;
  70712. u += du;
  70713. }
  70714. v += dv;
  70715. }
  70716. }
  70717. // Solid angle for entire sphere is 4*pi
  70718. var sphereSolidAngle = 4.0 * Math.PI;
  70719. // Adjust the solid angle to allow for how many faces we processed.
  70720. var facesProcessed = 6.0;
  70721. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  70722. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  70723. // This is needed because the numerical integration over the cube uses a
  70724. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  70725. // and also to compensate for accumulative error due to float precision in the summation.
  70726. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  70727. sphericalHarmonics.scale(correctionFactor);
  70728. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  70729. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  70730. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  70731. };
  70732. CubeMapToSphericalPolynomialTools.FileFaces = [
  70733. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  70734. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  70735. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  70736. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  70737. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  70738. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  70739. ];
  70740. return CubeMapToSphericalPolynomialTools;
  70741. }());
  70742. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  70743. })(BABYLON || (BABYLON = {}));
  70744. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  70745. var BABYLON;
  70746. (function (BABYLON) {
  70747. /**
  70748. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  70749. */
  70750. var PanoramaToCubeMapTools = /** @class */ (function () {
  70751. function PanoramaToCubeMapTools() {
  70752. }
  70753. /**
  70754. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  70755. *
  70756. * @param float32Array The source data.
  70757. * @param inputWidth The width of the input panorama.
  70758. * @param inputhHeight The height of the input panorama.
  70759. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  70760. * @return The cubemap data
  70761. */
  70762. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  70763. if (!float32Array) {
  70764. throw "ConvertPanoramaToCubemap: input cannot be null";
  70765. }
  70766. if (float32Array.length != inputWidth * inputHeight * 3) {
  70767. throw "ConvertPanoramaToCubemap: input size is wrong";
  70768. }
  70769. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  70770. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  70771. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  70772. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  70773. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  70774. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  70775. return {
  70776. front: textureFront,
  70777. back: textureBack,
  70778. left: textureLeft,
  70779. right: textureRight,
  70780. up: textureUp,
  70781. down: textureDown,
  70782. size: size,
  70783. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  70784. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  70785. gammaSpace: false,
  70786. };
  70787. };
  70788. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  70789. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  70790. var textureArray = new Float32Array(buffer);
  70791. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  70792. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  70793. var dy = 1 / texSize;
  70794. var fy = 0;
  70795. for (var y = 0; y < texSize; y++) {
  70796. var xv1 = faceData[0];
  70797. var xv2 = faceData[2];
  70798. for (var x = 0; x < texSize; x++) {
  70799. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  70800. v.normalize();
  70801. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  70802. // 3 channels per pixels
  70803. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  70804. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  70805. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  70806. xv1 = xv1.add(rotDX1);
  70807. xv2 = xv2.add(rotDX2);
  70808. }
  70809. fy += dy;
  70810. }
  70811. return textureArray;
  70812. };
  70813. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  70814. var theta = Math.atan2(vDir.z, vDir.x);
  70815. var phi = Math.acos(vDir.y);
  70816. while (theta < -Math.PI)
  70817. theta += 2 * Math.PI;
  70818. while (theta > Math.PI)
  70819. theta -= 2 * Math.PI;
  70820. var dx = theta / Math.PI;
  70821. var dy = phi / Math.PI;
  70822. // recenter.
  70823. dx = dx * 0.5 + 0.5;
  70824. var px = Math.round(dx * inputWidth);
  70825. if (px < 0)
  70826. px = 0;
  70827. else if (px >= inputWidth)
  70828. px = inputWidth - 1;
  70829. var py = Math.round(dy * inputHeight);
  70830. if (py < 0)
  70831. py = 0;
  70832. else if (py >= inputHeight)
  70833. py = inputHeight - 1;
  70834. var inputY = (inputHeight - py - 1);
  70835. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  70836. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  70837. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  70838. return {
  70839. r: r,
  70840. g: g,
  70841. b: b
  70842. };
  70843. };
  70844. PanoramaToCubeMapTools.FACE_FRONT = [
  70845. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70846. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70847. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70848. new BABYLON.Vector3(1.0, 1.0, -1.0)
  70849. ];
  70850. PanoramaToCubeMapTools.FACE_BACK = [
  70851. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70852. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70853. new BABYLON.Vector3(1.0, 1.0, 1.0),
  70854. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  70855. ];
  70856. PanoramaToCubeMapTools.FACE_RIGHT = [
  70857. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70858. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70859. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70860. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70861. ];
  70862. PanoramaToCubeMapTools.FACE_LEFT = [
  70863. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70864. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70865. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70866. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  70867. ];
  70868. PanoramaToCubeMapTools.FACE_DOWN = [
  70869. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70870. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70871. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70872. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70873. ];
  70874. PanoramaToCubeMapTools.FACE_UP = [
  70875. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70876. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70877. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70878. new BABYLON.Vector3(1.0, -1.0, -1.0)
  70879. ];
  70880. return PanoramaToCubeMapTools;
  70881. }());
  70882. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  70883. })(BABYLON || (BABYLON = {}));
  70884. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  70885. var BABYLON;
  70886. (function (BABYLON) {
  70887. ;
  70888. /**
  70889. * This groups tools to convert HDR texture to native colors array.
  70890. */
  70891. var HDRTools = /** @class */ (function () {
  70892. function HDRTools() {
  70893. }
  70894. HDRTools.Ldexp = function (mantissa, exponent) {
  70895. if (exponent > 1023) {
  70896. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  70897. }
  70898. if (exponent < -1074) {
  70899. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  70900. }
  70901. return mantissa * Math.pow(2, exponent);
  70902. };
  70903. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  70904. if (exponent > 0) {
  70905. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  70906. float32array[index + 0] = red * exponent;
  70907. float32array[index + 1] = green * exponent;
  70908. float32array[index + 2] = blue * exponent;
  70909. }
  70910. else {
  70911. float32array[index + 0] = 0;
  70912. float32array[index + 1] = 0;
  70913. float32array[index + 2] = 0;
  70914. }
  70915. };
  70916. HDRTools.readStringLine = function (uint8array, startIndex) {
  70917. var line = "";
  70918. var character = "";
  70919. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  70920. character = String.fromCharCode(uint8array[i]);
  70921. if (character == "\n") {
  70922. break;
  70923. }
  70924. line += character;
  70925. }
  70926. return line;
  70927. };
  70928. /**
  70929. * Reads header information from an RGBE texture stored in a native array.
  70930. * More information on this format are available here:
  70931. * https://en.wikipedia.org/wiki/RGBE_image_format
  70932. *
  70933. * @param uint8array The binary file stored in native array.
  70934. * @return The header information.
  70935. */
  70936. HDRTools.RGBE_ReadHeader = function (uint8array) {
  70937. var height = 0;
  70938. var width = 0;
  70939. var line = this.readStringLine(uint8array, 0);
  70940. if (line[0] != '#' || line[1] != '?') {
  70941. throw "Bad HDR Format.";
  70942. }
  70943. var endOfHeader = false;
  70944. var findFormat = false;
  70945. var lineIndex = 0;
  70946. do {
  70947. lineIndex += (line.length + 1);
  70948. line = this.readStringLine(uint8array, lineIndex);
  70949. if (line == "FORMAT=32-bit_rle_rgbe") {
  70950. findFormat = true;
  70951. }
  70952. else if (line.length == 0) {
  70953. endOfHeader = true;
  70954. }
  70955. } while (!endOfHeader);
  70956. if (!findFormat) {
  70957. throw "HDR Bad header format, unsupported FORMAT";
  70958. }
  70959. lineIndex += (line.length + 1);
  70960. line = this.readStringLine(uint8array, lineIndex);
  70961. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  70962. var match = sizeRegexp.exec(line);
  70963. // TODO. Support +Y and -X if needed.
  70964. if (!match || match.length < 3) {
  70965. throw "HDR Bad header format, no size";
  70966. }
  70967. width = parseInt(match[2]);
  70968. height = parseInt(match[1]);
  70969. if (width < 8 || width > 0x7fff) {
  70970. throw "HDR Bad header format, unsupported size";
  70971. }
  70972. lineIndex += (line.length + 1);
  70973. return {
  70974. height: height,
  70975. width: width,
  70976. dataPosition: lineIndex
  70977. };
  70978. };
  70979. /**
  70980. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  70981. * This RGBE texture needs to store the information as a panorama.
  70982. *
  70983. * More information on this format are available here:
  70984. * https://en.wikipedia.org/wiki/RGBE_image_format
  70985. *
  70986. * @param buffer The binary file stored in an array buffer.
  70987. * @param size The expected size of the extracted cubemap.
  70988. * @return The Cube Map information.
  70989. */
  70990. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  70991. var uint8array = new Uint8Array(buffer);
  70992. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  70993. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  70994. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  70995. return cubeMapData;
  70996. };
  70997. /**
  70998. * Returns the pixels data extracted from an RGBE texture.
  70999. * This pixels will be stored left to right up to down in the R G B order in one array.
  71000. *
  71001. * More information on this format are available here:
  71002. * https://en.wikipedia.org/wiki/RGBE_image_format
  71003. *
  71004. * @param uint8array The binary file stored in an array buffer.
  71005. * @param hdrInfo The header information of the file.
  71006. * @return The pixels data in RGB right to left up to down order.
  71007. */
  71008. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  71009. // Keep for multi format supports.
  71010. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  71011. };
  71012. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  71013. var num_scanlines = hdrInfo.height;
  71014. var scanline_width = hdrInfo.width;
  71015. var a, b, c, d, count;
  71016. var dataIndex = hdrInfo.dataPosition;
  71017. var index = 0, endIndex = 0, i = 0;
  71018. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  71019. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  71020. // 3 channels of 4 bytes per pixel in float.
  71021. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  71022. var resultArray = new Float32Array(resultBuffer);
  71023. // read in each successive scanline
  71024. while (num_scanlines > 0) {
  71025. a = uint8array[dataIndex++];
  71026. b = uint8array[dataIndex++];
  71027. c = uint8array[dataIndex++];
  71028. d = uint8array[dataIndex++];
  71029. if (a != 2 || b != 2 || (c & 0x80)) {
  71030. // this file is not run length encoded
  71031. throw "HDR Bad header format, not RLE";
  71032. }
  71033. if (((c << 8) | d) != scanline_width) {
  71034. throw "HDR Bad header format, wrong scan line width";
  71035. }
  71036. index = 0;
  71037. // read each of the four channels for the scanline into the buffer
  71038. for (i = 0; i < 4; i++) {
  71039. endIndex = (i + 1) * scanline_width;
  71040. while (index < endIndex) {
  71041. a = uint8array[dataIndex++];
  71042. b = uint8array[dataIndex++];
  71043. if (a > 128) {
  71044. // a run of the same value
  71045. count = a - 128;
  71046. if ((count == 0) || (count > endIndex - index)) {
  71047. throw "HDR Bad Format, bad scanline data (run)";
  71048. }
  71049. while (count-- > 0) {
  71050. scanLineArray[index++] = b;
  71051. }
  71052. }
  71053. else {
  71054. // a non-run
  71055. count = a;
  71056. if ((count == 0) || (count > endIndex - index)) {
  71057. throw "HDR Bad Format, bad scanline data (non-run)";
  71058. }
  71059. scanLineArray[index++] = b;
  71060. if (--count > 0) {
  71061. for (var j = 0; j < count; j++) {
  71062. scanLineArray[index++] = uint8array[dataIndex++];
  71063. }
  71064. }
  71065. }
  71066. }
  71067. }
  71068. // now convert data from buffer into floats
  71069. for (i = 0; i < scanline_width; i++) {
  71070. a = scanLineArray[i];
  71071. b = scanLineArray[i + scanline_width];
  71072. c = scanLineArray[i + 2 * scanline_width];
  71073. d = scanLineArray[i + 3 * scanline_width];
  71074. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  71075. }
  71076. num_scanlines--;
  71077. }
  71078. return resultArray;
  71079. };
  71080. return HDRTools;
  71081. }());
  71082. BABYLON.HDRTools = HDRTools;
  71083. })(BABYLON || (BABYLON = {}));
  71084. //# sourceMappingURL=babylon.hdr.js.map
  71085. var BABYLON;
  71086. (function (BABYLON) {
  71087. /**
  71088. * This represents a texture coming from an HDR input.
  71089. *
  71090. * The only supported format is currently panorama picture stored in RGBE format.
  71091. * Example of such files can be found on HDRLib: http://hdrlib.com/
  71092. */
  71093. var HDRCubeTexture = /** @class */ (function (_super) {
  71094. __extends(HDRCubeTexture, _super);
  71095. /**
  71096. * Instantiates an HDRTexture from the following parameters.
  71097. *
  71098. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  71099. * @param scene The scene the texture will be used in
  71100. * @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.
  71101. * @param noMipmap Forces to not generate the mipmap if true
  71102. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  71103. * @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)
  71104. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  71105. */
  71106. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  71107. if (noMipmap === void 0) { noMipmap = false; }
  71108. if (generateHarmonics === void 0) { generateHarmonics = true; }
  71109. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  71110. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  71111. if (onLoad === void 0) { onLoad = null; }
  71112. if (onError === void 0) { onError = null; }
  71113. var _this = _super.call(this, scene) || this;
  71114. _this._useInGammaSpace = false;
  71115. _this._generateHarmonics = true;
  71116. _this._isBABYLONPreprocessed = false;
  71117. _this._onLoad = null;
  71118. _this._onError = null;
  71119. /**
  71120. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  71121. */
  71122. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  71123. /**
  71124. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  71125. * This is usefull at run time to apply the good shader.
  71126. */
  71127. _this.isPMREM = false;
  71128. _this._isBlocking = true;
  71129. if (!url) {
  71130. return _this;
  71131. }
  71132. _this.name = url;
  71133. _this.url = url;
  71134. _this.hasAlpha = false;
  71135. _this.isCube = true;
  71136. _this._textureMatrix = BABYLON.Matrix.Identity();
  71137. _this._onLoad = onLoad;
  71138. _this._onError = onError;
  71139. _this.gammaSpace = false;
  71140. var caps = scene.getEngine().getCaps();
  71141. if (size) {
  71142. _this._isBABYLONPreprocessed = false;
  71143. _this._noMipmap = noMipmap;
  71144. _this._size = size;
  71145. _this._useInGammaSpace = useInGammaSpace;
  71146. _this._usePMREMGenerator = usePMREMGenerator &&
  71147. caps.textureLOD &&
  71148. caps.textureFloat &&
  71149. !_this._useInGammaSpace;
  71150. }
  71151. else {
  71152. _this._isBABYLONPreprocessed = true;
  71153. _this._noMipmap = false;
  71154. _this._useInGammaSpace = false;
  71155. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  71156. !_this._useInGammaSpace;
  71157. }
  71158. _this.isPMREM = _this._usePMREMGenerator;
  71159. _this._texture = _this._getFromCache(url, _this._noMipmap);
  71160. if (!_this._texture) {
  71161. if (!scene.useDelayedTextureLoading) {
  71162. _this.loadTexture();
  71163. }
  71164. else {
  71165. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  71166. }
  71167. }
  71168. return _this;
  71169. }
  71170. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  71171. /**
  71172. * Gets wether or not the texture is blocking during loading.
  71173. */
  71174. get: function () {
  71175. return this._isBlocking;
  71176. },
  71177. /**
  71178. * Sets wether or not the texture is blocking during loading.
  71179. */
  71180. set: function (value) {
  71181. this._isBlocking = value;
  71182. },
  71183. enumerable: true,
  71184. configurable: true
  71185. });
  71186. /**
  71187. * Occurs when the file is a preprocessed .babylon.hdr file.
  71188. */
  71189. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  71190. var _this = this;
  71191. var mipLevels = 0;
  71192. var floatArrayView = null;
  71193. var scene = this.getScene();
  71194. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  71195. var mips = new Array();
  71196. if (!floatArrayView) {
  71197. return mips;
  71198. }
  71199. var startIndex = 30;
  71200. for (var level = 0; level < mipLevels; level++) {
  71201. mips.push([]);
  71202. // Fill each pixel of the mip level.
  71203. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  71204. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71205. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  71206. mips[level].push(faceData);
  71207. startIndex += faceSize;
  71208. }
  71209. }
  71210. return mips;
  71211. } : null;
  71212. var callback = function (buffer) {
  71213. var scene = _this.getScene();
  71214. if (!scene) {
  71215. return null;
  71216. }
  71217. // Create Native Array Views
  71218. var intArrayView = new Int32Array(buffer);
  71219. floatArrayView = new Float32Array(buffer);
  71220. // Fill header.
  71221. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  71222. _this._size = intArrayView[1]; // CubeMap max mip face size.
  71223. // Update Texture Information.
  71224. if (!_this._texture) {
  71225. return null;
  71226. }
  71227. _this._texture.updateSize(_this._size, _this._size);
  71228. // Fill polynomial information.
  71229. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  71230. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  71231. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  71232. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  71233. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  71234. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  71235. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  71236. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  71237. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  71238. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  71239. _this.sphericalPolynomial = sphericalPolynomial;
  71240. // Fill pixel data.
  71241. mipLevels = intArrayView[29]; // Number of mip levels.
  71242. var startIndex = 30;
  71243. var data = [];
  71244. var faceSize = Math.pow(_this._size, 2) * 3;
  71245. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71246. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  71247. startIndex += faceSize;
  71248. }
  71249. var results = [];
  71250. var byteArray = null;
  71251. // Push each faces.
  71252. for (var k = 0; k < 6; k++) {
  71253. var dataFace = null;
  71254. // To be deprecated.
  71255. if (version === 1) {
  71256. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  71257. dataFace = data[j];
  71258. }
  71259. // If special cases.
  71260. if (!mipmapGenerator && dataFace) {
  71261. if (!scene.getEngine().getCaps().textureFloat) {
  71262. // 3 channels of 1 bytes per pixel in bytes.
  71263. var byteBuffer = new ArrayBuffer(faceSize);
  71264. byteArray = new Uint8Array(byteBuffer);
  71265. }
  71266. for (var i = 0; i < _this._size * _this._size; i++) {
  71267. // Put in gamma space if requested.
  71268. if (_this._useInGammaSpace) {
  71269. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71270. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71271. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71272. }
  71273. // Convert to int texture for fallback.
  71274. if (byteArray) {
  71275. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71276. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71277. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71278. // May use luminance instead if the result is not accurate.
  71279. var max = Math.max(Math.max(r, g), b);
  71280. if (max > 255) {
  71281. var scale = 255 / max;
  71282. r *= scale;
  71283. g *= scale;
  71284. b *= scale;
  71285. }
  71286. byteArray[(i * 3) + 0] = r;
  71287. byteArray[(i * 3) + 1] = g;
  71288. byteArray[(i * 3) + 2] = b;
  71289. }
  71290. }
  71291. }
  71292. // Fill the array accordingly.
  71293. if (byteArray) {
  71294. results.push(byteArray);
  71295. }
  71296. else {
  71297. results.push(dataFace);
  71298. }
  71299. }
  71300. return results;
  71301. };
  71302. if (scene) {
  71303. 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);
  71304. }
  71305. };
  71306. /**
  71307. * Occurs when the file is raw .hdr file.
  71308. */
  71309. HDRCubeTexture.prototype.loadHDRTexture = function () {
  71310. var _this = this;
  71311. var callback = function (buffer) {
  71312. var scene = _this.getScene();
  71313. if (!scene) {
  71314. return null;
  71315. }
  71316. // Extract the raw linear data.
  71317. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  71318. // Generate harmonics if needed.
  71319. if (_this._generateHarmonics) {
  71320. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  71321. _this.sphericalPolynomial = sphericalPolynomial;
  71322. }
  71323. var results = [];
  71324. var byteArray = null;
  71325. // Push each faces.
  71326. for (var j = 0; j < 6; j++) {
  71327. // Create uintarray fallback.
  71328. if (!scene.getEngine().getCaps().textureFloat) {
  71329. // 3 channels of 1 bytes per pixel in bytes.
  71330. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  71331. byteArray = new Uint8Array(byteBuffer);
  71332. }
  71333. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  71334. // If special cases.
  71335. if (_this._useInGammaSpace || byteArray) {
  71336. for (var i = 0; i < _this._size * _this._size; i++) {
  71337. // Put in gamma space if requested.
  71338. if (_this._useInGammaSpace) {
  71339. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71340. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71341. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71342. }
  71343. // Convert to int texture for fallback.
  71344. if (byteArray) {
  71345. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71346. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71347. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71348. // May use luminance instead if the result is not accurate.
  71349. var max = Math.max(Math.max(r, g), b);
  71350. if (max > 255) {
  71351. var scale = 255 / max;
  71352. r *= scale;
  71353. g *= scale;
  71354. b *= scale;
  71355. }
  71356. byteArray[(i * 3) + 0] = r;
  71357. byteArray[(i * 3) + 1] = g;
  71358. byteArray[(i * 3) + 2] = b;
  71359. }
  71360. }
  71361. }
  71362. if (byteArray) {
  71363. results.push(byteArray);
  71364. }
  71365. else {
  71366. results.push(dataFace);
  71367. }
  71368. }
  71369. return results;
  71370. };
  71371. var mipmapGenerator = null;
  71372. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  71373. // if (!this._noMipmap &&
  71374. // this._usePMREMGenerator) {
  71375. // mipmapGenerator = (data: ArrayBufferView[]) => {
  71376. // // Custom setup of the generator matching with the PBR shader values.
  71377. // var generator = new BABYLON.PMREMGenerator(data,
  71378. // this._size,
  71379. // this._size,
  71380. // 0,
  71381. // 3,
  71382. // this.getScene().getEngine().getCaps().textureFloat,
  71383. // 2048,
  71384. // 0.25,
  71385. // false,
  71386. // true);
  71387. // return generator.filterCubeMap();
  71388. // };
  71389. // }
  71390. var scene = this.getScene();
  71391. if (scene) {
  71392. 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);
  71393. }
  71394. };
  71395. /**
  71396. * Starts the loading process of the texture.
  71397. */
  71398. HDRCubeTexture.prototype.loadTexture = function () {
  71399. if (this._isBABYLONPreprocessed) {
  71400. this.loadBabylonTexture();
  71401. }
  71402. else {
  71403. this.loadHDRTexture();
  71404. }
  71405. };
  71406. HDRCubeTexture.prototype.clone = function () {
  71407. var scene = this.getScene();
  71408. if (!scene) {
  71409. return this;
  71410. }
  71411. var size = (this._isBABYLONPreprocessed ? null : this._size);
  71412. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  71413. // Base texture
  71414. newTexture.level = this.level;
  71415. newTexture.wrapU = this.wrapU;
  71416. newTexture.wrapV = this.wrapV;
  71417. newTexture.coordinatesIndex = this.coordinatesIndex;
  71418. newTexture.coordinatesMode = this.coordinatesMode;
  71419. return newTexture;
  71420. };
  71421. // Methods
  71422. HDRCubeTexture.prototype.delayLoad = function () {
  71423. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71424. return;
  71425. }
  71426. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71427. this._texture = this._getFromCache(this.url, this._noMipmap);
  71428. if (!this._texture) {
  71429. this.loadTexture();
  71430. }
  71431. };
  71432. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  71433. return this._textureMatrix;
  71434. };
  71435. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71436. this._textureMatrix = value;
  71437. };
  71438. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71439. var texture = null;
  71440. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  71441. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  71442. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  71443. texture.name = parsedTexture.name;
  71444. texture.hasAlpha = parsedTexture.hasAlpha;
  71445. texture.level = parsedTexture.level;
  71446. texture.coordinatesMode = parsedTexture.coordinatesMode;
  71447. texture.isBlocking = parsedTexture.isBlocking;
  71448. }
  71449. return texture;
  71450. };
  71451. HDRCubeTexture.prototype.serialize = function () {
  71452. if (!this.name) {
  71453. return null;
  71454. }
  71455. var serializationObject = {};
  71456. serializationObject.name = this.name;
  71457. serializationObject.hasAlpha = this.hasAlpha;
  71458. serializationObject.isCube = true;
  71459. serializationObject.level = this.level;
  71460. serializationObject.size = this._size;
  71461. serializationObject.coordinatesMode = this.coordinatesMode;
  71462. serializationObject.useInGammaSpace = this._useInGammaSpace;
  71463. serializationObject.generateHarmonics = this._generateHarmonics;
  71464. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  71465. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  71466. serializationObject.customType = "BABYLON.HDRCubeTexture";
  71467. serializationObject.noMipmap = this._noMipmap;
  71468. serializationObject.isBlocking = this._isBlocking;
  71469. return serializationObject;
  71470. };
  71471. /**
  71472. * Saves as a file the data contained in the texture in a binary format.
  71473. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71474. * as the spherical used in the lighting.
  71475. * @param url The HDR file url.
  71476. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71477. * @param onError Method called if any error happens during download.
  71478. * @return The packed binary data.
  71479. */
  71480. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  71481. if (onError === void 0) { onError = null; }
  71482. var callback = function (buffer) {
  71483. var data = new Blob([buffer], { type: 'application/octet-stream' });
  71484. // Returns a URL you can use as a href.
  71485. var objUrl = window.URL.createObjectURL(data);
  71486. // Simulates a link to it and click to dowload.
  71487. var a = document.createElement("a");
  71488. document.body.appendChild(a);
  71489. a.style.display = "none";
  71490. a.href = objUrl;
  71491. a.download = "envmap.babylon.hdr";
  71492. a.click();
  71493. };
  71494. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  71495. };
  71496. /**
  71497. * Serializes the data contained in the texture in a binary format.
  71498. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71499. * as the spherical used in the lighting.
  71500. * @param url The HDR file url.
  71501. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71502. * @param onError Method called if any error happens during download.
  71503. * @return The packed binary data.
  71504. */
  71505. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  71506. if (onError === void 0) { onError = null; }
  71507. // Needs the url tho create the texture.
  71508. if (!url) {
  71509. return;
  71510. }
  71511. // Check Power of two size.
  71512. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  71513. return;
  71514. }
  71515. // Coming Back in 3.x.
  71516. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  71517. };
  71518. HDRCubeTexture._facesMapping = [
  71519. "right",
  71520. "left",
  71521. "up",
  71522. "down",
  71523. "front",
  71524. "back"
  71525. ];
  71526. return HDRCubeTexture;
  71527. }(BABYLON.BaseTexture));
  71528. BABYLON.HDRCubeTexture = HDRCubeTexture;
  71529. })(BABYLON || (BABYLON = {}));
  71530. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  71531. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  71532. // Huge respect for a such great lib.
  71533. // Earcut license:
  71534. // Copyright (c) 2016, Mapbox
  71535. //
  71536. // Permission to use, copy, modify, and/or distribute this software for any purpose
  71537. // with or without fee is hereby granted, provided that the above copyright notice
  71538. // and this permission notice appear in all copies.
  71539. //
  71540. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  71541. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  71542. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  71543. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  71544. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  71545. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  71546. // THIS SOFTWARE.
  71547. var Earcut;
  71548. (function (Earcut) {
  71549. /**
  71550. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  71551. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  71552. * @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).
  71553. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  71554. */
  71555. function earcut(data, holeIndices, dim) {
  71556. dim = dim || 2;
  71557. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  71558. if (!outerNode)
  71559. return triangles;
  71560. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  71561. if (hasHoles)
  71562. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  71563. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  71564. if (data.length > 80 * dim) {
  71565. minX = maxX = data[0];
  71566. minY = maxY = data[1];
  71567. for (var i = dim; i < outerLen; i += dim) {
  71568. x = data[i];
  71569. y = data[i + 1];
  71570. if (x < minX)
  71571. minX = x;
  71572. if (y < minY)
  71573. minY = y;
  71574. if (x > maxX)
  71575. maxX = x;
  71576. if (y > maxY)
  71577. maxY = y;
  71578. }
  71579. // minX, minY and size are later used to transform coords into integers for z-order calculation
  71580. size = Math.max(maxX - minX, maxY - minY);
  71581. }
  71582. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  71583. return triangles;
  71584. }
  71585. Earcut.earcut = earcut;
  71586. var Node = /** @class */ (function () {
  71587. function Node(i, x, y) {
  71588. this.i = i;
  71589. this.x = x;
  71590. this.y = y;
  71591. this.prev = null;
  71592. this.next = null;
  71593. this.z = null;
  71594. this.prevZ = null;
  71595. this.nextZ = null;
  71596. this.steiner = false;
  71597. }
  71598. return Node;
  71599. }());
  71600. // create a circular doubly linked list from polygon points in the specified winding order
  71601. function linkedList(data, start, end, dim, clockwise) {
  71602. var i, last = null;
  71603. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  71604. for (i = start; i < end; i += dim)
  71605. last = insertNode(i, data[i], data[i + 1], last);
  71606. }
  71607. else {
  71608. for (i = end - dim; i >= start; i -= dim)
  71609. last = insertNode(i, data[i], data[i + 1], last);
  71610. }
  71611. if (last && equals(last, last.next)) {
  71612. removeNode(last);
  71613. last = last.next;
  71614. }
  71615. return last;
  71616. }
  71617. // eliminate colinear or duplicate points
  71618. function filterPoints(start, end) {
  71619. if (!start)
  71620. return start;
  71621. if (!end)
  71622. end = start;
  71623. var p = start, again;
  71624. do {
  71625. again = false;
  71626. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  71627. removeNode(p);
  71628. p = end = p.prev;
  71629. if (p === p.next)
  71630. return undefined;
  71631. again = true;
  71632. }
  71633. else {
  71634. p = p.next;
  71635. }
  71636. } while (again || p !== end);
  71637. return end;
  71638. }
  71639. // main ear slicing loop which triangulates a polygon (given as a linked list)
  71640. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  71641. if (!ear)
  71642. return;
  71643. // interlink polygon nodes in z-order
  71644. if (!pass && size)
  71645. indexCurve(ear, minX, minY, size);
  71646. var stop = ear, prev, next;
  71647. // iterate through ears, slicing them one by one
  71648. while (ear.prev !== ear.next) {
  71649. prev = ear.prev;
  71650. next = ear.next;
  71651. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  71652. // cut off the triangle
  71653. triangles.push(prev.i / dim);
  71654. triangles.push(ear.i / dim);
  71655. triangles.push(next.i / dim);
  71656. removeNode(ear);
  71657. // skipping the next vertice leads to less sliver triangles
  71658. ear = next.next;
  71659. stop = next.next;
  71660. continue;
  71661. }
  71662. ear = next;
  71663. // if we looped through the whole remaining polygon and can't find any more ears
  71664. if (ear === stop) {
  71665. // try filtering points and slicing again
  71666. if (!pass) {
  71667. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  71668. // if this didn't work, try curing all small self-intersections locally
  71669. }
  71670. else if (pass === 1) {
  71671. ear = cureLocalIntersections(ear, triangles, dim);
  71672. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  71673. // as a last resort, try splitting the remaining polygon into two
  71674. }
  71675. else if (pass === 2) {
  71676. splitEarcut(ear, triangles, dim, minX, minY, size);
  71677. }
  71678. break;
  71679. }
  71680. }
  71681. }
  71682. // check whether a polygon node forms a valid ear with adjacent nodes
  71683. function isEar(ear) {
  71684. var a = ear.prev, b = ear, c = ear.next;
  71685. if (area(a, b, c) >= 0)
  71686. return false; // reflex, can't be an ear
  71687. // now make sure we don't have other points inside the potential ear
  71688. var p = ear.next.next;
  71689. while (p !== ear.prev) {
  71690. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71691. area(p.prev, p, p.next) >= 0)
  71692. return false;
  71693. p = p.next;
  71694. }
  71695. return true;
  71696. }
  71697. function isEarHashed(ear, minX, minY, size) {
  71698. var a = ear.prev, b = ear, c = ear.next;
  71699. if (area(a, b, c) >= 0)
  71700. return false; // reflex, can't be an ear
  71701. // triangle bbox; min & max are calculated like this for speed
  71702. 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);
  71703. // z-order range for the current triangle bbox;
  71704. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  71705. // first look for points inside the triangle in increasing z-order
  71706. var p = ear.nextZ;
  71707. while (p && p.z <= maxZ) {
  71708. if (p !== ear.prev &&
  71709. p !== ear.next &&
  71710. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71711. area(p.prev, p, p.next) >= 0)
  71712. return false;
  71713. p = p.nextZ;
  71714. }
  71715. // then look for points in decreasing z-order
  71716. p = ear.prevZ;
  71717. while (p && p.z >= minZ) {
  71718. if (p !== ear.prev &&
  71719. p !== ear.next &&
  71720. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71721. area(p.prev, p, p.next) >= 0)
  71722. return false;
  71723. p = p.prevZ;
  71724. }
  71725. return true;
  71726. }
  71727. // go through all polygon nodes and cure small local self-intersections
  71728. function cureLocalIntersections(start, triangles, dim) {
  71729. var p = start;
  71730. do {
  71731. var a = p.prev, b = p.next.next;
  71732. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  71733. triangles.push(a.i / dim);
  71734. triangles.push(p.i / dim);
  71735. triangles.push(b.i / dim);
  71736. // remove two nodes involved
  71737. removeNode(p);
  71738. removeNode(p.next);
  71739. p = start = b;
  71740. }
  71741. p = p.next;
  71742. } while (p !== start);
  71743. return p;
  71744. }
  71745. // try splitting polygon into two and triangulate them independently
  71746. function splitEarcut(start, triangles, dim, minX, minY, size) {
  71747. // look for a valid diagonal that divides the polygon into two
  71748. var a = start;
  71749. do {
  71750. var b = a.next.next;
  71751. while (b !== a.prev) {
  71752. if (a.i !== b.i && isValidDiagonal(a, b)) {
  71753. // split the polygon in two by the diagonal
  71754. var c = splitPolygon(a, b);
  71755. // filter colinear points around the cuts
  71756. a = filterPoints(a, a.next);
  71757. c = filterPoints(c, c.next);
  71758. // run earcut on each half
  71759. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  71760. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  71761. return;
  71762. }
  71763. b = b.next;
  71764. }
  71765. a = a.next;
  71766. } while (a !== start);
  71767. }
  71768. // link every hole into the outer loop, producing a single-ring polygon without holes
  71769. function eliminateHoles(data, holeIndices, outerNode, dim) {
  71770. var queue = [], i, len, start, end, list;
  71771. for (i = 0, len = holeIndices.length; i < len; i++) {
  71772. start = holeIndices[i] * dim;
  71773. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71774. list = linkedList(data, start, end, dim, false);
  71775. if (list === list.next)
  71776. list.steiner = true;
  71777. queue.push(getLeftmost(list));
  71778. }
  71779. queue.sort(compareX);
  71780. // process holes from left to right
  71781. for (i = 0; i < queue.length; i++) {
  71782. eliminateHole(queue[i], outerNode);
  71783. outerNode = filterPoints(outerNode, outerNode.next);
  71784. }
  71785. return outerNode;
  71786. }
  71787. function compareX(a, b) {
  71788. return a.x - b.x;
  71789. }
  71790. // find a bridge between vertices that connects hole with an outer ring and and link it
  71791. function eliminateHole(hole, outerNode) {
  71792. outerNode = findHoleBridge(hole, outerNode);
  71793. if (outerNode) {
  71794. var b = splitPolygon(outerNode, hole);
  71795. filterPoints(b, b.next);
  71796. }
  71797. }
  71798. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  71799. function findHoleBridge(hole, outerNode) {
  71800. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  71801. // find a segment intersected by a ray from the hole's leftmost point to the left;
  71802. // segment's endpoint with lesser x will be potential connection point
  71803. do {
  71804. if (hy <= p.y && hy >= p.next.y) {
  71805. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  71806. if (x <= hx && x > qx) {
  71807. qx = x;
  71808. if (x === hx) {
  71809. if (hy === p.y)
  71810. return p;
  71811. if (hy === p.next.y)
  71812. return p.next;
  71813. }
  71814. m = p.x < p.next.x ? p : p.next;
  71815. }
  71816. }
  71817. p = p.next;
  71818. } while (p !== outerNode);
  71819. if (!m)
  71820. return null;
  71821. if (hx === qx)
  71822. return m.prev; // hole touches outer segment; pick lower endpoint
  71823. // look for points inside the triangle of hole point, segment intersection and endpoint;
  71824. // if there are no points found, we have a valid connection;
  71825. // otherwise choose the point of the minimum angle with the ray as connection point
  71826. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  71827. p = m.next;
  71828. while (p !== stop) {
  71829. if (hx >= p.x &&
  71830. p.x >= mx &&
  71831. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  71832. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  71833. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  71834. m = p;
  71835. tanMin = tan;
  71836. }
  71837. }
  71838. p = p.next;
  71839. }
  71840. return m;
  71841. }
  71842. // interlink polygon nodes in z-order
  71843. function indexCurve(start, minX, minY, size) {
  71844. var p = start;
  71845. do {
  71846. if (p.z === null)
  71847. p.z = zOrder(p.x, p.y, minX, minY, size);
  71848. p.prevZ = p.prev;
  71849. p.nextZ = p.next;
  71850. p = p.next;
  71851. } while (p !== start);
  71852. p.prevZ.nextZ = null;
  71853. p.prevZ = null;
  71854. sortLinked(p);
  71855. }
  71856. // Simon Tatham's linked list merge sort algorithm
  71857. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  71858. function sortLinked(list) {
  71859. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  71860. do {
  71861. p = list;
  71862. list = null;
  71863. tail = null;
  71864. numMerges = 0;
  71865. while (p) {
  71866. numMerges++;
  71867. q = p;
  71868. pSize = 0;
  71869. for (i = 0; i < inSize; i++) {
  71870. pSize++;
  71871. q = q.nextZ;
  71872. if (!q)
  71873. break;
  71874. }
  71875. qSize = inSize;
  71876. while (pSize > 0 || (qSize > 0 && q)) {
  71877. if (pSize === 0) {
  71878. e = q;
  71879. q = q.nextZ;
  71880. qSize--;
  71881. }
  71882. else if (qSize === 0 || !q) {
  71883. e = p;
  71884. p = p.nextZ;
  71885. pSize--;
  71886. }
  71887. else if (p.z <= q.z) {
  71888. e = p;
  71889. p = p.nextZ;
  71890. pSize--;
  71891. }
  71892. else {
  71893. e = q;
  71894. q = q.nextZ;
  71895. qSize--;
  71896. }
  71897. if (tail)
  71898. tail.nextZ = e;
  71899. else
  71900. list = e;
  71901. e.prevZ = tail;
  71902. tail = e;
  71903. }
  71904. p = q;
  71905. }
  71906. tail.nextZ = null;
  71907. inSize *= 2;
  71908. } while (numMerges > 1);
  71909. return list;
  71910. }
  71911. // z-order of a point given coords and size of the data bounding box
  71912. function zOrder(x, y, minX, minY, size) {
  71913. // coords are transformed into non-negative 15-bit integer range
  71914. x = 32767 * (x - minX) / size;
  71915. y = 32767 * (y - minY) / size;
  71916. x = (x | (x << 8)) & 0x00FF00FF;
  71917. x = (x | (x << 4)) & 0x0F0F0F0F;
  71918. x = (x | (x << 2)) & 0x33333333;
  71919. x = (x | (x << 1)) & 0x55555555;
  71920. y = (y | (y << 8)) & 0x00FF00FF;
  71921. y = (y | (y << 4)) & 0x0F0F0F0F;
  71922. y = (y | (y << 2)) & 0x33333333;
  71923. y = (y | (y << 1)) & 0x55555555;
  71924. return x | (y << 1);
  71925. }
  71926. // find the leftmost node of a polygon ring
  71927. function getLeftmost(start) {
  71928. var p = start, leftmost = start;
  71929. do {
  71930. if (p.x < leftmost.x)
  71931. leftmost = p;
  71932. p = p.next;
  71933. } while (p !== start);
  71934. return leftmost;
  71935. }
  71936. // check if a point lies within a convex triangle
  71937. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  71938. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  71939. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  71940. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  71941. }
  71942. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  71943. function isValidDiagonal(a, b) {
  71944. return a.next.i !== b.i &&
  71945. a.prev.i !== b.i &&
  71946. !intersectsPolygon(a, b) &&
  71947. locallyInside(a, b) &&
  71948. locallyInside(b, a) &&
  71949. middleInside(a, b);
  71950. }
  71951. // signed area of a triangle
  71952. function area(p, q, r) {
  71953. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  71954. }
  71955. // check if two points are equal
  71956. function equals(p1, p2) {
  71957. return p1.x === p2.x && p1.y === p2.y;
  71958. }
  71959. // check if two segments intersect
  71960. function intersects(p1, q1, p2, q2) {
  71961. if ((equals(p1, q1) && equals(p2, q2)) ||
  71962. (equals(p1, q2) && equals(p2, q1)))
  71963. return true;
  71964. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  71965. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  71966. }
  71967. // check if a polygon diagonal intersects any polygon segments
  71968. function intersectsPolygon(a, b) {
  71969. var p = a;
  71970. do {
  71971. if (p.i !== a.i &&
  71972. p.next.i !== a.i &&
  71973. p.i !== b.i &&
  71974. p.next.i !== b.i &&
  71975. intersects(p, p.next, a, b))
  71976. return true;
  71977. p = p.next;
  71978. } while (p !== a);
  71979. return false;
  71980. }
  71981. // check if a polygon diagonal is locally inside the polygon
  71982. function locallyInside(a, b) {
  71983. return area(a.prev, a, a.next) < 0
  71984. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  71985. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  71986. }
  71987. // check if the middle point of a polygon diagonal is inside the polygon
  71988. function middleInside(a, b) {
  71989. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  71990. do {
  71991. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  71992. inside = !inside;
  71993. p = p.next;
  71994. } while (p !== a);
  71995. return inside;
  71996. }
  71997. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  71998. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  71999. function splitPolygon(a, b) {
  72000. 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;
  72001. a.next = b;
  72002. b.prev = a;
  72003. a2.next = an;
  72004. an.prev = a2;
  72005. b2.next = a2;
  72006. a2.prev = b2;
  72007. bp.next = b2;
  72008. b2.prev = bp;
  72009. return b2;
  72010. }
  72011. // create a node and optionally link it with previous one (in a circular doubly linked list)
  72012. function insertNode(i, x, y, last) {
  72013. var p = new Node(i, x, y);
  72014. if (!last) {
  72015. p.prev = p;
  72016. p.next = p;
  72017. }
  72018. else {
  72019. p.next = last.next;
  72020. p.prev = last;
  72021. last.next.prev = p;
  72022. last.next = p;
  72023. }
  72024. return p;
  72025. }
  72026. function removeNode(p) {
  72027. p.next.prev = p.prev;
  72028. p.prev.next = p.next;
  72029. if (p.prevZ)
  72030. p.prevZ.nextZ = p.nextZ;
  72031. if (p.nextZ)
  72032. p.nextZ.prevZ = p.prevZ;
  72033. }
  72034. /**
  72035. * return a percentage difference between the polygon area and its triangulation area;
  72036. * used to verify correctness of triangulation
  72037. */
  72038. function deviation(data, holeIndices, dim, triangles) {
  72039. var hasHoles = holeIndices && holeIndices.length;
  72040. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  72041. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  72042. if (hasHoles) {
  72043. for (var i = 0, len = holeIndices.length; i < len; i++) {
  72044. var start = holeIndices[i] * dim;
  72045. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  72046. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  72047. }
  72048. }
  72049. var trianglesArea = 0;
  72050. for (i = 0; i < triangles.length; i += 3) {
  72051. var a = triangles[i] * dim;
  72052. var b = triangles[i + 1] * dim;
  72053. var c = triangles[i + 2] * dim;
  72054. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  72055. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  72056. }
  72057. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  72058. }
  72059. Earcut.deviation = deviation;
  72060. ;
  72061. function signedArea(data, start, end, dim) {
  72062. var sum = 0;
  72063. for (var i = start, j = end - dim; i < end; i += dim) {
  72064. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  72065. j = i;
  72066. }
  72067. return sum;
  72068. }
  72069. /**
  72070. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  72071. */
  72072. function flatten(data) {
  72073. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  72074. for (var i = 0; i < data.length; i++) {
  72075. for (var j = 0; j < data[i].length; j++) {
  72076. for (var d = 0; d < dim; d++)
  72077. result.vertices.push(data[i][j][d]);
  72078. }
  72079. if (i > 0) {
  72080. holeIndex += data[i - 1].length;
  72081. result.holes.push(holeIndex);
  72082. }
  72083. }
  72084. return result;
  72085. }
  72086. Earcut.flatten = flatten;
  72087. ;
  72088. })(Earcut || (Earcut = {}));
  72089. //# sourceMappingURL=babylon.earcut.js.map
  72090. var BABYLON;
  72091. (function (BABYLON) {
  72092. var IndexedVector2 = /** @class */ (function (_super) {
  72093. __extends(IndexedVector2, _super);
  72094. function IndexedVector2(original, index) {
  72095. var _this = _super.call(this, original.x, original.y) || this;
  72096. _this.index = index;
  72097. return _this;
  72098. }
  72099. return IndexedVector2;
  72100. }(BABYLON.Vector2));
  72101. var PolygonPoints = /** @class */ (function () {
  72102. function PolygonPoints() {
  72103. this.elements = new Array();
  72104. }
  72105. PolygonPoints.prototype.add = function (originalPoints) {
  72106. var _this = this;
  72107. var result = new Array();
  72108. originalPoints.forEach(function (point) {
  72109. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  72110. var newPoint = new IndexedVector2(point, _this.elements.length);
  72111. result.push(newPoint);
  72112. _this.elements.push(newPoint);
  72113. }
  72114. });
  72115. return result;
  72116. };
  72117. PolygonPoints.prototype.computeBounds = function () {
  72118. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  72119. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  72120. this.elements.forEach(function (point) {
  72121. // x
  72122. if (point.x < lmin.x) {
  72123. lmin.x = point.x;
  72124. }
  72125. else if (point.x > lmax.x) {
  72126. lmax.x = point.x;
  72127. }
  72128. // y
  72129. if (point.y < lmin.y) {
  72130. lmin.y = point.y;
  72131. }
  72132. else if (point.y > lmax.y) {
  72133. lmax.y = point.y;
  72134. }
  72135. });
  72136. return {
  72137. min: lmin,
  72138. max: lmax,
  72139. width: lmax.x - lmin.x,
  72140. height: lmax.y - lmin.y
  72141. };
  72142. };
  72143. return PolygonPoints;
  72144. }());
  72145. var Polygon = /** @class */ (function () {
  72146. function Polygon() {
  72147. }
  72148. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  72149. return [
  72150. new BABYLON.Vector2(xmin, ymin),
  72151. new BABYLON.Vector2(xmax, ymin),
  72152. new BABYLON.Vector2(xmax, ymax),
  72153. new BABYLON.Vector2(xmin, ymax)
  72154. ];
  72155. };
  72156. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  72157. if (cx === void 0) { cx = 0; }
  72158. if (cy === void 0) { cy = 0; }
  72159. if (numberOfSides === void 0) { numberOfSides = 32; }
  72160. var result = new Array();
  72161. var angle = 0;
  72162. var increment = (Math.PI * 2) / numberOfSides;
  72163. for (var i = 0; i < numberOfSides; i++) {
  72164. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  72165. angle -= increment;
  72166. }
  72167. return result;
  72168. };
  72169. Polygon.Parse = function (input) {
  72170. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  72171. var i, result = [];
  72172. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  72173. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  72174. }
  72175. return result;
  72176. };
  72177. Polygon.StartingAt = function (x, y) {
  72178. return BABYLON.Path2.StartingAt(x, y);
  72179. };
  72180. return Polygon;
  72181. }());
  72182. BABYLON.Polygon = Polygon;
  72183. var PolygonMeshBuilder = /** @class */ (function () {
  72184. function PolygonMeshBuilder(name, contours, scene) {
  72185. this._points = new PolygonPoints();
  72186. this._outlinepoints = new PolygonPoints();
  72187. this._holes = new Array();
  72188. this._epoints = new Array();
  72189. this._eholes = new Array();
  72190. this._name = name;
  72191. this._scene = scene;
  72192. var points;
  72193. if (contours instanceof BABYLON.Path2) {
  72194. points = contours.getPoints();
  72195. }
  72196. else {
  72197. points = contours;
  72198. }
  72199. this._addToepoint(points);
  72200. this._points.add(points);
  72201. this._outlinepoints.add(points);
  72202. }
  72203. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  72204. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  72205. var p = points_1[_i];
  72206. this._epoints.push(p.x, p.y);
  72207. }
  72208. };
  72209. PolygonMeshBuilder.prototype.addHole = function (hole) {
  72210. this._points.add(hole);
  72211. var holepoints = new PolygonPoints();
  72212. holepoints.add(hole);
  72213. this._holes.push(holepoints);
  72214. this._eholes.push(this._epoints.length / 2);
  72215. this._addToepoint(hole);
  72216. return this;
  72217. };
  72218. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  72219. var _this = this;
  72220. if (updatable === void 0) { updatable = false; }
  72221. if (depth === void 0) { depth = 0; }
  72222. var result = new BABYLON.Mesh(this._name, this._scene);
  72223. var normals = new Array();
  72224. var positions = new Array();
  72225. var uvs = new Array();
  72226. var bounds = this._points.computeBounds();
  72227. this._points.elements.forEach(function (p) {
  72228. normals.push(0, 1.0, 0);
  72229. positions.push(p.x, 0, p.y);
  72230. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  72231. });
  72232. var indices = new Array();
  72233. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  72234. for (var i = 0; i < res.length; i++) {
  72235. indices.push(res[i]);
  72236. }
  72237. if (depth > 0) {
  72238. var positionscount = (positions.length / 3); //get the current pointcount
  72239. this._points.elements.forEach(function (p) {
  72240. normals.push(0, -1.0, 0);
  72241. positions.push(p.x, -depth, p.y);
  72242. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  72243. });
  72244. var totalCount = indices.length;
  72245. for (var i = 0; i < totalCount; i += 3) {
  72246. var i0 = indices[i + 0];
  72247. var i1 = indices[i + 1];
  72248. var i2 = indices[i + 2];
  72249. indices.push(i2 + positionscount);
  72250. indices.push(i1 + positionscount);
  72251. indices.push(i0 + positionscount);
  72252. }
  72253. //Add the sides
  72254. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  72255. this._holes.forEach(function (hole) {
  72256. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  72257. });
  72258. }
  72259. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  72260. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  72261. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  72262. result.setIndices(indices);
  72263. return result;
  72264. };
  72265. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  72266. var StartIndex = positions.length / 3;
  72267. var ulength = 0;
  72268. for (var i = 0; i < points.elements.length; i++) {
  72269. var p = points.elements[i];
  72270. var p1;
  72271. if ((i + 1) > points.elements.length - 1) {
  72272. p1 = points.elements[0];
  72273. }
  72274. else {
  72275. p1 = points.elements[i + 1];
  72276. }
  72277. positions.push(p.x, 0, p.y);
  72278. positions.push(p.x, -depth, p.y);
  72279. positions.push(p1.x, 0, p1.y);
  72280. positions.push(p1.x, -depth, p1.y);
  72281. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  72282. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  72283. var v3 = v2.subtract(v1);
  72284. var v4 = new BABYLON.Vector3(0, 1, 0);
  72285. var vn = BABYLON.Vector3.Cross(v3, v4);
  72286. vn = vn.normalize();
  72287. uvs.push(ulength / bounds.width, 0);
  72288. uvs.push(ulength / bounds.width, 1);
  72289. ulength += v3.length();
  72290. uvs.push((ulength / bounds.width), 0);
  72291. uvs.push((ulength / bounds.width), 1);
  72292. if (!flip) {
  72293. normals.push(-vn.x, -vn.y, -vn.z);
  72294. normals.push(-vn.x, -vn.y, -vn.z);
  72295. normals.push(-vn.x, -vn.y, -vn.z);
  72296. normals.push(-vn.x, -vn.y, -vn.z);
  72297. indices.push(StartIndex);
  72298. indices.push(StartIndex + 1);
  72299. indices.push(StartIndex + 2);
  72300. indices.push(StartIndex + 1);
  72301. indices.push(StartIndex + 3);
  72302. indices.push(StartIndex + 2);
  72303. }
  72304. else {
  72305. normals.push(vn.x, vn.y, vn.z);
  72306. normals.push(vn.x, vn.y, vn.z);
  72307. normals.push(vn.x, vn.y, vn.z);
  72308. normals.push(vn.x, vn.y, vn.z);
  72309. indices.push(StartIndex);
  72310. indices.push(StartIndex + 2);
  72311. indices.push(StartIndex + 1);
  72312. indices.push(StartIndex + 1);
  72313. indices.push(StartIndex + 2);
  72314. indices.push(StartIndex + 3);
  72315. }
  72316. StartIndex += 4;
  72317. }
  72318. ;
  72319. };
  72320. return PolygonMeshBuilder;
  72321. }());
  72322. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  72323. })(BABYLON || (BABYLON = {}));
  72324. //# sourceMappingURL=babylon.polygonMesh.js.map
  72325. var BABYLON;
  72326. (function (BABYLON) {
  72327. // Unique ID when we import meshes from Babylon to CSG
  72328. var currentCSGMeshId = 0;
  72329. // # class Vertex
  72330. // Represents a vertex of a polygon. Use your own vertex class instead of this
  72331. // one to provide additional features like texture coordinates and vertex
  72332. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  72333. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  72334. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  72335. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  72336. // is not used anywhere else.
  72337. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  72338. var Vertex = /** @class */ (function () {
  72339. function Vertex(pos, normal, uv) {
  72340. this.pos = pos;
  72341. this.normal = normal;
  72342. this.uv = uv;
  72343. }
  72344. Vertex.prototype.clone = function () {
  72345. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  72346. };
  72347. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  72348. // orientation of a polygon is flipped.
  72349. Vertex.prototype.flip = function () {
  72350. this.normal = this.normal.scale(-1);
  72351. };
  72352. // Create a new vertex between this vertex and `other` by linearly
  72353. // interpolating all properties using a parameter of `t`. Subclasses should
  72354. // override this to interpolate additional properties.
  72355. Vertex.prototype.interpolate = function (other, t) {
  72356. 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));
  72357. };
  72358. return Vertex;
  72359. }());
  72360. // # class Plane
  72361. // Represents a plane in 3D space.
  72362. var Plane = /** @class */ (function () {
  72363. function Plane(normal, w) {
  72364. this.normal = normal;
  72365. this.w = w;
  72366. }
  72367. Plane.FromPoints = function (a, b, c) {
  72368. var v0 = c.subtract(a);
  72369. var v1 = b.subtract(a);
  72370. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  72371. return null;
  72372. }
  72373. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  72374. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  72375. };
  72376. Plane.prototype.clone = function () {
  72377. return new Plane(this.normal.clone(), this.w);
  72378. };
  72379. Plane.prototype.flip = function () {
  72380. this.normal.scaleInPlace(-1);
  72381. this.w = -this.w;
  72382. };
  72383. // Split `polygon` by this plane if needed, then put the polygon or polygon
  72384. // fragments in the appropriate lists. Coplanar polygons go into either
  72385. // `coplanarFront` or `coplanarBack` depending on their orientation with
  72386. // respect to this plane. Polygons in front or in back of this plane go into
  72387. // either `front` or `back`.
  72388. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  72389. var COPLANAR = 0;
  72390. var FRONT = 1;
  72391. var BACK = 2;
  72392. var SPANNING = 3;
  72393. // Classify each point as well as the entire polygon into one of the above
  72394. // four classes.
  72395. var polygonType = 0;
  72396. var types = [];
  72397. var i;
  72398. var t;
  72399. for (i = 0; i < polygon.vertices.length; i++) {
  72400. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  72401. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  72402. polygonType |= type;
  72403. types.push(type);
  72404. }
  72405. // Put the polygon in the correct list, splitting it when necessary.
  72406. switch (polygonType) {
  72407. case COPLANAR:
  72408. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  72409. break;
  72410. case FRONT:
  72411. front.push(polygon);
  72412. break;
  72413. case BACK:
  72414. back.push(polygon);
  72415. break;
  72416. case SPANNING:
  72417. var f = [], b = [];
  72418. for (i = 0; i < polygon.vertices.length; i++) {
  72419. var j = (i + 1) % polygon.vertices.length;
  72420. var ti = types[i], tj = types[j];
  72421. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  72422. if (ti !== BACK)
  72423. f.push(vi);
  72424. if (ti !== FRONT)
  72425. b.push(ti !== BACK ? vi.clone() : vi);
  72426. if ((ti | tj) === SPANNING) {
  72427. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  72428. var v = vi.interpolate(vj, t);
  72429. f.push(v);
  72430. b.push(v.clone());
  72431. }
  72432. }
  72433. var poly;
  72434. if (f.length >= 3) {
  72435. poly = new Polygon(f, polygon.shared);
  72436. if (poly.plane)
  72437. front.push(poly);
  72438. }
  72439. if (b.length >= 3) {
  72440. poly = new Polygon(b, polygon.shared);
  72441. if (poly.plane)
  72442. back.push(poly);
  72443. }
  72444. break;
  72445. }
  72446. };
  72447. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  72448. // point is on the plane.
  72449. Plane.EPSILON = 1e-5;
  72450. return Plane;
  72451. }());
  72452. // # class Polygon
  72453. // Represents a convex polygon. The vertices used to initialize a polygon must
  72454. // be coplanar and form a convex loop.
  72455. //
  72456. // Each convex polygon has a `shared` property, which is shared between all
  72457. // polygons that are clones of each other or were split from the same polygon.
  72458. // This can be used to define per-polygon properties (such as surface color).
  72459. var Polygon = /** @class */ (function () {
  72460. function Polygon(vertices, shared) {
  72461. this.vertices = vertices;
  72462. this.shared = shared;
  72463. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  72464. }
  72465. Polygon.prototype.clone = function () {
  72466. var vertices = this.vertices.map(function (v) { return v.clone(); });
  72467. return new Polygon(vertices, this.shared);
  72468. };
  72469. Polygon.prototype.flip = function () {
  72470. this.vertices.reverse().map(function (v) { v.flip(); });
  72471. this.plane.flip();
  72472. };
  72473. return Polygon;
  72474. }());
  72475. // # class Node
  72476. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  72477. // by picking a polygon to split along. That polygon (and all other coplanar
  72478. // polygons) are added directly to that node and the other polygons are added to
  72479. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  72480. // no distinction between internal and leaf nodes.
  72481. var Node = /** @class */ (function () {
  72482. function Node(polygons) {
  72483. this.plane = null;
  72484. this.front = null;
  72485. this.back = null;
  72486. this.polygons = new Array();
  72487. if (polygons) {
  72488. this.build(polygons);
  72489. }
  72490. }
  72491. Node.prototype.clone = function () {
  72492. var node = new Node();
  72493. node.plane = this.plane && this.plane.clone();
  72494. node.front = this.front && this.front.clone();
  72495. node.back = this.back && this.back.clone();
  72496. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  72497. return node;
  72498. };
  72499. // Convert solid space to empty space and empty space to solid space.
  72500. Node.prototype.invert = function () {
  72501. for (var i = 0; i < this.polygons.length; i++) {
  72502. this.polygons[i].flip();
  72503. }
  72504. if (this.plane) {
  72505. this.plane.flip();
  72506. }
  72507. if (this.front) {
  72508. this.front.invert();
  72509. }
  72510. if (this.back) {
  72511. this.back.invert();
  72512. }
  72513. var temp = this.front;
  72514. this.front = this.back;
  72515. this.back = temp;
  72516. };
  72517. // Recursively remove all polygons in `polygons` that are inside this BSP
  72518. // tree.
  72519. Node.prototype.clipPolygons = function (polygons) {
  72520. if (!this.plane)
  72521. return polygons.slice();
  72522. var front = new Array(), back = new Array();
  72523. for (var i = 0; i < polygons.length; i++) {
  72524. this.plane.splitPolygon(polygons[i], front, back, front, back);
  72525. }
  72526. if (this.front) {
  72527. front = this.front.clipPolygons(front);
  72528. }
  72529. if (this.back) {
  72530. back = this.back.clipPolygons(back);
  72531. }
  72532. else {
  72533. back = [];
  72534. }
  72535. return front.concat(back);
  72536. };
  72537. // Remove all polygons in this BSP tree that are inside the other BSP tree
  72538. // `bsp`.
  72539. Node.prototype.clipTo = function (bsp) {
  72540. this.polygons = bsp.clipPolygons(this.polygons);
  72541. if (this.front)
  72542. this.front.clipTo(bsp);
  72543. if (this.back)
  72544. this.back.clipTo(bsp);
  72545. };
  72546. // Return a list of all polygons in this BSP tree.
  72547. Node.prototype.allPolygons = function () {
  72548. var polygons = this.polygons.slice();
  72549. if (this.front)
  72550. polygons = polygons.concat(this.front.allPolygons());
  72551. if (this.back)
  72552. polygons = polygons.concat(this.back.allPolygons());
  72553. return polygons;
  72554. };
  72555. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  72556. // new polygons are filtered down to the bottom of the tree and become new
  72557. // nodes there. Each set of polygons is partitioned using the first polygon
  72558. // (no heuristic is used to pick a good split).
  72559. Node.prototype.build = function (polygons) {
  72560. if (!polygons.length)
  72561. return;
  72562. if (!this.plane)
  72563. this.plane = polygons[0].plane.clone();
  72564. var front = new Array(), back = new Array();
  72565. for (var i = 0; i < polygons.length; i++) {
  72566. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  72567. }
  72568. if (front.length) {
  72569. if (!this.front)
  72570. this.front = new Node();
  72571. this.front.build(front);
  72572. }
  72573. if (back.length) {
  72574. if (!this.back)
  72575. this.back = new Node();
  72576. this.back.build(back);
  72577. }
  72578. };
  72579. return Node;
  72580. }());
  72581. var CSG = /** @class */ (function () {
  72582. function CSG() {
  72583. this.polygons = new Array();
  72584. }
  72585. // Convert BABYLON.Mesh to BABYLON.CSG
  72586. CSG.FromMesh = function (mesh) {
  72587. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  72588. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  72589. if (mesh instanceof BABYLON.Mesh) {
  72590. mesh.computeWorldMatrix(true);
  72591. matrix = mesh.getWorldMatrix();
  72592. meshPosition = mesh.position.clone();
  72593. meshRotation = mesh.rotation.clone();
  72594. if (mesh.rotationQuaternion) {
  72595. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  72596. }
  72597. meshScaling = mesh.scaling.clone();
  72598. }
  72599. else {
  72600. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  72601. }
  72602. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  72603. var subMeshes = mesh.subMeshes;
  72604. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  72605. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  72606. vertices = [];
  72607. for (var j = 0; j < 3; j++) {
  72608. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  72609. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  72610. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  72611. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  72612. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  72613. vertex = new Vertex(position, normal, uv);
  72614. vertices.push(vertex);
  72615. }
  72616. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  72617. // To handle the case of degenerated triangle
  72618. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  72619. if (polygon.plane)
  72620. polygons.push(polygon);
  72621. }
  72622. }
  72623. var csg = CSG.FromPolygons(polygons);
  72624. csg.matrix = matrix;
  72625. csg.position = meshPosition;
  72626. csg.rotation = meshRotation;
  72627. csg.scaling = meshScaling;
  72628. csg.rotationQuaternion = meshRotationQuaternion;
  72629. currentCSGMeshId++;
  72630. return csg;
  72631. };
  72632. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  72633. CSG.FromPolygons = function (polygons) {
  72634. var csg = new CSG();
  72635. csg.polygons = polygons;
  72636. return csg;
  72637. };
  72638. CSG.prototype.clone = function () {
  72639. var csg = new CSG();
  72640. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  72641. csg.copyTransformAttributes(this);
  72642. return csg;
  72643. };
  72644. CSG.prototype.union = function (csg) {
  72645. var a = new Node(this.clone().polygons);
  72646. var b = new Node(csg.clone().polygons);
  72647. a.clipTo(b);
  72648. b.clipTo(a);
  72649. b.invert();
  72650. b.clipTo(a);
  72651. b.invert();
  72652. a.build(b.allPolygons());
  72653. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72654. };
  72655. CSG.prototype.unionInPlace = function (csg) {
  72656. var a = new Node(this.polygons);
  72657. var b = new Node(csg.polygons);
  72658. a.clipTo(b);
  72659. b.clipTo(a);
  72660. b.invert();
  72661. b.clipTo(a);
  72662. b.invert();
  72663. a.build(b.allPolygons());
  72664. this.polygons = a.allPolygons();
  72665. };
  72666. CSG.prototype.subtract = function (csg) {
  72667. var a = new Node(this.clone().polygons);
  72668. var b = new Node(csg.clone().polygons);
  72669. a.invert();
  72670. a.clipTo(b);
  72671. b.clipTo(a);
  72672. b.invert();
  72673. b.clipTo(a);
  72674. b.invert();
  72675. a.build(b.allPolygons());
  72676. a.invert();
  72677. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72678. };
  72679. CSG.prototype.subtractInPlace = function (csg) {
  72680. var a = new Node(this.polygons);
  72681. var b = new Node(csg.polygons);
  72682. a.invert();
  72683. a.clipTo(b);
  72684. b.clipTo(a);
  72685. b.invert();
  72686. b.clipTo(a);
  72687. b.invert();
  72688. a.build(b.allPolygons());
  72689. a.invert();
  72690. this.polygons = a.allPolygons();
  72691. };
  72692. CSG.prototype.intersect = function (csg) {
  72693. var a = new Node(this.clone().polygons);
  72694. var b = new Node(csg.clone().polygons);
  72695. a.invert();
  72696. b.clipTo(a);
  72697. b.invert();
  72698. a.clipTo(b);
  72699. b.clipTo(a);
  72700. a.build(b.allPolygons());
  72701. a.invert();
  72702. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72703. };
  72704. CSG.prototype.intersectInPlace = function (csg) {
  72705. var a = new Node(this.polygons);
  72706. var b = new Node(csg.polygons);
  72707. a.invert();
  72708. b.clipTo(a);
  72709. b.invert();
  72710. a.clipTo(b);
  72711. b.clipTo(a);
  72712. a.build(b.allPolygons());
  72713. a.invert();
  72714. this.polygons = a.allPolygons();
  72715. };
  72716. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  72717. // not modified.
  72718. CSG.prototype.inverse = function () {
  72719. var csg = this.clone();
  72720. csg.inverseInPlace();
  72721. return csg;
  72722. };
  72723. CSG.prototype.inverseInPlace = function () {
  72724. this.polygons.map(function (p) { p.flip(); });
  72725. };
  72726. // This is used to keep meshes transformations so they can be restored
  72727. // when we build back a Babylon Mesh
  72728. // NB : All CSG operations are performed in world coordinates
  72729. CSG.prototype.copyTransformAttributes = function (csg) {
  72730. this.matrix = csg.matrix;
  72731. this.position = csg.position;
  72732. this.rotation = csg.rotation;
  72733. this.scaling = csg.scaling;
  72734. this.rotationQuaternion = csg.rotationQuaternion;
  72735. return this;
  72736. };
  72737. // Build Raw mesh from CSG
  72738. // Coordinates here are in world space
  72739. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  72740. var matrix = this.matrix.clone();
  72741. matrix.invert();
  72742. 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;
  72743. if (keepSubMeshes) {
  72744. // Sort Polygons, since subMeshes are indices range
  72745. polygons.sort(function (a, b) {
  72746. if (a.shared.meshId === b.shared.meshId) {
  72747. return a.shared.subMeshId - b.shared.subMeshId;
  72748. }
  72749. else {
  72750. return a.shared.meshId - b.shared.meshId;
  72751. }
  72752. });
  72753. }
  72754. for (var i = 0, il = polygons.length; i < il; i++) {
  72755. polygon = polygons[i];
  72756. // Building SubMeshes
  72757. if (!subMesh_dict[polygon.shared.meshId]) {
  72758. subMesh_dict[polygon.shared.meshId] = {};
  72759. }
  72760. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  72761. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  72762. indexStart: +Infinity,
  72763. indexEnd: -Infinity,
  72764. materialIndex: polygon.shared.materialIndex
  72765. };
  72766. }
  72767. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  72768. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  72769. polygonIndices[0] = 0;
  72770. polygonIndices[1] = j - 1;
  72771. polygonIndices[2] = j;
  72772. for (var k = 0; k < 3; k++) {
  72773. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  72774. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  72775. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  72776. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  72777. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  72778. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  72779. // Check if 2 points can be merged
  72780. if (!(typeof vertex_idx !== 'undefined' &&
  72781. normals[vertex_idx * 3] === localNormal.x &&
  72782. normals[vertex_idx * 3 + 1] === localNormal.y &&
  72783. normals[vertex_idx * 3 + 2] === localNormal.z &&
  72784. uvs[vertex_idx * 2] === uv.x &&
  72785. uvs[vertex_idx * 2 + 1] === uv.y)) {
  72786. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  72787. uvs.push(uv.x, uv.y);
  72788. normals.push(normal.x, normal.y, normal.z);
  72789. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  72790. }
  72791. indices.push(vertex_idx);
  72792. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  72793. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  72794. currentIndex++;
  72795. }
  72796. }
  72797. }
  72798. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  72799. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  72800. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  72801. mesh.setIndices(indices, null);
  72802. if (keepSubMeshes) {
  72803. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  72804. var materialIndexOffset = 0, materialMaxIndex;
  72805. mesh.subMeshes = new Array();
  72806. for (var m in subMesh_dict) {
  72807. materialMaxIndex = -1;
  72808. for (var sm in subMesh_dict[m]) {
  72809. subMesh_obj = subMesh_dict[m][sm];
  72810. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  72811. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  72812. }
  72813. materialIndexOffset += ++materialMaxIndex;
  72814. }
  72815. }
  72816. return mesh;
  72817. };
  72818. // Build Mesh from CSG taking material and transforms into account
  72819. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  72820. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  72821. mesh.material = material;
  72822. mesh.position.copyFrom(this.position);
  72823. mesh.rotation.copyFrom(this.rotation);
  72824. if (this.rotationQuaternion) {
  72825. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  72826. }
  72827. mesh.scaling.copyFrom(this.scaling);
  72828. mesh.computeWorldMatrix(true);
  72829. return mesh;
  72830. };
  72831. return CSG;
  72832. }());
  72833. BABYLON.CSG = CSG;
  72834. })(BABYLON || (BABYLON = {}));
  72835. //# sourceMappingURL=babylon.csg.js.map
  72836. var BABYLON;
  72837. (function (BABYLON) {
  72838. var LensFlare = /** @class */ (function () {
  72839. function LensFlare(size, position, color, imgUrl, system) {
  72840. this.size = size;
  72841. this.position = position;
  72842. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  72843. this.color = color || new BABYLON.Color3(1, 1, 1);
  72844. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  72845. this._system = system;
  72846. system.lensFlares.push(this);
  72847. }
  72848. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  72849. return new LensFlare(size, position, color, imgUrl, system);
  72850. };
  72851. LensFlare.prototype.dispose = function () {
  72852. if (this.texture) {
  72853. this.texture.dispose();
  72854. }
  72855. // Remove from scene
  72856. var index = this._system.lensFlares.indexOf(this);
  72857. this._system.lensFlares.splice(index, 1);
  72858. };
  72859. ;
  72860. return LensFlare;
  72861. }());
  72862. BABYLON.LensFlare = LensFlare;
  72863. })(BABYLON || (BABYLON = {}));
  72864. //# sourceMappingURL=babylon.lensFlare.js.map
  72865. var BABYLON;
  72866. (function (BABYLON) {
  72867. var LensFlareSystem = /** @class */ (function () {
  72868. function LensFlareSystem(name, emitter, scene) {
  72869. this.name = name;
  72870. this.lensFlares = new Array();
  72871. this.borderLimit = 300;
  72872. this.viewportBorder = 0;
  72873. this.layerMask = 0x0FFFFFFF;
  72874. this._vertexBuffers = {};
  72875. this._isEnabled = true;
  72876. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72877. this._emitter = emitter;
  72878. this.id = name;
  72879. scene.lensFlareSystems.push(this);
  72880. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  72881. var engine = scene.getEngine();
  72882. // VBO
  72883. var vertices = [];
  72884. vertices.push(1, 1);
  72885. vertices.push(-1, 1);
  72886. vertices.push(-1, -1);
  72887. vertices.push(1, -1);
  72888. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72889. // Indices
  72890. var indices = [];
  72891. indices.push(0);
  72892. indices.push(1);
  72893. indices.push(2);
  72894. indices.push(0);
  72895. indices.push(2);
  72896. indices.push(3);
  72897. this._indexBuffer = engine.createIndexBuffer(indices);
  72898. // Effects
  72899. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  72900. }
  72901. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  72902. get: function () {
  72903. return this._isEnabled;
  72904. },
  72905. set: function (value) {
  72906. this._isEnabled = value;
  72907. },
  72908. enumerable: true,
  72909. configurable: true
  72910. });
  72911. LensFlareSystem.prototype.getScene = function () {
  72912. return this._scene;
  72913. };
  72914. LensFlareSystem.prototype.getEmitter = function () {
  72915. return this._emitter;
  72916. };
  72917. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  72918. this._emitter = newEmitter;
  72919. };
  72920. LensFlareSystem.prototype.getEmitterPosition = function () {
  72921. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  72922. };
  72923. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  72924. var position = this.getEmitterPosition();
  72925. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  72926. this._positionX = position.x;
  72927. this._positionY = position.y;
  72928. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  72929. if (this.viewportBorder > 0) {
  72930. globalViewport.x -= this.viewportBorder;
  72931. globalViewport.y -= this.viewportBorder;
  72932. globalViewport.width += this.viewportBorder * 2;
  72933. globalViewport.height += this.viewportBorder * 2;
  72934. position.x += this.viewportBorder;
  72935. position.y += this.viewportBorder;
  72936. this._positionX += this.viewportBorder;
  72937. this._positionY += this.viewportBorder;
  72938. }
  72939. if (position.z > 0) {
  72940. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  72941. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  72942. return true;
  72943. }
  72944. return true;
  72945. }
  72946. return false;
  72947. };
  72948. LensFlareSystem.prototype._isVisible = function () {
  72949. if (!this._isEnabled || !this._scene.activeCamera) {
  72950. return false;
  72951. }
  72952. var emitterPosition = this.getEmitterPosition();
  72953. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  72954. var distance = direction.length();
  72955. direction.normalize();
  72956. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  72957. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  72958. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  72959. };
  72960. LensFlareSystem.prototype.render = function () {
  72961. if (!this._effect.isReady() || !this._scene.activeCamera)
  72962. return false;
  72963. var engine = this._scene.getEngine();
  72964. var viewport = this._scene.activeCamera.viewport;
  72965. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  72966. // Position
  72967. if (!this.computeEffectivePosition(globalViewport)) {
  72968. return false;
  72969. }
  72970. // Visibility
  72971. if (!this._isVisible()) {
  72972. return false;
  72973. }
  72974. // Intensity
  72975. var awayX;
  72976. var awayY;
  72977. if (this._positionX < this.borderLimit + globalViewport.x) {
  72978. awayX = this.borderLimit + globalViewport.x - this._positionX;
  72979. }
  72980. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  72981. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  72982. }
  72983. else {
  72984. awayX = 0;
  72985. }
  72986. if (this._positionY < this.borderLimit + globalViewport.y) {
  72987. awayY = this.borderLimit + globalViewport.y - this._positionY;
  72988. }
  72989. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  72990. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  72991. }
  72992. else {
  72993. awayY = 0;
  72994. }
  72995. var away = (awayX > awayY) ? awayX : awayY;
  72996. away -= this.viewportBorder;
  72997. if (away > this.borderLimit) {
  72998. away = this.borderLimit;
  72999. }
  73000. var intensity = 1.0 - (away / this.borderLimit);
  73001. if (intensity < 0) {
  73002. return false;
  73003. }
  73004. if (intensity > 1.0) {
  73005. intensity = 1.0;
  73006. }
  73007. if (this.viewportBorder > 0) {
  73008. globalViewport.x += this.viewportBorder;
  73009. globalViewport.y += this.viewportBorder;
  73010. globalViewport.width -= this.viewportBorder * 2;
  73011. globalViewport.height -= this.viewportBorder * 2;
  73012. this._positionX -= this.viewportBorder;
  73013. this._positionY -= this.viewportBorder;
  73014. }
  73015. // Position
  73016. var centerX = globalViewport.x + globalViewport.width / 2;
  73017. var centerY = globalViewport.y + globalViewport.height / 2;
  73018. var distX = centerX - this._positionX;
  73019. var distY = centerY - this._positionY;
  73020. // Effects
  73021. engine.enableEffect(this._effect);
  73022. engine.setState(false);
  73023. engine.setDepthBuffer(false);
  73024. // VBOs
  73025. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73026. // Flares
  73027. for (var index = 0; index < this.lensFlares.length; index++) {
  73028. var flare = this.lensFlares[index];
  73029. engine.setAlphaMode(flare.alphaMode);
  73030. var x = centerX - (distX * flare.position);
  73031. var y = centerY - (distY * flare.position);
  73032. var cw = flare.size;
  73033. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  73034. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  73035. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  73036. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  73037. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  73038. // Texture
  73039. this._effect.setTexture("textureSampler", flare.texture);
  73040. // Color
  73041. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  73042. // Draw order
  73043. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73044. }
  73045. engine.setDepthBuffer(true);
  73046. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73047. return true;
  73048. };
  73049. LensFlareSystem.prototype.dispose = function () {
  73050. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73051. if (vertexBuffer) {
  73052. vertexBuffer.dispose();
  73053. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73054. }
  73055. if (this._indexBuffer) {
  73056. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73057. this._indexBuffer = null;
  73058. }
  73059. while (this.lensFlares.length) {
  73060. this.lensFlares[0].dispose();
  73061. }
  73062. // Remove from scene
  73063. var index = this._scene.lensFlareSystems.indexOf(this);
  73064. this._scene.lensFlareSystems.splice(index, 1);
  73065. };
  73066. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  73067. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  73068. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  73069. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  73070. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  73071. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  73072. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  73073. var parsedFlare = parsedLensFlareSystem.flares[index];
  73074. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  73075. }
  73076. return lensFlareSystem;
  73077. };
  73078. LensFlareSystem.prototype.serialize = function () {
  73079. var serializationObject = {};
  73080. serializationObject.id = this.id;
  73081. serializationObject.name = this.name;
  73082. serializationObject.emitterId = this.getEmitter().id;
  73083. serializationObject.borderLimit = this.borderLimit;
  73084. serializationObject.flares = [];
  73085. for (var index = 0; index < this.lensFlares.length; index++) {
  73086. var flare = this.lensFlares[index];
  73087. serializationObject.flares.push({
  73088. size: flare.size,
  73089. position: flare.position,
  73090. color: flare.color.asArray(),
  73091. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  73092. });
  73093. }
  73094. return serializationObject;
  73095. };
  73096. return LensFlareSystem;
  73097. }());
  73098. BABYLON.LensFlareSystem = LensFlareSystem;
  73099. })(BABYLON || (BABYLON = {}));
  73100. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  73101. var BABYLON;
  73102. (function (BABYLON) {
  73103. /**
  73104. * This is a holder class for the physics joint created by the physics plugin.
  73105. * It holds a set of functions to control the underlying joint.
  73106. */
  73107. var PhysicsJoint = /** @class */ (function () {
  73108. function PhysicsJoint(type, jointData) {
  73109. this.type = type;
  73110. this.jointData = jointData;
  73111. jointData.nativeParams = jointData.nativeParams || {};
  73112. }
  73113. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  73114. get: function () {
  73115. return this._physicsJoint;
  73116. },
  73117. set: function (newJoint) {
  73118. if (this._physicsJoint) {
  73119. //remove from the wolrd
  73120. }
  73121. this._physicsJoint = newJoint;
  73122. },
  73123. enumerable: true,
  73124. configurable: true
  73125. });
  73126. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  73127. set: function (physicsPlugin) {
  73128. this._physicsPlugin = physicsPlugin;
  73129. },
  73130. enumerable: true,
  73131. configurable: true
  73132. });
  73133. /**
  73134. * Execute a function that is physics-plugin specific.
  73135. * @param {Function} func the function that will be executed.
  73136. * It accepts two parameters: the physics world and the physics joint.
  73137. */
  73138. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  73139. func(this._physicsPlugin.world, this._physicsJoint);
  73140. };
  73141. //TODO check if the native joints are the same
  73142. //Joint Types
  73143. PhysicsJoint.DistanceJoint = 0;
  73144. PhysicsJoint.HingeJoint = 1;
  73145. PhysicsJoint.BallAndSocketJoint = 2;
  73146. PhysicsJoint.WheelJoint = 3;
  73147. PhysicsJoint.SliderJoint = 4;
  73148. //OIMO
  73149. PhysicsJoint.PrismaticJoint = 5;
  73150. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  73151. PhysicsJoint.UniversalJoint = 6;
  73152. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  73153. //Cannon
  73154. //Similar to a Ball-Joint. Different in params
  73155. PhysicsJoint.PointToPointJoint = 8;
  73156. //Cannon only at the moment
  73157. PhysicsJoint.SpringJoint = 9;
  73158. PhysicsJoint.LockJoint = 10;
  73159. return PhysicsJoint;
  73160. }());
  73161. BABYLON.PhysicsJoint = PhysicsJoint;
  73162. /**
  73163. * A class representing a physics distance joint.
  73164. */
  73165. var DistanceJoint = /** @class */ (function (_super) {
  73166. __extends(DistanceJoint, _super);
  73167. function DistanceJoint(jointData) {
  73168. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  73169. }
  73170. /**
  73171. * Update the predefined distance.
  73172. */
  73173. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  73174. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  73175. };
  73176. return DistanceJoint;
  73177. }(PhysicsJoint));
  73178. BABYLON.DistanceJoint = DistanceJoint;
  73179. var MotorEnabledJoint = /** @class */ (function (_super) {
  73180. __extends(MotorEnabledJoint, _super);
  73181. function MotorEnabledJoint(type, jointData) {
  73182. return _super.call(this, type, jointData) || this;
  73183. }
  73184. /**
  73185. * Set the motor values.
  73186. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73187. * @param {number} force the force to apply
  73188. * @param {number} maxForce max force for this motor.
  73189. */
  73190. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  73191. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73192. };
  73193. /**
  73194. * Set the motor's limits.
  73195. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73196. */
  73197. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73198. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73199. };
  73200. return MotorEnabledJoint;
  73201. }(PhysicsJoint));
  73202. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  73203. /**
  73204. * This class represents a single hinge physics joint
  73205. */
  73206. var HingeJoint = /** @class */ (function (_super) {
  73207. __extends(HingeJoint, _super);
  73208. function HingeJoint(jointData) {
  73209. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  73210. }
  73211. /**
  73212. * Set the motor values.
  73213. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73214. * @param {number} force the force to apply
  73215. * @param {number} maxForce max force for this motor.
  73216. */
  73217. HingeJoint.prototype.setMotor = function (force, maxForce) {
  73218. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73219. };
  73220. /**
  73221. * Set the motor's limits.
  73222. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73223. */
  73224. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73225. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73226. };
  73227. return HingeJoint;
  73228. }(MotorEnabledJoint));
  73229. BABYLON.HingeJoint = HingeJoint;
  73230. /**
  73231. * This class represents a dual hinge physics joint (same as wheel joint)
  73232. */
  73233. var Hinge2Joint = /** @class */ (function (_super) {
  73234. __extends(Hinge2Joint, _super);
  73235. function Hinge2Joint(jointData) {
  73236. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  73237. }
  73238. /**
  73239. * Set the motor values.
  73240. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73241. * @param {number} force the force to apply
  73242. * @param {number} maxForce max force for this motor.
  73243. * @param {motorIndex} the motor's index, 0 or 1.
  73244. */
  73245. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  73246. if (motorIndex === void 0) { motorIndex = 0; }
  73247. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  73248. };
  73249. /**
  73250. * Set the motor limits.
  73251. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73252. * @param {number} upperLimit the upper limit
  73253. * @param {number} lowerLimit lower limit
  73254. * @param {motorIndex} the motor's index, 0 or 1.
  73255. */
  73256. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  73257. if (motorIndex === void 0) { motorIndex = 0; }
  73258. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  73259. };
  73260. return Hinge2Joint;
  73261. }(MotorEnabledJoint));
  73262. BABYLON.Hinge2Joint = Hinge2Joint;
  73263. })(BABYLON || (BABYLON = {}));
  73264. //# sourceMappingURL=babylon.physicsJoint.js.map
  73265. var BABYLON;
  73266. (function (BABYLON) {
  73267. var PhysicsImpostor = /** @class */ (function () {
  73268. function PhysicsImpostor(object, type, _options, _scene) {
  73269. if (_options === void 0) { _options = { mass: 0 }; }
  73270. var _this = this;
  73271. this.object = object;
  73272. this.type = type;
  73273. this._options = _options;
  73274. this._scene = _scene;
  73275. this._bodyUpdateRequired = false;
  73276. this._onBeforePhysicsStepCallbacks = new Array();
  73277. this._onAfterPhysicsStepCallbacks = new Array();
  73278. this._onPhysicsCollideCallbacks = [];
  73279. this._deltaPosition = BABYLON.Vector3.Zero();
  73280. this._isDisposed = false;
  73281. //temp variables for parent rotation calculations
  73282. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  73283. this._tmpQuat = new BABYLON.Quaternion();
  73284. this._tmpQuat2 = new BABYLON.Quaternion();
  73285. /**
  73286. * this function is executed by the physics engine.
  73287. */
  73288. this.beforeStep = function () {
  73289. if (!_this._physicsEngine) {
  73290. return;
  73291. }
  73292. _this.object.translate(_this._deltaPosition, -1);
  73293. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  73294. _this.object.computeWorldMatrix(false);
  73295. if (_this.object.parent && _this.object.rotationQuaternion) {
  73296. _this.getParentsRotation();
  73297. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  73298. }
  73299. else {
  73300. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  73301. }
  73302. if (!_this._options.disableBidirectionalTransformation) {
  73303. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  73304. }
  73305. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  73306. func(_this);
  73307. });
  73308. };
  73309. /**
  73310. * this function is executed by the physics engine.
  73311. */
  73312. this.afterStep = function () {
  73313. if (!_this._physicsEngine) {
  73314. return;
  73315. }
  73316. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  73317. func(_this);
  73318. });
  73319. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  73320. // object has now its world rotation. needs to be converted to local.
  73321. if (_this.object.parent && _this.object.rotationQuaternion) {
  73322. _this.getParentsRotation();
  73323. _this._tmpQuat.conjugateInPlace();
  73324. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  73325. }
  73326. // take the position set and make it the absolute position of this object.
  73327. _this.object.setAbsolutePosition(_this.object.position);
  73328. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  73329. _this.object.translate(_this._deltaPosition, 1);
  73330. };
  73331. /**
  73332. * Legacy collision detection event support
  73333. */
  73334. this.onCollideEvent = null;
  73335. //event and body object due to cannon's event-based architecture.
  73336. this.onCollide = function (e) {
  73337. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  73338. return;
  73339. }
  73340. if (!_this._physicsEngine) {
  73341. return;
  73342. }
  73343. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  73344. if (otherImpostor) {
  73345. // Legacy collision detection event support
  73346. if (_this.onCollideEvent) {
  73347. _this.onCollideEvent(_this, otherImpostor);
  73348. }
  73349. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  73350. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  73351. }).forEach(function (obj) {
  73352. obj.callback(_this, otherImpostor);
  73353. });
  73354. }
  73355. };
  73356. //sanity check!
  73357. if (!this.object) {
  73358. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  73359. return;
  73360. }
  73361. //legacy support for old syntax.
  73362. if (!this._scene && object.getScene) {
  73363. this._scene = object.getScene();
  73364. }
  73365. if (!this._scene) {
  73366. return;
  73367. }
  73368. this._physicsEngine = this._scene.getPhysicsEngine();
  73369. if (!this._physicsEngine) {
  73370. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  73371. }
  73372. else {
  73373. //set the object's quaternion, if not set
  73374. if (!this.object.rotationQuaternion) {
  73375. if (this.object.rotation) {
  73376. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  73377. }
  73378. else {
  73379. this.object.rotationQuaternion = new BABYLON.Quaternion();
  73380. }
  73381. }
  73382. //default options params
  73383. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  73384. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  73385. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  73386. this._joints = [];
  73387. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  73388. if (!this.object.parent || this._options.ignoreParent) {
  73389. this._init();
  73390. }
  73391. else if (this.object.parent.physicsImpostor) {
  73392. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  73393. }
  73394. }
  73395. }
  73396. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  73397. get: function () {
  73398. return this._isDisposed;
  73399. },
  73400. enumerable: true,
  73401. configurable: true
  73402. });
  73403. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  73404. get: function () {
  73405. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  73406. },
  73407. set: function (value) {
  73408. this.setMass(value);
  73409. },
  73410. enumerable: true,
  73411. configurable: true
  73412. });
  73413. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  73414. get: function () {
  73415. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  73416. },
  73417. set: function (value) {
  73418. if (!this._physicsEngine) {
  73419. return;
  73420. }
  73421. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  73422. },
  73423. enumerable: true,
  73424. configurable: true
  73425. });
  73426. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  73427. get: function () {
  73428. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  73429. },
  73430. set: function (value) {
  73431. if (!this._physicsEngine) {
  73432. return;
  73433. }
  73434. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  73435. },
  73436. enumerable: true,
  73437. configurable: true
  73438. });
  73439. /**
  73440. * This function will completly initialize this impostor.
  73441. * It will create a new body - but only if this mesh has no parent.
  73442. * If it has, this impostor will not be used other than to define the impostor
  73443. * of the child mesh.
  73444. */
  73445. PhysicsImpostor.prototype._init = function () {
  73446. if (!this._physicsEngine) {
  73447. return;
  73448. }
  73449. this._physicsEngine.removeImpostor(this);
  73450. this.physicsBody = null;
  73451. this._parent = this._parent || this._getPhysicsParent();
  73452. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  73453. this._physicsEngine.addImpostor(this);
  73454. }
  73455. };
  73456. PhysicsImpostor.prototype._getPhysicsParent = function () {
  73457. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  73458. var parentMesh = this.object.parent;
  73459. return parentMesh.physicsImpostor;
  73460. }
  73461. return null;
  73462. };
  73463. /**
  73464. * Should a new body be generated.
  73465. */
  73466. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  73467. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  73468. };
  73469. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  73470. this.forceUpdate();
  73471. };
  73472. /**
  73473. * Force a regeneration of this or the parent's impostor's body.
  73474. * Use under cautious - This will remove all joints already implemented.
  73475. */
  73476. PhysicsImpostor.prototype.forceUpdate = function () {
  73477. this._init();
  73478. if (this.parent && !this._options.ignoreParent) {
  73479. this.parent.forceUpdate();
  73480. }
  73481. };
  73482. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  73483. /*public get mesh(): AbstractMesh {
  73484. return this._mesh;
  73485. }*/
  73486. /**
  73487. * Gets the body that holds this impostor. Either its own, or its parent.
  73488. */
  73489. get: function () {
  73490. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  73491. },
  73492. /**
  73493. * Set the physics body. Used mainly by the physics engine/plugin
  73494. */
  73495. set: function (physicsBody) {
  73496. if (this._physicsBody && this._physicsEngine) {
  73497. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  73498. }
  73499. this._physicsBody = physicsBody;
  73500. this.resetUpdateFlags();
  73501. },
  73502. enumerable: true,
  73503. configurable: true
  73504. });
  73505. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  73506. get: function () {
  73507. return !this._options.ignoreParent && this._parent ? this._parent : null;
  73508. },
  73509. set: function (value) {
  73510. this._parent = value;
  73511. },
  73512. enumerable: true,
  73513. configurable: true
  73514. });
  73515. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  73516. this._bodyUpdateRequired = false;
  73517. };
  73518. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  73519. if (this.object.getBoundingInfo) {
  73520. var q = this.object.rotationQuaternion;
  73521. //reset rotation
  73522. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  73523. //calculate the world matrix with no rotation
  73524. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73525. var boundingInfo = this.object.getBoundingInfo();
  73526. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  73527. //bring back the rotation
  73528. this.object.rotationQuaternion = q;
  73529. //calculate the world matrix with the new rotation
  73530. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73531. return size;
  73532. }
  73533. else {
  73534. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  73535. }
  73536. };
  73537. PhysicsImpostor.prototype.getObjectCenter = function () {
  73538. if (this.object.getBoundingInfo) {
  73539. var boundingInfo = this.object.getBoundingInfo();
  73540. return boundingInfo.boundingBox.centerWorld;
  73541. }
  73542. else {
  73543. return this.object.position;
  73544. }
  73545. };
  73546. /**
  73547. * Get a specific parametes from the options parameter.
  73548. */
  73549. PhysicsImpostor.prototype.getParam = function (paramName) {
  73550. return this._options[paramName];
  73551. };
  73552. /**
  73553. * Sets a specific parameter in the options given to the physics plugin
  73554. */
  73555. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  73556. this._options[paramName] = value;
  73557. this._bodyUpdateRequired = true;
  73558. };
  73559. /**
  73560. * Specifically change the body's mass option. Won't recreate the physics body object
  73561. */
  73562. PhysicsImpostor.prototype.setMass = function (mass) {
  73563. if (this.getParam("mass") !== mass) {
  73564. this.setParam("mass", mass);
  73565. }
  73566. if (this._physicsEngine) {
  73567. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  73568. }
  73569. };
  73570. PhysicsImpostor.prototype.getLinearVelocity = function () {
  73571. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  73572. };
  73573. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  73574. if (this._physicsEngine) {
  73575. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  73576. }
  73577. };
  73578. PhysicsImpostor.prototype.getAngularVelocity = function () {
  73579. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  73580. };
  73581. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  73582. if (this._physicsEngine) {
  73583. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  73584. }
  73585. };
  73586. /**
  73587. * Execute a function with the physics plugin native code.
  73588. * Provide a function the will have two variables - the world object and the physics body object.
  73589. */
  73590. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  73591. if (this._physicsEngine) {
  73592. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  73593. }
  73594. };
  73595. /**
  73596. * Register a function that will be executed before the physics world is stepping forward.
  73597. */
  73598. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  73599. this._onBeforePhysicsStepCallbacks.push(func);
  73600. };
  73601. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  73602. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  73603. if (index > -1) {
  73604. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  73605. }
  73606. else {
  73607. BABYLON.Tools.Warn("Function to remove was not found");
  73608. }
  73609. };
  73610. /**
  73611. * Register a function that will be executed after the physics step
  73612. */
  73613. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  73614. this._onAfterPhysicsStepCallbacks.push(func);
  73615. };
  73616. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  73617. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  73618. if (index > -1) {
  73619. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  73620. }
  73621. else {
  73622. BABYLON.Tools.Warn("Function to remove was not found");
  73623. }
  73624. };
  73625. /**
  73626. * register a function that will be executed when this impostor collides against a different body.
  73627. */
  73628. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  73629. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73630. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  73631. };
  73632. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  73633. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73634. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  73635. if (index > -1) {
  73636. this._onPhysicsCollideCallbacks.splice(index, 1);
  73637. }
  73638. else {
  73639. BABYLON.Tools.Warn("Function to remove was not found");
  73640. }
  73641. };
  73642. PhysicsImpostor.prototype.getParentsRotation = function () {
  73643. var parent = this.object.parent;
  73644. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  73645. while (parent) {
  73646. if (parent.rotationQuaternion) {
  73647. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  73648. }
  73649. else {
  73650. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  73651. }
  73652. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  73653. parent = parent.parent;
  73654. }
  73655. return this._tmpQuat;
  73656. };
  73657. /**
  73658. * Apply a force
  73659. */
  73660. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  73661. if (this._physicsEngine) {
  73662. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  73663. }
  73664. return this;
  73665. };
  73666. /**
  73667. * Apply an impulse
  73668. */
  73669. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  73670. if (this._physicsEngine) {
  73671. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  73672. }
  73673. return this;
  73674. };
  73675. /**
  73676. * A help function to create a joint.
  73677. */
  73678. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  73679. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  73680. this.addJoint(otherImpostor, joint);
  73681. return this;
  73682. };
  73683. /**
  73684. * Add a joint to this impostor with a different impostor.
  73685. */
  73686. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  73687. this._joints.push({
  73688. otherImpostor: otherImpostor,
  73689. joint: joint
  73690. });
  73691. if (this._physicsEngine) {
  73692. this._physicsEngine.addJoint(this, otherImpostor, joint);
  73693. }
  73694. return this;
  73695. };
  73696. /**
  73697. * Will keep this body still, in a sleep mode.
  73698. */
  73699. PhysicsImpostor.prototype.sleep = function () {
  73700. if (this._physicsEngine) {
  73701. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  73702. }
  73703. return this;
  73704. };
  73705. /**
  73706. * Wake the body up.
  73707. */
  73708. PhysicsImpostor.prototype.wakeUp = function () {
  73709. if (this._physicsEngine) {
  73710. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  73711. }
  73712. return this;
  73713. };
  73714. PhysicsImpostor.prototype.clone = function (newObject) {
  73715. if (!newObject)
  73716. return null;
  73717. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  73718. };
  73719. PhysicsImpostor.prototype.dispose = function () {
  73720. var _this = this;
  73721. //no dispose if no physics engine is available.
  73722. if (!this._physicsEngine) {
  73723. return;
  73724. }
  73725. this._joints.forEach(function (j) {
  73726. if (_this._physicsEngine) {
  73727. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  73728. }
  73729. });
  73730. //dispose the physics body
  73731. this._physicsEngine.removeImpostor(this);
  73732. if (this.parent) {
  73733. this.parent.forceUpdate();
  73734. }
  73735. else {
  73736. /*this._object.getChildMeshes().forEach(function(mesh) {
  73737. if (mesh.physicsImpostor) {
  73738. if (disposeChildren) {
  73739. mesh.physicsImpostor.dispose();
  73740. mesh.physicsImpostor = null;
  73741. }
  73742. }
  73743. })*/
  73744. }
  73745. this._isDisposed = true;
  73746. };
  73747. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  73748. this._deltaPosition.copyFrom(position);
  73749. };
  73750. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  73751. if (!this._deltaRotation) {
  73752. this._deltaRotation = new BABYLON.Quaternion();
  73753. }
  73754. this._deltaRotation.copyFrom(rotation);
  73755. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  73756. };
  73757. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  73758. if (this._physicsEngine) {
  73759. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  73760. }
  73761. return this;
  73762. };
  73763. PhysicsImpostor.prototype.getRadius = function () {
  73764. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  73765. };
  73766. /**
  73767. * Sync a bone with this impostor
  73768. * @param bone The bone to sync to the impostor.
  73769. * @param boneMesh The mesh that the bone is influencing.
  73770. * @param jointPivot The pivot of the joint / bone in local space.
  73771. * @param distToJoint Optional distance from the impostor to the joint.
  73772. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73773. */
  73774. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  73775. var tempVec = PhysicsImpostor._tmpVecs[0];
  73776. var mesh = this.object;
  73777. if (mesh.rotationQuaternion) {
  73778. if (adjustRotation) {
  73779. var tempQuat = PhysicsImpostor._tmpQuat;
  73780. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  73781. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  73782. }
  73783. else {
  73784. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  73785. }
  73786. }
  73787. tempVec.x = 0;
  73788. tempVec.y = 0;
  73789. tempVec.z = 0;
  73790. if (jointPivot) {
  73791. tempVec.x = jointPivot.x;
  73792. tempVec.y = jointPivot.y;
  73793. tempVec.z = jointPivot.z;
  73794. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  73795. if (distToJoint === undefined || distToJoint === null) {
  73796. distToJoint = jointPivot.length();
  73797. }
  73798. tempVec.x *= distToJoint;
  73799. tempVec.y *= distToJoint;
  73800. tempVec.z *= distToJoint;
  73801. }
  73802. if (bone.getParent()) {
  73803. tempVec.addInPlace(mesh.getAbsolutePosition());
  73804. bone.setAbsolutePosition(tempVec, boneMesh);
  73805. }
  73806. else {
  73807. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  73808. boneMesh.position.x -= tempVec.x;
  73809. boneMesh.position.y -= tempVec.y;
  73810. boneMesh.position.z -= tempVec.z;
  73811. }
  73812. };
  73813. /**
  73814. * Sync impostor to a bone
  73815. * @param bone The bone that the impostor will be synced to.
  73816. * @param boneMesh The mesh that the bone is influencing.
  73817. * @param jointPivot The pivot of the joint / bone in local space.
  73818. * @param distToJoint Optional distance from the impostor to the joint.
  73819. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73820. * @param boneAxis Optional vector3 axis the bone is aligned with
  73821. */
  73822. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  73823. var mesh = this.object;
  73824. if (mesh.rotationQuaternion) {
  73825. if (adjustRotation) {
  73826. var tempQuat = PhysicsImpostor._tmpQuat;
  73827. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  73828. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  73829. }
  73830. else {
  73831. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  73832. }
  73833. }
  73834. var pos = PhysicsImpostor._tmpVecs[0];
  73835. var boneDir = PhysicsImpostor._tmpVecs[1];
  73836. if (!boneAxis) {
  73837. boneAxis = PhysicsImpostor._tmpVecs[2];
  73838. boneAxis.x = 0;
  73839. boneAxis.y = 1;
  73840. boneAxis.z = 0;
  73841. }
  73842. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  73843. bone.getAbsolutePositionToRef(boneMesh, pos);
  73844. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  73845. distToJoint = jointPivot.length();
  73846. }
  73847. if (distToJoint !== undefined && distToJoint !== null) {
  73848. pos.x += boneDir.x * distToJoint;
  73849. pos.y += boneDir.y * distToJoint;
  73850. pos.z += boneDir.z * distToJoint;
  73851. }
  73852. mesh.setAbsolutePosition(pos);
  73853. };
  73854. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  73855. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  73856. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73857. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  73858. //Impostor types
  73859. PhysicsImpostor.NoImpostor = 0;
  73860. PhysicsImpostor.SphereImpostor = 1;
  73861. PhysicsImpostor.BoxImpostor = 2;
  73862. PhysicsImpostor.PlaneImpostor = 3;
  73863. PhysicsImpostor.MeshImpostor = 4;
  73864. PhysicsImpostor.CylinderImpostor = 7;
  73865. PhysicsImpostor.ParticleImpostor = 8;
  73866. PhysicsImpostor.HeightmapImpostor = 9;
  73867. return PhysicsImpostor;
  73868. }());
  73869. BABYLON.PhysicsImpostor = PhysicsImpostor;
  73870. })(BABYLON || (BABYLON = {}));
  73871. //# sourceMappingURL=babylon.physicsImpostor.js.map
  73872. var BABYLON;
  73873. (function (BABYLON) {
  73874. var PhysicsEngine = /** @class */ (function () {
  73875. function PhysicsEngine(gravity, _physicsPlugin) {
  73876. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  73877. this._physicsPlugin = _physicsPlugin;
  73878. //new methods and parameters
  73879. this._impostors = [];
  73880. this._joints = [];
  73881. if (!this._physicsPlugin.isSupported()) {
  73882. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  73883. + "Please make sure it is included.");
  73884. }
  73885. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  73886. this.setGravity(gravity);
  73887. this.setTimeStep();
  73888. }
  73889. PhysicsEngine.prototype.setGravity = function (gravity) {
  73890. this.gravity = gravity;
  73891. this._physicsPlugin.setGravity(this.gravity);
  73892. };
  73893. /**
  73894. * Set the time step of the physics engine.
  73895. * default is 1/60.
  73896. * To slow it down, enter 1/600 for example.
  73897. * To speed it up, 1/30
  73898. * @param {number} newTimeStep the new timestep to apply to this world.
  73899. */
  73900. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  73901. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  73902. this._physicsPlugin.setTimeStep(newTimeStep);
  73903. };
  73904. /**
  73905. * Get the time step of the physics engine.
  73906. */
  73907. PhysicsEngine.prototype.getTimeStep = function () {
  73908. return this._physicsPlugin.getTimeStep();
  73909. };
  73910. PhysicsEngine.prototype.dispose = function () {
  73911. this._impostors.forEach(function (impostor) {
  73912. impostor.dispose();
  73913. });
  73914. this._physicsPlugin.dispose();
  73915. };
  73916. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  73917. return this._physicsPlugin.name;
  73918. };
  73919. /**
  73920. * Adding a new impostor for the impostor tracking.
  73921. * This will be done by the impostor itself.
  73922. * @param {PhysicsImpostor} impostor the impostor to add
  73923. */
  73924. PhysicsEngine.prototype.addImpostor = function (impostor) {
  73925. impostor.uniqueId = this._impostors.push(impostor);
  73926. //if no parent, generate the body
  73927. if (!impostor.parent) {
  73928. this._physicsPlugin.generatePhysicsBody(impostor);
  73929. }
  73930. };
  73931. /**
  73932. * Remove an impostor from the engine.
  73933. * This impostor and its mesh will not longer be updated by the physics engine.
  73934. * @param {PhysicsImpostor} impostor the impostor to remove
  73935. */
  73936. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  73937. var index = this._impostors.indexOf(impostor);
  73938. if (index > -1) {
  73939. var removed = this._impostors.splice(index, 1);
  73940. //Is it needed?
  73941. if (removed.length) {
  73942. //this will also remove it from the world.
  73943. removed[0].physicsBody = null;
  73944. }
  73945. }
  73946. };
  73947. /**
  73948. * Add a joint to the physics engine
  73949. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  73950. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  73951. * @param {PhysicsJoint} the joint that will connect both impostors.
  73952. */
  73953. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  73954. var impostorJoint = {
  73955. mainImpostor: mainImpostor,
  73956. connectedImpostor: connectedImpostor,
  73957. joint: joint
  73958. };
  73959. joint.physicsPlugin = this._physicsPlugin;
  73960. this._joints.push(impostorJoint);
  73961. this._physicsPlugin.generateJoint(impostorJoint);
  73962. };
  73963. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  73964. var matchingJoints = this._joints.filter(function (impostorJoint) {
  73965. return (impostorJoint.connectedImpostor === connectedImpostor
  73966. && impostorJoint.joint === joint
  73967. && impostorJoint.mainImpostor === mainImpostor);
  73968. });
  73969. if (matchingJoints.length) {
  73970. this._physicsPlugin.removeJoint(matchingJoints[0]);
  73971. //TODO remove it from the list as well
  73972. }
  73973. };
  73974. /**
  73975. * Called by the scene. no need to call it.
  73976. */
  73977. PhysicsEngine.prototype._step = function (delta) {
  73978. var _this = this;
  73979. //check if any mesh has no body / requires an update
  73980. this._impostors.forEach(function (impostor) {
  73981. if (impostor.isBodyInitRequired()) {
  73982. _this._physicsPlugin.generatePhysicsBody(impostor);
  73983. }
  73984. });
  73985. if (delta > 0.1) {
  73986. delta = 0.1;
  73987. }
  73988. else if (delta <= 0) {
  73989. delta = 1.0 / 60.0;
  73990. }
  73991. this._physicsPlugin.executeStep(delta, this._impostors);
  73992. };
  73993. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  73994. return this._physicsPlugin;
  73995. };
  73996. PhysicsEngine.prototype.getImpostors = function () {
  73997. return this._impostors;
  73998. };
  73999. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  74000. for (var i = 0; i < this._impostors.length; ++i) {
  74001. if (this._impostors[i].object === object) {
  74002. return this._impostors[i];
  74003. }
  74004. }
  74005. return null;
  74006. };
  74007. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  74008. for (var i = 0; i < this._impostors.length; ++i) {
  74009. if (this._impostors[i].physicsBody === body) {
  74010. return this._impostors[i];
  74011. }
  74012. }
  74013. return null;
  74014. };
  74015. // Statics
  74016. PhysicsEngine.Epsilon = 0.001;
  74017. return PhysicsEngine;
  74018. }());
  74019. BABYLON.PhysicsEngine = PhysicsEngine;
  74020. })(BABYLON || (BABYLON = {}));
  74021. //# sourceMappingURL=babylon.physicsEngine.js.map
  74022. var BABYLON;
  74023. (function (BABYLON) {
  74024. var PhysicsHelper = /** @class */ (function () {
  74025. function PhysicsHelper(scene) {
  74026. this._scene = scene;
  74027. this._physicsEngine = this._scene.getPhysicsEngine();
  74028. if (!this._physicsEngine) {
  74029. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  74030. }
  74031. }
  74032. /**
  74033. * @param {Vector3} origin the origin of the explosion
  74034. * @param {number} radius the explosion radius
  74035. * @param {number} strength the explosion strength
  74036. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74037. */
  74038. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  74039. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74040. if (!this._physicsEngine) {
  74041. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  74042. return null;
  74043. }
  74044. var impostors = this._physicsEngine.getImpostors();
  74045. if (impostors.length === 0) {
  74046. return null;
  74047. }
  74048. var event = new PhysicsRadialExplosionEvent(this._scene);
  74049. impostors.forEach(function (impostor) {
  74050. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  74051. if (!impostorForceAndContactPoint) {
  74052. return;
  74053. }
  74054. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74055. });
  74056. event.dispose(false);
  74057. return event;
  74058. };
  74059. /**
  74060. * @param {Vector3} origin the origin of the explosion
  74061. * @param {number} radius the explosion radius
  74062. * @param {number} strength the explosion strength
  74063. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74064. */
  74065. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  74066. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74067. if (!this._physicsEngine) {
  74068. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74069. return null;
  74070. }
  74071. var impostors = this._physicsEngine.getImpostors();
  74072. if (impostors.length === 0) {
  74073. return null;
  74074. }
  74075. var event = new PhysicsRadialExplosionEvent(this._scene);
  74076. impostors.forEach(function (impostor) {
  74077. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  74078. if (!impostorForceAndContactPoint) {
  74079. return;
  74080. }
  74081. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74082. });
  74083. event.dispose(false);
  74084. return event;
  74085. };
  74086. /**
  74087. * @param {Vector3} origin the origin of the explosion
  74088. * @param {number} radius the explosion radius
  74089. * @param {number} strength the explosion strength
  74090. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74091. */
  74092. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  74093. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74094. if (!this._physicsEngine) {
  74095. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74096. return null;
  74097. }
  74098. var impostors = this._physicsEngine.getImpostors();
  74099. if (impostors.length === 0) {
  74100. return null;
  74101. }
  74102. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  74103. event.dispose(false);
  74104. return event;
  74105. };
  74106. /**
  74107. * @param {Vector3} origin the origin of the updraft
  74108. * @param {number} radius the radius of the updraft
  74109. * @param {number} strength the strength of the updraft
  74110. * @param {number} height the height of the updraft
  74111. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  74112. */
  74113. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  74114. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  74115. if (!this._physicsEngine) {
  74116. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74117. return null;
  74118. }
  74119. if (this._physicsEngine.getImpostors().length === 0) {
  74120. return null;
  74121. }
  74122. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  74123. event.dispose(false);
  74124. return event;
  74125. };
  74126. /**
  74127. * @param {Vector3} origin the of the vortex
  74128. * @param {number} radius the radius of the vortex
  74129. * @param {number} strength the strength of the vortex
  74130. * @param {number} height the height of the vortex
  74131. */
  74132. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  74133. if (!this._physicsEngine) {
  74134. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74135. return null;
  74136. }
  74137. if (this._physicsEngine.getImpostors().length === 0) {
  74138. return null;
  74139. }
  74140. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  74141. event.dispose(false);
  74142. return event;
  74143. };
  74144. return PhysicsHelper;
  74145. }());
  74146. BABYLON.PhysicsHelper = PhysicsHelper;
  74147. /***** Radial explosion *****/
  74148. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  74149. function PhysicsRadialExplosionEvent(scene) {
  74150. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  74151. this._rays = [];
  74152. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  74153. this._scene = scene;
  74154. }
  74155. /**
  74156. * Returns the data related to the radial explosion event (sphere & rays).
  74157. * @returns {PhysicsRadialExplosionEventData}
  74158. */
  74159. PhysicsRadialExplosionEvent.prototype.getData = function () {
  74160. this._dataFetched = true;
  74161. return {
  74162. sphere: this._sphere,
  74163. rays: this._rays,
  74164. };
  74165. };
  74166. /**
  74167. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  74168. * @param impostor
  74169. * @param {Vector3} origin the origin of the explosion
  74170. * @param {number} radius the explosion radius
  74171. * @param {number} strength the explosion strength
  74172. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  74173. * @returns {Nullable<PhysicsForceAndContactPoint>}
  74174. */
  74175. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  74176. if (impostor.mass === 0) {
  74177. return null;
  74178. }
  74179. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  74180. return null;
  74181. }
  74182. if (impostor.object.getClassName() !== 'Mesh') {
  74183. return null;
  74184. }
  74185. var impostorObject = impostor.object;
  74186. var impostorObjectCenter = impostor.getObjectCenter();
  74187. var direction = impostorObjectCenter.subtract(origin);
  74188. var ray = new BABYLON.Ray(origin, direction, radius);
  74189. this._rays.push(ray);
  74190. var hit = ray.intersectsMesh(impostorObject);
  74191. var contactPoint = hit.pickedPoint;
  74192. if (!contactPoint) {
  74193. return null;
  74194. }
  74195. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  74196. if (distanceFromOrigin > radius) {
  74197. return null;
  74198. }
  74199. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  74200. ? strength
  74201. : strength * (1 - (distanceFromOrigin / radius));
  74202. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74203. return { force: force, contactPoint: contactPoint };
  74204. };
  74205. /**
  74206. * Disposes the sphere.
  74207. * @param {bolean} force
  74208. */
  74209. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  74210. var _this = this;
  74211. if (force === void 0) { force = true; }
  74212. if (force) {
  74213. this._sphere.dispose();
  74214. }
  74215. else {
  74216. setTimeout(function () {
  74217. if (!_this._dataFetched) {
  74218. _this._sphere.dispose();
  74219. }
  74220. }, 0);
  74221. }
  74222. };
  74223. /*** Helpers ***/
  74224. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  74225. if (!this._sphere) {
  74226. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  74227. this._sphere.isVisible = false;
  74228. }
  74229. };
  74230. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  74231. var impostorObject = impostor.object;
  74232. this._prepareSphere();
  74233. this._sphere.position = origin;
  74234. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  74235. this._sphere._updateBoundingInfo();
  74236. this._sphere.computeWorldMatrix(true);
  74237. return this._sphere.intersectsMesh(impostorObject, true);
  74238. };
  74239. return PhysicsRadialExplosionEvent;
  74240. }());
  74241. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  74242. /***** Gravitational Field *****/
  74243. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  74244. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  74245. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74246. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74247. this._physicsHelper = physicsHelper;
  74248. this._scene = scene;
  74249. this._origin = origin;
  74250. this._radius = radius;
  74251. this._strength = strength;
  74252. this._falloff = falloff;
  74253. this._tickCallback = this._tick.bind(this);
  74254. }
  74255. /**
  74256. * Returns the data related to the gravitational field event (sphere).
  74257. * @returns {PhysicsGravitationalFieldEventData}
  74258. */
  74259. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  74260. this._dataFetched = true;
  74261. return {
  74262. sphere: this._sphere,
  74263. };
  74264. };
  74265. /**
  74266. * Enables the gravitational field.
  74267. */
  74268. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  74269. this._tickCallback.call(this);
  74270. this._scene.registerBeforeRender(this._tickCallback);
  74271. };
  74272. /**
  74273. * Disables the gravitational field.
  74274. */
  74275. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  74276. this._scene.unregisterBeforeRender(this._tickCallback);
  74277. };
  74278. /**
  74279. * Disposes the sphere.
  74280. * @param {bolean} force
  74281. */
  74282. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  74283. var _this = this;
  74284. if (force === void 0) { force = true; }
  74285. if (force) {
  74286. this._sphere.dispose();
  74287. }
  74288. else {
  74289. setTimeout(function () {
  74290. if (!_this._dataFetched) {
  74291. _this._sphere.dispose();
  74292. }
  74293. }, 0);
  74294. }
  74295. };
  74296. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  74297. // Since the params won't change, we fetch the event only once
  74298. if (this._sphere) {
  74299. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74300. }
  74301. else {
  74302. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74303. if (radialExplosionEvent) {
  74304. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  74305. }
  74306. }
  74307. };
  74308. return PhysicsGravitationalFieldEvent;
  74309. }());
  74310. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  74311. /***** Updraft *****/
  74312. var PhysicsUpdraftEvent = /** @class */ (function () {
  74313. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  74314. this._scene = _scene;
  74315. this._origin = _origin;
  74316. this._radius = _radius;
  74317. this._strength = _strength;
  74318. this._height = _height;
  74319. this._updraftMode = _updraftMode;
  74320. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74321. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  74322. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74323. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74324. this._physicsEngine = this._scene.getPhysicsEngine();
  74325. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74326. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74327. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74328. this._originDirection = this._origin.subtract(this._originTop).normalize();
  74329. }
  74330. this._tickCallback = this._tick.bind(this);
  74331. }
  74332. /**
  74333. * Returns the data related to the updraft event (cylinder).
  74334. * @returns {PhysicsUpdraftEventData}
  74335. */
  74336. PhysicsUpdraftEvent.prototype.getData = function () {
  74337. this._dataFetched = true;
  74338. return {
  74339. cylinder: this._cylinder,
  74340. };
  74341. };
  74342. /**
  74343. * Enables the updraft.
  74344. */
  74345. PhysicsUpdraftEvent.prototype.enable = function () {
  74346. this._tickCallback.call(this);
  74347. this._scene.registerBeforeRender(this._tickCallback);
  74348. };
  74349. /**
  74350. * Disables the cortex.
  74351. */
  74352. PhysicsUpdraftEvent.prototype.disable = function () {
  74353. this._scene.unregisterBeforeRender(this._tickCallback);
  74354. };
  74355. /**
  74356. * Disposes the sphere.
  74357. * @param {bolean} force
  74358. */
  74359. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  74360. var _this = this;
  74361. if (force === void 0) { force = true; }
  74362. if (force) {
  74363. this._cylinder.dispose();
  74364. }
  74365. else {
  74366. setTimeout(function () {
  74367. if (!_this._dataFetched) {
  74368. _this._cylinder.dispose();
  74369. }
  74370. }, 0);
  74371. }
  74372. };
  74373. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74374. if (impostor.mass === 0) {
  74375. return null;
  74376. }
  74377. if (!this._intersectsWithCylinder(impostor)) {
  74378. return null;
  74379. }
  74380. var impostorObjectCenter = impostor.getObjectCenter();
  74381. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74382. var direction = this._originDirection;
  74383. }
  74384. else {
  74385. var direction = impostorObjectCenter.subtract(this._originTop);
  74386. }
  74387. var multiplier = this._strength * -1;
  74388. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74389. return { force: force, contactPoint: impostorObjectCenter };
  74390. };
  74391. PhysicsUpdraftEvent.prototype._tick = function () {
  74392. var _this = this;
  74393. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74394. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74395. if (!impostorForceAndContactPoint) {
  74396. return;
  74397. }
  74398. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74399. });
  74400. };
  74401. /*** Helpers ***/
  74402. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  74403. if (!this._cylinder) {
  74404. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  74405. height: this._height,
  74406. diameter: this._radius * 2,
  74407. }, this._scene);
  74408. this._cylinder.isVisible = false;
  74409. }
  74410. };
  74411. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  74412. var impostorObject = impostor.object;
  74413. this._prepareCylinder();
  74414. this._cylinder.position = this._cylinderPosition;
  74415. return this._cylinder.intersectsMesh(impostorObject, true);
  74416. };
  74417. return PhysicsUpdraftEvent;
  74418. }());
  74419. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  74420. /***** Vortex *****/
  74421. var PhysicsVortexEvent = /** @class */ (function () {
  74422. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  74423. this._scene = _scene;
  74424. this._origin = _origin;
  74425. this._radius = _radius;
  74426. this._strength = _strength;
  74427. this._height = _height;
  74428. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74429. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  74430. this._updraftMultiplier = 0.02;
  74431. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74432. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74433. this._physicsEngine = this._scene.getPhysicsEngine();
  74434. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74435. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74436. this._tickCallback = this._tick.bind(this);
  74437. }
  74438. /**
  74439. * Returns the data related to the vortex event (cylinder).
  74440. * @returns {PhysicsVortexEventData}
  74441. */
  74442. PhysicsVortexEvent.prototype.getData = function () {
  74443. this._dataFetched = true;
  74444. return {
  74445. cylinder: this._cylinder,
  74446. };
  74447. };
  74448. /**
  74449. * Enables the vortex.
  74450. */
  74451. PhysicsVortexEvent.prototype.enable = function () {
  74452. this._tickCallback.call(this);
  74453. this._scene.registerBeforeRender(this._tickCallback);
  74454. };
  74455. /**
  74456. * Disables the cortex.
  74457. */
  74458. PhysicsVortexEvent.prototype.disable = function () {
  74459. this._scene.unregisterBeforeRender(this._tickCallback);
  74460. };
  74461. /**
  74462. * Disposes the sphere.
  74463. * @param {bolean} force
  74464. */
  74465. PhysicsVortexEvent.prototype.dispose = function (force) {
  74466. var _this = this;
  74467. if (force === void 0) { force = true; }
  74468. if (force) {
  74469. this._cylinder.dispose();
  74470. }
  74471. else {
  74472. setTimeout(function () {
  74473. if (!_this._dataFetched) {
  74474. _this._cylinder.dispose();
  74475. }
  74476. }, 0);
  74477. }
  74478. };
  74479. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74480. if (impostor.mass === 0) {
  74481. return null;
  74482. }
  74483. if (!this._intersectsWithCylinder(impostor)) {
  74484. return null;
  74485. }
  74486. if (impostor.object.getClassName() !== 'Mesh') {
  74487. return null;
  74488. }
  74489. var impostorObject = impostor.object;
  74490. var impostorObjectCenter = impostor.getObjectCenter();
  74491. 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)
  74492. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  74493. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  74494. var hit = ray.intersectsMesh(impostorObject);
  74495. var contactPoint = hit.pickedPoint;
  74496. if (!contactPoint) {
  74497. return null;
  74498. }
  74499. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  74500. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  74501. var directionToOrigin = contactPoint.normalize();
  74502. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74503. directionToOrigin = directionToOrigin.negate();
  74504. }
  74505. // TODO: find a more physically based solution
  74506. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74507. var forceX = directionToOrigin.x * this._strength / 8;
  74508. var forceY = directionToOrigin.y * this._updraftMultiplier;
  74509. var forceZ = directionToOrigin.z * this._strength / 8;
  74510. }
  74511. else {
  74512. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  74513. var forceY = this._originTop.y * this._updraftMultiplier;
  74514. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  74515. }
  74516. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  74517. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  74518. return { force: force, contactPoint: impostorObjectCenter };
  74519. };
  74520. PhysicsVortexEvent.prototype._tick = function () {
  74521. var _this = this;
  74522. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74523. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74524. if (!impostorForceAndContactPoint) {
  74525. return;
  74526. }
  74527. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74528. });
  74529. };
  74530. /*** Helpers ***/
  74531. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  74532. if (!this._cylinder) {
  74533. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  74534. height: this._height,
  74535. diameter: this._radius * 2,
  74536. }, this._scene);
  74537. this._cylinder.isVisible = false;
  74538. }
  74539. };
  74540. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  74541. var impostorObject = impostor.object;
  74542. this._prepareCylinder();
  74543. this._cylinder.position = this._cylinderPosition;
  74544. return this._cylinder.intersectsMesh(impostorObject, true);
  74545. };
  74546. return PhysicsVortexEvent;
  74547. }());
  74548. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  74549. /***** Enums *****/
  74550. /**
  74551. * The strenght of the force in correspondence to the distance of the affected object
  74552. */
  74553. var PhysicsRadialImpulseFalloff;
  74554. (function (PhysicsRadialImpulseFalloff) {
  74555. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  74556. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  74557. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  74558. /**
  74559. * The strenght of the force in correspondence to the distance of the affected object
  74560. */
  74561. var PhysicsUpdraftMode;
  74562. (function (PhysicsUpdraftMode) {
  74563. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  74564. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  74565. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  74566. })(BABYLON || (BABYLON = {}));
  74567. //# sourceMappingURL=babylon.physicsHelper.js.map
  74568. var BABYLON;
  74569. (function (BABYLON) {
  74570. var CannonJSPlugin = /** @class */ (function () {
  74571. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  74572. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  74573. if (iterations === void 0) { iterations = 10; }
  74574. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  74575. this.name = "CannonJSPlugin";
  74576. this._physicsMaterials = new Array();
  74577. this._fixedTimeStep = 1 / 60;
  74578. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  74579. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  74580. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  74581. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  74582. this._tmpPosition = BABYLON.Vector3.Zero();
  74583. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  74584. this._tmpUnityRotation = new BABYLON.Quaternion();
  74585. if (!this.isSupported()) {
  74586. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  74587. return;
  74588. }
  74589. this._extendNamespace();
  74590. this.world = new this.BJSCANNON.World();
  74591. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  74592. this.world.solver.iterations = iterations;
  74593. }
  74594. CannonJSPlugin.prototype.setGravity = function (gravity) {
  74595. this.world.gravity.copy(gravity);
  74596. };
  74597. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  74598. this._fixedTimeStep = timeStep;
  74599. };
  74600. CannonJSPlugin.prototype.getTimeStep = function () {
  74601. return this._fixedTimeStep;
  74602. };
  74603. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  74604. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  74605. };
  74606. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  74607. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74608. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74609. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  74610. };
  74611. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  74612. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74613. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74614. impostor.physicsBody.applyForce(impulse, worldPoint);
  74615. };
  74616. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  74617. //parent-child relationship. Does this impostor has a parent impostor?
  74618. if (impostor.parent) {
  74619. if (impostor.physicsBody) {
  74620. this.removePhysicsBody(impostor);
  74621. //TODO is that needed?
  74622. impostor.forceUpdate();
  74623. }
  74624. return;
  74625. }
  74626. //should a new body be created for this impostor?
  74627. if (impostor.isBodyInitRequired()) {
  74628. var shape = this._createShape(impostor);
  74629. //unregister events, if body is being changed
  74630. var oldBody = impostor.physicsBody;
  74631. if (oldBody) {
  74632. this.removePhysicsBody(impostor);
  74633. }
  74634. //create the body and material
  74635. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  74636. var bodyCreationObject = {
  74637. mass: impostor.getParam("mass"),
  74638. material: material
  74639. };
  74640. // A simple extend, in case native options were used.
  74641. var nativeOptions = impostor.getParam("nativeOptions");
  74642. for (var key in nativeOptions) {
  74643. if (nativeOptions.hasOwnProperty(key)) {
  74644. bodyCreationObject[key] = nativeOptions[key];
  74645. }
  74646. }
  74647. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  74648. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  74649. this.world.addEventListener("preStep", impostor.beforeStep);
  74650. this.world.addEventListener("postStep", impostor.afterStep);
  74651. impostor.physicsBody.addShape(shape);
  74652. this.world.add(impostor.physicsBody);
  74653. //try to keep the body moving in the right direction by taking old properties.
  74654. //Should be tested!
  74655. if (oldBody) {
  74656. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  74657. impostor.physicsBody[param].copy(oldBody[param]);
  74658. });
  74659. }
  74660. this._processChildMeshes(impostor);
  74661. }
  74662. //now update the body's transformation
  74663. this._updatePhysicsBodyTransformation(impostor);
  74664. };
  74665. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  74666. var _this = this;
  74667. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  74668. var currentRotation = mainImpostor.object.rotationQuaternion;
  74669. if (meshChildren.length) {
  74670. var processMesh = function (localPosition, mesh) {
  74671. if (!currentRotation || !mesh.rotationQuaternion) {
  74672. return;
  74673. }
  74674. var childImpostor = mesh.getPhysicsImpostor();
  74675. if (childImpostor) {
  74676. var parent = childImpostor.parent;
  74677. if (parent !== mainImpostor) {
  74678. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  74679. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  74680. if (childImpostor.physicsBody) {
  74681. _this.removePhysicsBody(childImpostor);
  74682. childImpostor.physicsBody = null;
  74683. }
  74684. childImpostor.parent = mainImpostor;
  74685. childImpostor.resetUpdateFlags();
  74686. 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));
  74687. //Add the mass of the children.
  74688. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  74689. }
  74690. }
  74691. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  74692. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  74693. };
  74694. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  74695. }
  74696. };
  74697. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  74698. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  74699. this.world.removeEventListener("preStep", impostor.beforeStep);
  74700. this.world.removeEventListener("postStep", impostor.afterStep);
  74701. this.world.remove(impostor.physicsBody);
  74702. };
  74703. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  74704. var mainBody = impostorJoint.mainImpostor.physicsBody;
  74705. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  74706. if (!mainBody || !connectedBody) {
  74707. return;
  74708. }
  74709. var constraint;
  74710. var jointData = impostorJoint.joint.jointData;
  74711. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  74712. var constraintData = {
  74713. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  74714. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  74715. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  74716. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  74717. maxForce: jointData.nativeParams.maxForce,
  74718. collideConnected: !!jointData.collision
  74719. };
  74720. switch (impostorJoint.joint.type) {
  74721. case BABYLON.PhysicsJoint.HingeJoint:
  74722. case BABYLON.PhysicsJoint.Hinge2Joint:
  74723. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  74724. break;
  74725. case BABYLON.PhysicsJoint.DistanceJoint:
  74726. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  74727. break;
  74728. case BABYLON.PhysicsJoint.SpringJoint:
  74729. var springData = jointData;
  74730. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  74731. restLength: springData.length,
  74732. stiffness: springData.stiffness,
  74733. damping: springData.damping,
  74734. localAnchorA: constraintData.pivotA,
  74735. localAnchorB: constraintData.pivotB
  74736. });
  74737. break;
  74738. case BABYLON.PhysicsJoint.LockJoint:
  74739. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  74740. break;
  74741. case BABYLON.PhysicsJoint.PointToPointJoint:
  74742. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  74743. default:
  74744. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  74745. break;
  74746. }
  74747. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  74748. constraint.collideConnected = !!jointData.collision;
  74749. impostorJoint.joint.physicsJoint = constraint;
  74750. //don't add spring as constraint, as it is not one.
  74751. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  74752. this.world.addConstraint(constraint);
  74753. }
  74754. else {
  74755. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  74756. constraint.applyForce();
  74757. });
  74758. }
  74759. };
  74760. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  74761. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  74762. };
  74763. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  74764. var index;
  74765. var mat;
  74766. for (index = 0; index < this._physicsMaterials.length; index++) {
  74767. mat = this._physicsMaterials[index];
  74768. if (mat.friction === friction && mat.restitution === restitution) {
  74769. return mat;
  74770. }
  74771. }
  74772. var currentMat = new this.BJSCANNON.Material(name);
  74773. currentMat.friction = friction;
  74774. currentMat.restitution = restitution;
  74775. this._physicsMaterials.push(currentMat);
  74776. return currentMat;
  74777. };
  74778. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  74779. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  74780. };
  74781. CannonJSPlugin.prototype._createShape = function (impostor) {
  74782. var object = impostor.object;
  74783. var returnValue;
  74784. var extendSize = impostor.getObjectExtendSize();
  74785. switch (impostor.type) {
  74786. case BABYLON.PhysicsImpostor.SphereImpostor:
  74787. var radiusX = extendSize.x;
  74788. var radiusY = extendSize.y;
  74789. var radiusZ = extendSize.z;
  74790. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  74791. break;
  74792. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  74793. case BABYLON.PhysicsImpostor.CylinderImpostor:
  74794. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  74795. break;
  74796. case BABYLON.PhysicsImpostor.BoxImpostor:
  74797. var box = extendSize.scale(0.5);
  74798. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  74799. break;
  74800. case BABYLON.PhysicsImpostor.PlaneImpostor:
  74801. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  74802. returnValue = new this.BJSCANNON.Plane();
  74803. break;
  74804. case BABYLON.PhysicsImpostor.MeshImpostor:
  74805. // should transform the vertex data to world coordinates!!
  74806. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  74807. var rawFaces = object.getIndices ? object.getIndices() : [];
  74808. if (!rawVerts)
  74809. return;
  74810. // get only scale! so the object could transform correctly.
  74811. var oldPosition = object.position.clone();
  74812. var oldRotation = object.rotation && object.rotation.clone();
  74813. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  74814. object.position.copyFromFloats(0, 0, 0);
  74815. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74816. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74817. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74818. var transform = object.computeWorldMatrix(true);
  74819. // convert rawVerts to object space
  74820. var temp = new Array();
  74821. var index;
  74822. for (index = 0; index < rawVerts.length; index += 3) {
  74823. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  74824. }
  74825. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  74826. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  74827. //now set back the transformation!
  74828. object.position.copyFrom(oldPosition);
  74829. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  74830. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  74831. break;
  74832. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  74833. var oldPosition2 = object.position.clone();
  74834. var oldRotation2 = object.rotation && object.rotation.clone();
  74835. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  74836. object.position.copyFromFloats(0, 0, 0);
  74837. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74838. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74839. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74840. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  74841. returnValue = this._createHeightmap(object);
  74842. object.position.copyFrom(oldPosition2);
  74843. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  74844. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  74845. object.computeWorldMatrix(true);
  74846. break;
  74847. case BABYLON.PhysicsImpostor.ParticleImpostor:
  74848. returnValue = new this.BJSCANNON.Particle();
  74849. break;
  74850. }
  74851. return returnValue;
  74852. };
  74853. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  74854. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  74855. var transform = object.computeWorldMatrix(true);
  74856. // convert rawVerts to object space
  74857. var temp = new Array();
  74858. var index;
  74859. for (index = 0; index < pos.length; index += 3) {
  74860. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  74861. }
  74862. pos = temp;
  74863. var matrix = new Array();
  74864. //For now pointDepth will not be used and will be automatically calculated.
  74865. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  74866. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  74867. var boundingInfo = object.getBoundingInfo();
  74868. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  74869. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  74870. var elementSize = dim * 2 / arraySize;
  74871. for (var i = 0; i < pos.length; i = i + 3) {
  74872. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  74873. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  74874. var y = -pos[i + 2] + minY;
  74875. if (!matrix[x]) {
  74876. matrix[x] = [];
  74877. }
  74878. if (!matrix[x][z]) {
  74879. matrix[x][z] = y;
  74880. }
  74881. matrix[x][z] = Math.max(y, matrix[x][z]);
  74882. }
  74883. for (var x = 0; x <= arraySize; ++x) {
  74884. if (!matrix[x]) {
  74885. var loc = 1;
  74886. while (!matrix[(x + loc) % arraySize]) {
  74887. loc++;
  74888. }
  74889. matrix[x] = matrix[(x + loc) % arraySize].slice();
  74890. //console.log("missing x", x);
  74891. }
  74892. for (var z = 0; z <= arraySize; ++z) {
  74893. if (!matrix[x][z]) {
  74894. var loc = 1;
  74895. var newValue;
  74896. while (newValue === undefined) {
  74897. newValue = matrix[x][(z + loc++) % arraySize];
  74898. }
  74899. matrix[x][z] = newValue;
  74900. }
  74901. }
  74902. }
  74903. var shape = new this.BJSCANNON.Heightfield(matrix, {
  74904. elementSize: elementSize
  74905. });
  74906. //For future reference, needed for body transformation
  74907. shape.minY = minY;
  74908. return shape;
  74909. };
  74910. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  74911. var object = impostor.object;
  74912. //make sure it is updated...
  74913. object.computeWorldMatrix && object.computeWorldMatrix(true);
  74914. // The delta between the mesh position and the mesh bounding box center
  74915. var bInfo = object.getBoundingInfo();
  74916. if (!bInfo)
  74917. return;
  74918. var center = impostor.getObjectCenter();
  74919. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  74920. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  74921. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  74922. this._tmpPosition.copyFrom(center);
  74923. var quaternion = object.rotationQuaternion;
  74924. if (!quaternion) {
  74925. return;
  74926. }
  74927. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  74928. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  74929. //-90 DEG in X, precalculated
  74930. quaternion = quaternion.multiply(this._minus90X);
  74931. //Invert! (Precalculated, 90 deg in X)
  74932. //No need to clone. this will never change.
  74933. impostor.setDeltaRotation(this._plus90X);
  74934. }
  74935. //If it is a heightfield, if should be centered.
  74936. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  74937. var mesh = object;
  74938. var boundingInfo = mesh.getBoundingInfo();
  74939. //calculate the correct body position:
  74940. var rotationQuaternion = mesh.rotationQuaternion;
  74941. mesh.rotationQuaternion = this._tmpUnityRotation;
  74942. mesh.computeWorldMatrix(true);
  74943. //get original center with no rotation
  74944. var c = center.clone();
  74945. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  74946. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  74947. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  74948. mesh.setPreTransformMatrix(p);
  74949. mesh.computeWorldMatrix(true);
  74950. //calculate the translation
  74951. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  74952. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  74953. //add it inverted to the delta
  74954. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  74955. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  74956. //rotation is back
  74957. mesh.rotationQuaternion = rotationQuaternion;
  74958. mesh.setPreTransformMatrix(oldPivot);
  74959. mesh.computeWorldMatrix(true);
  74960. }
  74961. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  74962. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  74963. //this._tmpPosition.copyFrom(object.position);
  74964. }
  74965. impostor.setDeltaPosition(this._tmpDeltaPosition);
  74966. //Now update the impostor object
  74967. impostor.physicsBody.position.copy(this._tmpPosition);
  74968. impostor.physicsBody.quaternion.copy(quaternion);
  74969. };
  74970. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  74971. impostor.object.position.copyFrom(impostor.physicsBody.position);
  74972. if (impostor.object.rotationQuaternion) {
  74973. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  74974. }
  74975. };
  74976. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  74977. impostor.physicsBody.position.copy(newPosition);
  74978. impostor.physicsBody.quaternion.copy(newRotation);
  74979. };
  74980. CannonJSPlugin.prototype.isSupported = function () {
  74981. return this.BJSCANNON !== undefined;
  74982. };
  74983. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  74984. impostor.physicsBody.velocity.copy(velocity);
  74985. };
  74986. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  74987. impostor.physicsBody.angularVelocity.copy(velocity);
  74988. };
  74989. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  74990. var v = impostor.physicsBody.velocity;
  74991. if (!v) {
  74992. return null;
  74993. }
  74994. return new BABYLON.Vector3(v.x, v.y, v.z);
  74995. };
  74996. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  74997. var v = impostor.physicsBody.angularVelocity;
  74998. if (!v) {
  74999. return null;
  75000. }
  75001. return new BABYLON.Vector3(v.x, v.y, v.z);
  75002. };
  75003. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75004. impostor.physicsBody.mass = mass;
  75005. impostor.physicsBody.updateMassProperties();
  75006. };
  75007. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  75008. return impostor.physicsBody.mass;
  75009. };
  75010. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  75011. return impostor.physicsBody.material.friction;
  75012. };
  75013. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75014. impostor.physicsBody.material.friction = friction;
  75015. };
  75016. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75017. return impostor.physicsBody.material.restitution;
  75018. };
  75019. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75020. impostor.physicsBody.material.restitution = restitution;
  75021. };
  75022. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  75023. impostor.physicsBody.sleep();
  75024. };
  75025. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  75026. impostor.physicsBody.wakeUp();
  75027. };
  75028. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75029. joint.physicsJoint.distance = maxDistance;
  75030. };
  75031. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  75032. // if (!motorIndex) {
  75033. // joint.physicsJoint.enableMotor();
  75034. // }
  75035. // }
  75036. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  75037. // if (!motorIndex) {
  75038. // joint.physicsJoint.disableMotor();
  75039. // }
  75040. // }
  75041. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75042. if (!motorIndex) {
  75043. joint.physicsJoint.enableMotor();
  75044. joint.physicsJoint.setMotorSpeed(speed);
  75045. if (maxForce) {
  75046. this.setLimit(joint, maxForce);
  75047. }
  75048. }
  75049. };
  75050. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  75051. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  75052. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  75053. };
  75054. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75055. var body = impostor.physicsBody;
  75056. mesh.position.x = body.position.x;
  75057. mesh.position.y = body.position.y;
  75058. mesh.position.z = body.position.z;
  75059. if (mesh.rotationQuaternion) {
  75060. mesh.rotationQuaternion.x = body.quaternion.x;
  75061. mesh.rotationQuaternion.y = body.quaternion.y;
  75062. mesh.rotationQuaternion.z = body.quaternion.z;
  75063. mesh.rotationQuaternion.w = body.quaternion.w;
  75064. }
  75065. };
  75066. CannonJSPlugin.prototype.getRadius = function (impostor) {
  75067. var shape = impostor.physicsBody.shapes[0];
  75068. return shape.boundingSphereRadius;
  75069. };
  75070. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75071. var shape = impostor.physicsBody.shapes[0];
  75072. result.x = shape.halfExtents.x * 2;
  75073. result.y = shape.halfExtents.y * 2;
  75074. result.z = shape.halfExtents.z * 2;
  75075. };
  75076. CannonJSPlugin.prototype.dispose = function () {
  75077. };
  75078. CannonJSPlugin.prototype._extendNamespace = function () {
  75079. //this will force cannon to execute at least one step when using interpolation
  75080. var step_tmp1 = new this.BJSCANNON.Vec3();
  75081. var Engine = this.BJSCANNON;
  75082. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  75083. maxSubSteps = maxSubSteps || 10;
  75084. timeSinceLastCalled = timeSinceLastCalled || 0;
  75085. if (timeSinceLastCalled === 0) {
  75086. this.internalStep(dt);
  75087. this.time += dt;
  75088. }
  75089. else {
  75090. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  75091. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  75092. var t0 = performance.now();
  75093. for (var i = 0; i !== internalSteps; i++) {
  75094. this.internalStep(dt);
  75095. if (performance.now() - t0 > dt * 1000) {
  75096. break;
  75097. }
  75098. }
  75099. this.time += timeSinceLastCalled;
  75100. var h = this.time % dt;
  75101. var h_div_dt = h / dt;
  75102. var interpvelo = step_tmp1;
  75103. var bodies = this.bodies;
  75104. for (var j = 0; j !== bodies.length; j++) {
  75105. var b = bodies[j];
  75106. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  75107. b.position.vsub(b.previousPosition, interpvelo);
  75108. interpvelo.scale(h_div_dt, interpvelo);
  75109. b.position.vadd(interpvelo, b.interpolatedPosition);
  75110. }
  75111. else {
  75112. b.interpolatedPosition.copy(b.position);
  75113. b.interpolatedQuaternion.copy(b.quaternion);
  75114. }
  75115. }
  75116. }
  75117. };
  75118. };
  75119. return CannonJSPlugin;
  75120. }());
  75121. BABYLON.CannonJSPlugin = CannonJSPlugin;
  75122. })(BABYLON || (BABYLON = {}));
  75123. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  75124. var BABYLON;
  75125. (function (BABYLON) {
  75126. var OimoJSPlugin = /** @class */ (function () {
  75127. function OimoJSPlugin(iterations) {
  75128. this.name = "OimoJSPlugin";
  75129. this._tmpImpostorsArray = [];
  75130. this._tmpPositionVector = BABYLON.Vector3.Zero();
  75131. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  75132. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  75133. this.world.worldscale(1);
  75134. this.world.clear();
  75135. //making sure no stats are calculated
  75136. this.world.isNoStat = true;
  75137. }
  75138. OimoJSPlugin.prototype.setGravity = function (gravity) {
  75139. this.world.gravity.copy(gravity);
  75140. };
  75141. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  75142. this.world.timeStep = timeStep;
  75143. };
  75144. OimoJSPlugin.prototype.getTimeStep = function () {
  75145. return this.world.timeStep;
  75146. };
  75147. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  75148. var _this = this;
  75149. impostors.forEach(function (impostor) {
  75150. impostor.beforeStep();
  75151. });
  75152. this.world.step();
  75153. impostors.forEach(function (impostor) {
  75154. impostor.afterStep();
  75155. //update the ordered impostors array
  75156. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  75157. });
  75158. //check for collisions
  75159. var contact = this.world.contacts;
  75160. while (contact !== null) {
  75161. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  75162. contact = contact.next;
  75163. continue;
  75164. }
  75165. //is this body colliding with any other? get the impostor
  75166. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  75167. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  75168. if (!mainImpostor || !collidingImpostor) {
  75169. contact = contact.next;
  75170. continue;
  75171. }
  75172. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  75173. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  75174. contact = contact.next;
  75175. }
  75176. };
  75177. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  75178. var mass = impostor.physicsBody.massInfo.mass;
  75179. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  75180. };
  75181. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  75182. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  75183. this.applyImpulse(impostor, force, contactPoint);
  75184. };
  75185. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  75186. var _this = this;
  75187. //parent-child relationship. Does this impostor has a parent impostor?
  75188. if (impostor.parent) {
  75189. if (impostor.physicsBody) {
  75190. this.removePhysicsBody(impostor);
  75191. //TODO is that needed?
  75192. impostor.forceUpdate();
  75193. }
  75194. return;
  75195. }
  75196. if (impostor.isBodyInitRequired()) {
  75197. var bodyConfig = {
  75198. name: impostor.uniqueId,
  75199. //Oimo must have mass, also for static objects.
  75200. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  75201. size: [],
  75202. type: [],
  75203. pos: [],
  75204. rot: [],
  75205. move: impostor.getParam("mass") !== 0,
  75206. //Supporting older versions of Oimo
  75207. world: this.world
  75208. };
  75209. var impostors = [impostor];
  75210. var addToArray = function (parent) {
  75211. if (!parent.getChildMeshes)
  75212. return;
  75213. parent.getChildMeshes().forEach(function (m) {
  75214. if (m.physicsImpostor) {
  75215. impostors.push(m.physicsImpostor);
  75216. //m.physicsImpostor._init();
  75217. }
  75218. });
  75219. };
  75220. addToArray(impostor.object);
  75221. var checkWithEpsilon_1 = function (value) {
  75222. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  75223. };
  75224. impostors.forEach(function (i) {
  75225. if (!impostor.object.rotationQuaternion) {
  75226. return;
  75227. }
  75228. //get the correct bounding box
  75229. var oldQuaternion = i.object.rotationQuaternion;
  75230. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  75231. x: impostor.object.rotationQuaternion.x,
  75232. y: impostor.object.rotationQuaternion.y,
  75233. z: impostor.object.rotationQuaternion.z,
  75234. s: impostor.object.rotationQuaternion.w
  75235. });
  75236. var extendSize = i.getObjectExtendSize();
  75237. if (i === impostor) {
  75238. var center = impostor.getObjectCenter();
  75239. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  75240. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  75241. //Can also use Array.prototype.push.apply
  75242. bodyConfig.pos.push(center.x);
  75243. bodyConfig.pos.push(center.y);
  75244. bodyConfig.pos.push(center.z);
  75245. //tmp solution
  75246. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75247. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75248. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75249. }
  75250. else {
  75251. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  75252. bodyConfig.pos.push(localPosition.x);
  75253. bodyConfig.pos.push(localPosition.y);
  75254. bodyConfig.pos.push(localPosition.z);
  75255. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  75256. bodyConfig.rot.push(0);
  75257. bodyConfig.rot.push(0);
  75258. bodyConfig.rot.push(0);
  75259. }
  75260. // register mesh
  75261. switch (i.type) {
  75262. case BABYLON.PhysicsImpostor.ParticleImpostor:
  75263. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  75264. case BABYLON.PhysicsImpostor.SphereImpostor:
  75265. var radiusX = extendSize.x;
  75266. var radiusY = extendSize.y;
  75267. var radiusZ = extendSize.z;
  75268. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  75269. bodyConfig.type.push('sphere');
  75270. //due to the way oimo works with compounds, add 3 times
  75271. bodyConfig.size.push(size);
  75272. bodyConfig.size.push(size);
  75273. bodyConfig.size.push(size);
  75274. break;
  75275. case BABYLON.PhysicsImpostor.CylinderImpostor:
  75276. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  75277. var sizeY = checkWithEpsilon_1(extendSize.y);
  75278. bodyConfig.type.push('cylinder');
  75279. bodyConfig.size.push(sizeX);
  75280. bodyConfig.size.push(sizeY);
  75281. //due to the way oimo works with compounds, add one more value.
  75282. bodyConfig.size.push(sizeY);
  75283. break;
  75284. case BABYLON.PhysicsImpostor.PlaneImpostor:
  75285. case BABYLON.PhysicsImpostor.BoxImpostor:
  75286. default:
  75287. var sizeX = checkWithEpsilon_1(extendSize.x);
  75288. var sizeY = checkWithEpsilon_1(extendSize.y);
  75289. var sizeZ = checkWithEpsilon_1(extendSize.z);
  75290. bodyConfig.type.push('box');
  75291. bodyConfig.size.push(sizeX);
  75292. bodyConfig.size.push(sizeY);
  75293. bodyConfig.size.push(sizeZ);
  75294. break;
  75295. }
  75296. //actually not needed, but hey...
  75297. i.object.rotationQuaternion = oldQuaternion;
  75298. });
  75299. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  75300. }
  75301. else {
  75302. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  75303. }
  75304. impostor.setDeltaPosition(this._tmpPositionVector);
  75305. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  75306. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  75307. };
  75308. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75309. //impostor.physicsBody.dispose();
  75310. //Same as : (older oimo versions)
  75311. this.world.removeRigidBody(impostor.physicsBody);
  75312. };
  75313. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75314. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75315. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75316. if (!mainBody || !connectedBody) {
  75317. return;
  75318. }
  75319. var jointData = impostorJoint.joint.jointData;
  75320. var options = jointData.nativeParams || {};
  75321. var type;
  75322. var nativeJointData = {
  75323. body1: mainBody,
  75324. body2: connectedBody,
  75325. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  75326. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  75327. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  75328. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  75329. min: options.min,
  75330. max: options.max,
  75331. collision: options.collision || jointData.collision,
  75332. spring: options.spring,
  75333. //supporting older version of Oimo
  75334. world: this.world
  75335. };
  75336. switch (impostorJoint.joint.type) {
  75337. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  75338. type = "jointBall";
  75339. break;
  75340. case BABYLON.PhysicsJoint.SpringJoint:
  75341. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  75342. var springData = jointData;
  75343. nativeJointData.min = springData.length || nativeJointData.min;
  75344. //Max should also be set, just make sure it is at least min
  75345. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  75346. case BABYLON.PhysicsJoint.DistanceJoint:
  75347. type = "jointDistance";
  75348. nativeJointData.max = jointData.maxDistance;
  75349. break;
  75350. case BABYLON.PhysicsJoint.PrismaticJoint:
  75351. type = "jointPrisme";
  75352. break;
  75353. case BABYLON.PhysicsJoint.SliderJoint:
  75354. type = "jointSlide";
  75355. break;
  75356. case BABYLON.PhysicsJoint.WheelJoint:
  75357. type = "jointWheel";
  75358. break;
  75359. case BABYLON.PhysicsJoint.HingeJoint:
  75360. default:
  75361. type = "jointHinge";
  75362. break;
  75363. }
  75364. nativeJointData.type = type;
  75365. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  75366. };
  75367. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  75368. //Bug in Oimo prevents us from disposing a joint in the playground
  75369. //joint.joint.physicsJoint.dispose();
  75370. //So we will bruteforce it!
  75371. try {
  75372. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  75373. }
  75374. catch (e) {
  75375. BABYLON.Tools.Warn(e);
  75376. }
  75377. };
  75378. OimoJSPlugin.prototype.isSupported = function () {
  75379. return this.BJSOIMO !== undefined;
  75380. };
  75381. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  75382. if (!impostor.physicsBody.sleeping) {
  75383. //TODO check that
  75384. if (impostor.physicsBody.shapes.next) {
  75385. var parentShape = this._getLastShape(impostor.physicsBody);
  75386. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  75387. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  75388. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  75389. }
  75390. else {
  75391. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  75392. }
  75393. if (impostor.object.rotationQuaternion) {
  75394. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  75395. impostor.object.rotationQuaternion.normalize();
  75396. }
  75397. }
  75398. };
  75399. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75400. var body = impostor.physicsBody;
  75401. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  75402. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  75403. body.syncShapes();
  75404. body.awake();
  75405. };
  75406. OimoJSPlugin.prototype._getLastShape = function (body) {
  75407. var lastShape = body.shapes;
  75408. while (lastShape.next) {
  75409. lastShape = lastShape.next;
  75410. }
  75411. return lastShape;
  75412. };
  75413. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75414. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  75415. };
  75416. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75417. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  75418. };
  75419. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75420. var v = impostor.physicsBody.linearVelocity;
  75421. if (!v) {
  75422. return null;
  75423. }
  75424. return new BABYLON.Vector3(v.x, v.y, v.z);
  75425. };
  75426. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75427. var v = impostor.physicsBody.angularVelocity;
  75428. if (!v) {
  75429. return null;
  75430. }
  75431. return new BABYLON.Vector3(v.x, v.y, v.z);
  75432. };
  75433. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75434. var staticBody = mass === 0;
  75435. //this will actually set the body's density and not its mass.
  75436. //But this is how oimo treats the mass variable.
  75437. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  75438. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  75439. };
  75440. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  75441. return impostor.physicsBody.shapes.density;
  75442. };
  75443. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  75444. return impostor.physicsBody.shapes.friction;
  75445. };
  75446. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75447. impostor.physicsBody.shapes.friction = friction;
  75448. };
  75449. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75450. return impostor.physicsBody.shapes.restitution;
  75451. };
  75452. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75453. impostor.physicsBody.shapes.restitution = restitution;
  75454. };
  75455. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  75456. impostor.physicsBody.sleep();
  75457. };
  75458. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  75459. impostor.physicsBody.awake();
  75460. };
  75461. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75462. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  75463. if (minDistance !== void 0) {
  75464. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  75465. }
  75466. };
  75467. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75468. //TODO separate rotational and transational motors.
  75469. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75470. if (motor) {
  75471. motor.setMotor(speed, maxForce);
  75472. }
  75473. };
  75474. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  75475. //TODO separate rotational and transational motors.
  75476. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75477. if (motor) {
  75478. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  75479. }
  75480. };
  75481. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75482. var body = impostor.physicsBody;
  75483. mesh.position.x = body.position.x;
  75484. mesh.position.y = body.position.y;
  75485. mesh.position.z = body.position.z;
  75486. if (mesh.rotationQuaternion) {
  75487. mesh.rotationQuaternion.x = body.orientation.x;
  75488. mesh.rotationQuaternion.y = body.orientation.y;
  75489. mesh.rotationQuaternion.z = body.orientation.z;
  75490. mesh.rotationQuaternion.w = body.orientation.s;
  75491. }
  75492. };
  75493. OimoJSPlugin.prototype.getRadius = function (impostor) {
  75494. return impostor.physicsBody.shapes.radius;
  75495. };
  75496. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75497. var shape = impostor.physicsBody.shapes;
  75498. result.x = shape.halfWidth * 2;
  75499. result.y = shape.halfHeight * 2;
  75500. result.z = shape.halfDepth * 2;
  75501. };
  75502. OimoJSPlugin.prototype.dispose = function () {
  75503. this.world.clear();
  75504. };
  75505. return OimoJSPlugin;
  75506. }());
  75507. BABYLON.OimoJSPlugin = OimoJSPlugin;
  75508. })(BABYLON || (BABYLON = {}));
  75509. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  75510. var BABYLON;
  75511. (function (BABYLON) {
  75512. /*
  75513. * Based on jsTGALoader - Javascript loader for TGA file
  75514. * By Vincent Thibault
  75515. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  75516. */
  75517. var TGATools = /** @class */ (function () {
  75518. function TGATools() {
  75519. }
  75520. TGATools.GetTGAHeader = function (data) {
  75521. var offset = 0;
  75522. var header = {
  75523. id_length: data[offset++],
  75524. colormap_type: data[offset++],
  75525. image_type: data[offset++],
  75526. colormap_index: data[offset++] | data[offset++] << 8,
  75527. colormap_length: data[offset++] | data[offset++] << 8,
  75528. colormap_size: data[offset++],
  75529. origin: [
  75530. data[offset++] | data[offset++] << 8,
  75531. data[offset++] | data[offset++] << 8
  75532. ],
  75533. width: data[offset++] | data[offset++] << 8,
  75534. height: data[offset++] | data[offset++] << 8,
  75535. pixel_size: data[offset++],
  75536. flags: data[offset++]
  75537. };
  75538. return header;
  75539. };
  75540. TGATools.UploadContent = function (gl, data) {
  75541. // Not enough data to contain header ?
  75542. if (data.length < 19) {
  75543. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  75544. return;
  75545. }
  75546. // Read Header
  75547. var offset = 18;
  75548. var header = TGATools.GetTGAHeader(data);
  75549. // Assume it's a valid Targa file.
  75550. if (header.id_length + offset > data.length) {
  75551. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  75552. return;
  75553. }
  75554. // Skip not needed data
  75555. offset += header.id_length;
  75556. var use_rle = false;
  75557. var use_pal = false;
  75558. var use_grey = false;
  75559. // Get some informations.
  75560. switch (header.image_type) {
  75561. case TGATools._TYPE_RLE_INDEXED:
  75562. use_rle = true;
  75563. case TGATools._TYPE_INDEXED:
  75564. use_pal = true;
  75565. break;
  75566. case TGATools._TYPE_RLE_RGB:
  75567. use_rle = true;
  75568. case TGATools._TYPE_RGB:
  75569. // use_rgb = true;
  75570. break;
  75571. case TGATools._TYPE_RLE_GREY:
  75572. use_rle = true;
  75573. case TGATools._TYPE_GREY:
  75574. use_grey = true;
  75575. break;
  75576. }
  75577. var pixel_data;
  75578. // var numAlphaBits = header.flags & 0xf;
  75579. var pixel_size = header.pixel_size >> 3;
  75580. var pixel_total = header.width * header.height * pixel_size;
  75581. // Read palettes
  75582. var palettes;
  75583. if (use_pal) {
  75584. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  75585. }
  75586. // Read LRE
  75587. if (use_rle) {
  75588. pixel_data = new Uint8Array(pixel_total);
  75589. var c, count, i;
  75590. var localOffset = 0;
  75591. var pixels = new Uint8Array(pixel_size);
  75592. while (offset < pixel_total && localOffset < pixel_total) {
  75593. c = data[offset++];
  75594. count = (c & 0x7f) + 1;
  75595. // RLE pixels
  75596. if (c & 0x80) {
  75597. // Bind pixel tmp array
  75598. for (i = 0; i < pixel_size; ++i) {
  75599. pixels[i] = data[offset++];
  75600. }
  75601. // Copy pixel array
  75602. for (i = 0; i < count; ++i) {
  75603. pixel_data.set(pixels, localOffset + i * pixel_size);
  75604. }
  75605. localOffset += pixel_size * count;
  75606. }
  75607. else {
  75608. count *= pixel_size;
  75609. for (i = 0; i < count; ++i) {
  75610. pixel_data[localOffset + i] = data[offset++];
  75611. }
  75612. localOffset += count;
  75613. }
  75614. }
  75615. }
  75616. else {
  75617. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  75618. }
  75619. // Load to texture
  75620. var x_start, y_start, x_step, y_step, y_end, x_end;
  75621. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  75622. default:
  75623. case TGATools._ORIGIN_UL:
  75624. x_start = 0;
  75625. x_step = 1;
  75626. x_end = header.width;
  75627. y_start = 0;
  75628. y_step = 1;
  75629. y_end = header.height;
  75630. break;
  75631. case TGATools._ORIGIN_BL:
  75632. x_start = 0;
  75633. x_step = 1;
  75634. x_end = header.width;
  75635. y_start = header.height - 1;
  75636. y_step = -1;
  75637. y_end = -1;
  75638. break;
  75639. case TGATools._ORIGIN_UR:
  75640. x_start = header.width - 1;
  75641. x_step = -1;
  75642. x_end = -1;
  75643. y_start = 0;
  75644. y_step = 1;
  75645. y_end = header.height;
  75646. break;
  75647. case TGATools._ORIGIN_BR:
  75648. x_start = header.width - 1;
  75649. x_step = -1;
  75650. x_end = -1;
  75651. y_start = header.height - 1;
  75652. y_step = -1;
  75653. y_end = -1;
  75654. break;
  75655. }
  75656. // Load the specify method
  75657. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  75658. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  75659. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  75660. };
  75661. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75662. var image = pixel_data, colormap = palettes;
  75663. var width = header.width, height = header.height;
  75664. var color, i = 0, x, y;
  75665. var imageData = new Uint8Array(width * height * 4);
  75666. for (y = y_start; y !== y_end; y += y_step) {
  75667. for (x = x_start; x !== x_end; x += x_step, i++) {
  75668. color = image[i];
  75669. imageData[(x + width * y) * 4 + 3] = 255;
  75670. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  75671. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  75672. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  75673. }
  75674. }
  75675. return imageData;
  75676. };
  75677. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75678. var image = pixel_data;
  75679. var width = header.width, height = header.height;
  75680. var color, i = 0, x, y;
  75681. var imageData = new Uint8Array(width * height * 4);
  75682. for (y = y_start; y !== y_end; y += y_step) {
  75683. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75684. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  75685. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  75686. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  75687. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  75688. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  75689. }
  75690. }
  75691. return imageData;
  75692. };
  75693. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75694. var image = pixel_data;
  75695. var width = header.width, height = header.height;
  75696. var i = 0, x, y;
  75697. var imageData = new Uint8Array(width * height * 4);
  75698. for (y = y_start; y !== y_end; y += y_step) {
  75699. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  75700. imageData[(x + width * y) * 4 + 3] = 255;
  75701. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75702. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75703. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75704. }
  75705. }
  75706. return imageData;
  75707. };
  75708. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75709. var image = pixel_data;
  75710. var width = header.width, height = header.height;
  75711. var i = 0, x, y;
  75712. var imageData = new Uint8Array(width * height * 4);
  75713. for (y = y_start; y !== y_end; y += y_step) {
  75714. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  75715. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75716. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75717. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75718. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  75719. }
  75720. }
  75721. return imageData;
  75722. };
  75723. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75724. var image = pixel_data;
  75725. var width = header.width, height = header.height;
  75726. var color, i = 0, x, y;
  75727. var imageData = new Uint8Array(width * height * 4);
  75728. for (y = y_start; y !== y_end; y += y_step) {
  75729. for (x = x_start; x !== x_end; x += x_step, i++) {
  75730. color = image[i];
  75731. imageData[(x + width * y) * 4 + 0] = color;
  75732. imageData[(x + width * y) * 4 + 1] = color;
  75733. imageData[(x + width * y) * 4 + 2] = color;
  75734. imageData[(x + width * y) * 4 + 3] = 255;
  75735. }
  75736. }
  75737. return imageData;
  75738. };
  75739. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75740. var image = pixel_data;
  75741. var width = header.width, height = header.height;
  75742. var i = 0, x, y;
  75743. var imageData = new Uint8Array(width * height * 4);
  75744. for (y = y_start; y !== y_end; y += y_step) {
  75745. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75746. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  75747. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  75748. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75749. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  75750. }
  75751. }
  75752. return imageData;
  75753. };
  75754. //private static _TYPE_NO_DATA = 0;
  75755. TGATools._TYPE_INDEXED = 1;
  75756. TGATools._TYPE_RGB = 2;
  75757. TGATools._TYPE_GREY = 3;
  75758. TGATools._TYPE_RLE_INDEXED = 9;
  75759. TGATools._TYPE_RLE_RGB = 10;
  75760. TGATools._TYPE_RLE_GREY = 11;
  75761. TGATools._ORIGIN_MASK = 0x30;
  75762. TGATools._ORIGIN_SHIFT = 0x04;
  75763. TGATools._ORIGIN_BL = 0x00;
  75764. TGATools._ORIGIN_BR = 0x01;
  75765. TGATools._ORIGIN_UL = 0x02;
  75766. TGATools._ORIGIN_UR = 0x03;
  75767. return TGATools;
  75768. }());
  75769. BABYLON.TGATools = TGATools;
  75770. })(BABYLON || (BABYLON = {}));
  75771. //# sourceMappingURL=babylon.tga.js.map
  75772. var BABYLON;
  75773. (function (BABYLON) {
  75774. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  75775. // All values and structures referenced from:
  75776. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  75777. var DDS_MAGIC = 0x20534444;
  75778. var
  75779. //DDSD_CAPS = 0x1,
  75780. //DDSD_HEIGHT = 0x2,
  75781. //DDSD_WIDTH = 0x4,
  75782. //DDSD_PITCH = 0x8,
  75783. //DDSD_PIXELFORMAT = 0x1000,
  75784. DDSD_MIPMAPCOUNT = 0x20000;
  75785. //DDSD_LINEARSIZE = 0x80000,
  75786. //DDSD_DEPTH = 0x800000;
  75787. // var DDSCAPS_COMPLEX = 0x8,
  75788. // DDSCAPS_MIPMAP = 0x400000,
  75789. // DDSCAPS_TEXTURE = 0x1000;
  75790. var DDSCAPS2_CUBEMAP = 0x200;
  75791. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  75792. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  75793. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  75794. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  75795. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  75796. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  75797. // DDSCAPS2_VOLUME = 0x200000;
  75798. var
  75799. //DDPF_ALPHAPIXELS = 0x1,
  75800. //DDPF_ALPHA = 0x2,
  75801. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  75802. //DDPF_YUV = 0x200,
  75803. DDPF_LUMINANCE = 0x20000;
  75804. function FourCCToInt32(value) {
  75805. return value.charCodeAt(0) +
  75806. (value.charCodeAt(1) << 8) +
  75807. (value.charCodeAt(2) << 16) +
  75808. (value.charCodeAt(3) << 24);
  75809. }
  75810. function Int32ToFourCC(value) {
  75811. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  75812. }
  75813. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  75814. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  75815. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  75816. var FOURCC_DX10 = FourCCToInt32("DX10");
  75817. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  75818. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  75819. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  75820. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  75821. var headerLengthInt = 31; // The header length in 32 bit ints
  75822. // Offsets into the header array
  75823. var off_magic = 0;
  75824. var off_size = 1;
  75825. var off_flags = 2;
  75826. var off_height = 3;
  75827. var off_width = 4;
  75828. var off_mipmapCount = 7;
  75829. var off_pfFlags = 20;
  75830. var off_pfFourCC = 21;
  75831. var off_RGBbpp = 22;
  75832. var off_RMask = 23;
  75833. var off_GMask = 24;
  75834. var off_BMask = 25;
  75835. var off_AMask = 26;
  75836. // var off_caps1 = 27;
  75837. var off_caps2 = 28;
  75838. // var off_caps3 = 29;
  75839. // var off_caps4 = 30;
  75840. var off_dxgiFormat = 32;
  75841. ;
  75842. var DDSTools = /** @class */ (function () {
  75843. function DDSTools() {
  75844. }
  75845. DDSTools.GetDDSInfo = function (arrayBuffer) {
  75846. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  75847. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  75848. var mipmapCount = 1;
  75849. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  75850. mipmapCount = Math.max(1, header[off_mipmapCount]);
  75851. }
  75852. var fourCC = header[off_pfFourCC];
  75853. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  75854. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75855. switch (fourCC) {
  75856. case FOURCC_D3DFMT_R16G16B16A16F:
  75857. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75858. break;
  75859. case FOURCC_D3DFMT_R32G32B32A32F:
  75860. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75861. break;
  75862. case FOURCC_DX10:
  75863. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  75864. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75865. break;
  75866. }
  75867. }
  75868. return {
  75869. width: header[off_width],
  75870. height: header[off_height],
  75871. mipmapCount: mipmapCount,
  75872. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  75873. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  75874. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  75875. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  75876. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  75877. dxgiFormat: dxgiFormat,
  75878. textureType: textureType
  75879. };
  75880. };
  75881. DDSTools._ToHalfFloat = function (value) {
  75882. if (!DDSTools._FloatView) {
  75883. DDSTools._FloatView = new Float32Array(1);
  75884. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  75885. }
  75886. DDSTools._FloatView[0] = value;
  75887. var x = DDSTools._Int32View[0];
  75888. var bits = (x >> 16) & 0x8000; /* Get the sign */
  75889. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  75890. var e = (x >> 23) & 0xff; /* Using int is faster here */
  75891. /* If zero, or denormal, or exponent underflows too much for a denormal
  75892. * half, return signed zero. */
  75893. if (e < 103) {
  75894. return bits;
  75895. }
  75896. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  75897. if (e > 142) {
  75898. bits |= 0x7c00;
  75899. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  75900. * not Inf, so make sure we set one mantissa bit too. */
  75901. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  75902. return bits;
  75903. }
  75904. /* If exponent underflows but not too much, return a denormal */
  75905. if (e < 113) {
  75906. m |= 0x0800;
  75907. /* Extra rounding may overflow and set mantissa to 0 and exponent
  75908. * to 1, which is OK. */
  75909. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  75910. return bits;
  75911. }
  75912. bits |= ((e - 112) << 10) | (m >> 1);
  75913. bits += m & 1;
  75914. return bits;
  75915. };
  75916. DDSTools._FromHalfFloat = function (value) {
  75917. var s = (value & 0x8000) >> 15;
  75918. var e = (value & 0x7C00) >> 10;
  75919. var f = value & 0x03FF;
  75920. if (e === 0) {
  75921. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  75922. }
  75923. else if (e == 0x1F) {
  75924. return f ? NaN : ((s ? -1 : 1) * Infinity);
  75925. }
  75926. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  75927. };
  75928. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75929. var destArray = new Float32Array(dataLength);
  75930. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75931. var index = 0;
  75932. for (var y = 0; y < height; y++) {
  75933. for (var x = 0; x < width; x++) {
  75934. var srcPos = (x + y * width) * 4;
  75935. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  75936. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  75937. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  75938. if (DDSTools.StoreLODInAlphaChannel) {
  75939. destArray[index + 3] = lod;
  75940. }
  75941. else {
  75942. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  75943. }
  75944. index += 4;
  75945. }
  75946. }
  75947. return destArray;
  75948. };
  75949. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75950. if (DDSTools.StoreLODInAlphaChannel) {
  75951. var destArray = new Uint16Array(dataLength);
  75952. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75953. var index = 0;
  75954. for (var y = 0; y < height; y++) {
  75955. for (var x = 0; x < width; x++) {
  75956. var srcPos = (x + y * width) * 4;
  75957. destArray[index] = srcData[srcPos];
  75958. destArray[index + 1] = srcData[srcPos + 1];
  75959. destArray[index + 2] = srcData[srcPos + 2];
  75960. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  75961. index += 4;
  75962. }
  75963. }
  75964. return destArray;
  75965. }
  75966. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  75967. };
  75968. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75969. if (DDSTools.StoreLODInAlphaChannel) {
  75970. var destArray = new Float32Array(dataLength);
  75971. var srcData = new Float32Array(arrayBuffer, dataOffset);
  75972. var index = 0;
  75973. for (var y = 0; y < height; y++) {
  75974. for (var x = 0; x < width; x++) {
  75975. var srcPos = (x + y * width) * 4;
  75976. destArray[index] = srcData[srcPos];
  75977. destArray[index + 1] = srcData[srcPos + 1];
  75978. destArray[index + 2] = srcData[srcPos + 2];
  75979. destArray[index + 3] = lod;
  75980. index += 4;
  75981. }
  75982. }
  75983. return destArray;
  75984. }
  75985. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  75986. };
  75987. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75988. var destArray = new Uint8Array(dataLength);
  75989. var srcData = new Float32Array(arrayBuffer, dataOffset);
  75990. var index = 0;
  75991. for (var y = 0; y < height; y++) {
  75992. for (var x = 0; x < width; x++) {
  75993. var srcPos = (x + y * width) * 4;
  75994. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  75995. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  75996. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  75997. if (DDSTools.StoreLODInAlphaChannel) {
  75998. destArray[index + 3] = lod;
  75999. }
  76000. else {
  76001. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  76002. }
  76003. index += 4;
  76004. }
  76005. }
  76006. return destArray;
  76007. };
  76008. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76009. var destArray = new Uint8Array(dataLength);
  76010. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76011. var index = 0;
  76012. for (var y = 0; y < height; y++) {
  76013. for (var x = 0; x < width; x++) {
  76014. var srcPos = (x + y * width) * 4;
  76015. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  76016. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  76017. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  76018. if (DDSTools.StoreLODInAlphaChannel) {
  76019. destArray[index + 3] = lod;
  76020. }
  76021. else {
  76022. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  76023. }
  76024. index += 4;
  76025. }
  76026. }
  76027. return destArray;
  76028. };
  76029. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  76030. var byteArray = new Uint8Array(dataLength);
  76031. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76032. var index = 0;
  76033. for (var y = 0; y < height; y++) {
  76034. for (var x = 0; x < width; x++) {
  76035. var srcPos = (x + y * width) * 4;
  76036. byteArray[index] = srcData[srcPos + rOffset];
  76037. byteArray[index + 1] = srcData[srcPos + gOffset];
  76038. byteArray[index + 2] = srcData[srcPos + bOffset];
  76039. byteArray[index + 3] = srcData[srcPos + aOffset];
  76040. index += 4;
  76041. }
  76042. }
  76043. return byteArray;
  76044. };
  76045. DDSTools._ExtractLongWordOrder = function (value) {
  76046. if (value === 0 || value === 255 || value === -16777216) {
  76047. return 0;
  76048. }
  76049. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  76050. };
  76051. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  76052. var byteArray = new Uint8Array(dataLength);
  76053. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76054. var index = 0;
  76055. for (var y = 0; y < height; y++) {
  76056. for (var x = 0; x < width; x++) {
  76057. var srcPos = (x + y * width) * 3;
  76058. byteArray[index] = srcData[srcPos + rOffset];
  76059. byteArray[index + 1] = srcData[srcPos + gOffset];
  76060. byteArray[index + 2] = srcData[srcPos + bOffset];
  76061. index += 3;
  76062. }
  76063. }
  76064. return byteArray;
  76065. };
  76066. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  76067. var byteArray = new Uint8Array(dataLength);
  76068. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76069. var index = 0;
  76070. for (var y = 0; y < height; y++) {
  76071. for (var x = 0; x < width; x++) {
  76072. var srcPos = (x + y * width);
  76073. byteArray[index] = srcData[srcPos];
  76074. index++;
  76075. }
  76076. }
  76077. return byteArray;
  76078. };
  76079. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  76080. if (lodIndex === void 0) { lodIndex = -1; }
  76081. var ext = engine.getCaps().s3tc;
  76082. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  76083. var fourCC, width, height, dataLength = 0, dataOffset;
  76084. var byteArray, mipmapCount, mip;
  76085. var internalFormat = 0;
  76086. var format = 0;
  76087. var blockBytes = 1;
  76088. if (header[off_magic] !== DDS_MAGIC) {
  76089. BABYLON.Tools.Error("Invalid magic number in DDS header");
  76090. return;
  76091. }
  76092. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  76093. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  76094. return;
  76095. }
  76096. if (info.isCompressed && !ext) {
  76097. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  76098. return;
  76099. }
  76100. var bpp = header[off_RGBbpp];
  76101. dataOffset = header[off_size] + 4;
  76102. var computeFormats = false;
  76103. if (info.isFourCC) {
  76104. fourCC = header[off_pfFourCC];
  76105. switch (fourCC) {
  76106. case FOURCC_DXT1:
  76107. blockBytes = 8;
  76108. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  76109. break;
  76110. case FOURCC_DXT3:
  76111. blockBytes = 16;
  76112. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  76113. break;
  76114. case FOURCC_DXT5:
  76115. blockBytes = 16;
  76116. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  76117. break;
  76118. case FOURCC_D3DFMT_R16G16B16A16F:
  76119. computeFormats = true;
  76120. break;
  76121. case FOURCC_D3DFMT_R32G32B32A32F:
  76122. computeFormats = true;
  76123. break;
  76124. case FOURCC_DX10:
  76125. // There is an additionnal header so dataOffset need to be changed
  76126. dataOffset += 5 * 4; // 5 uints
  76127. var supported = false;
  76128. switch (info.dxgiFormat) {
  76129. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  76130. computeFormats = true;
  76131. supported = true;
  76132. break;
  76133. case DXGI_FORMAT_B8G8R8X8_UNORM:
  76134. info.isRGB = true;
  76135. info.isFourCC = false;
  76136. bpp = 32;
  76137. supported = true;
  76138. break;
  76139. }
  76140. if (supported) {
  76141. break;
  76142. }
  76143. default:
  76144. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  76145. return;
  76146. }
  76147. }
  76148. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  76149. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  76150. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  76151. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  76152. if (computeFormats) {
  76153. format = engine._getWebGLTextureType(info.textureType);
  76154. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76155. }
  76156. mipmapCount = 1;
  76157. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  76158. mipmapCount = Math.max(1, header[off_mipmapCount]);
  76159. }
  76160. for (var face = 0; face < faces; face++) {
  76161. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  76162. width = header[off_width];
  76163. height = header[off_height];
  76164. for (mip = 0; mip < mipmapCount; ++mip) {
  76165. if (lodIndex === -1 || lodIndex === mip) {
  76166. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  76167. var i = (lodIndex === -1) ? mip : 0;
  76168. if (!info.isCompressed && info.isFourCC) {
  76169. dataLength = width * height * 4;
  76170. var floatArray = null;
  76171. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  76172. if (bpp === 128) {
  76173. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76174. }
  76175. else if (bpp === 64) {
  76176. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76177. }
  76178. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76179. format = engine._getWebGLTextureType(info.textureType);
  76180. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76181. }
  76182. else {
  76183. if (bpp === 128) {
  76184. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76185. }
  76186. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  76187. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76188. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76189. format = engine._getWebGLTextureType(info.textureType);
  76190. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76191. }
  76192. else {
  76193. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76194. }
  76195. }
  76196. if (floatArray) {
  76197. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  76198. }
  76199. }
  76200. else if (info.isRGB) {
  76201. if (bpp === 24) {
  76202. dataLength = width * height * 3;
  76203. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  76204. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  76205. }
  76206. else {
  76207. dataLength = width * height * 4;
  76208. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  76209. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  76210. }
  76211. }
  76212. else if (info.isLuminance) {
  76213. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  76214. var unpaddedRowSize = width;
  76215. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  76216. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  76217. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  76218. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  76219. }
  76220. else {
  76221. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  76222. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  76223. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  76224. }
  76225. }
  76226. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  76227. width *= 0.5;
  76228. height *= 0.5;
  76229. width = Math.max(1.0, width);
  76230. height = Math.max(1.0, height);
  76231. }
  76232. if (currentFace !== undefined) {
  76233. // Loading a single face
  76234. break;
  76235. }
  76236. }
  76237. };
  76238. DDSTools.StoreLODInAlphaChannel = false;
  76239. return DDSTools;
  76240. }());
  76241. BABYLON.DDSTools = DDSTools;
  76242. })(BABYLON || (BABYLON = {}));
  76243. //# sourceMappingURL=babylon.dds.js.map
  76244. var BABYLON;
  76245. (function (BABYLON) {
  76246. /**
  76247. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  76248. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  76249. */
  76250. var KhronosTextureContainer = /** @class */ (function () {
  76251. /**
  76252. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  76253. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  76254. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  76255. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  76256. */
  76257. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  76258. this.arrayBuffer = arrayBuffer;
  76259. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  76260. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  76261. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  76262. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  76263. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  76264. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  76265. BABYLON.Tools.Error("texture missing KTX identifier");
  76266. return;
  76267. }
  76268. // load the reset of the header in native 32 bit int
  76269. var header = new Int32Array(this.arrayBuffer, 12, 13);
  76270. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  76271. var oppositeEndianess = header[0] === 0x01020304;
  76272. // read all the header elements in order they exist in the file, without modification (sans endainness)
  76273. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  76274. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  76275. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  76276. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  76277. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  76278. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  76279. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  76280. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  76281. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  76282. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  76283. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  76284. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  76285. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  76286. if (this.glType !== 0) {
  76287. BABYLON.Tools.Error("only compressed formats currently supported");
  76288. return;
  76289. }
  76290. else {
  76291. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  76292. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  76293. }
  76294. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  76295. BABYLON.Tools.Error("only 2D textures currently supported");
  76296. return;
  76297. }
  76298. if (this.numberOfArrayElements !== 0) {
  76299. BABYLON.Tools.Error("texture arrays not currently supported");
  76300. return;
  76301. }
  76302. if (this.numberOfFaces !== facesExpected) {
  76303. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  76304. return;
  76305. }
  76306. // we now have a completely validated file, so could use existence of loadType as success
  76307. // would need to make this more elaborate & adjust checks above to support more than one load type
  76308. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  76309. }
  76310. // not as fast hardware based, but will probably never need to use
  76311. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  76312. return ((val & 0xFF) << 24)
  76313. | ((val & 0xFF00) << 8)
  76314. | ((val >> 8) & 0xFF00)
  76315. | ((val >> 24) & 0xFF);
  76316. };
  76317. /**
  76318. * It is assumed that the texture has already been created & is currently bound
  76319. */
  76320. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  76321. switch (this.loadType) {
  76322. case KhronosTextureContainer.COMPRESSED_2D:
  76323. this._upload2DCompressedLevels(gl, loadMipmaps);
  76324. break;
  76325. case KhronosTextureContainer.TEX_2D:
  76326. case KhronosTextureContainer.COMPRESSED_3D:
  76327. case KhronosTextureContainer.TEX_3D:
  76328. }
  76329. };
  76330. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  76331. // initialize width & height for level 1
  76332. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  76333. var width = this.pixelWidth;
  76334. var height = this.pixelHeight;
  76335. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  76336. for (var level = 0; level < mipmapCount; level++) {
  76337. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  76338. for (var face = 0; face < this.numberOfFaces; face++) {
  76339. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  76340. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  76341. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  76342. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  76343. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  76344. }
  76345. width = Math.max(1.0, width * 0.5);
  76346. height = Math.max(1.0, height * 0.5);
  76347. }
  76348. };
  76349. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  76350. // load types
  76351. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  76352. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  76353. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  76354. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  76355. return KhronosTextureContainer;
  76356. }());
  76357. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  76358. })(BABYLON || (BABYLON = {}));
  76359. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  76360. var BABYLON;
  76361. (function (BABYLON) {
  76362. var Debug = /** @class */ (function () {
  76363. function Debug() {
  76364. }
  76365. Debug.AxesViewer = /** @class */ (function () {
  76366. function AxesViewer(scene, scaleLines) {
  76367. if (scaleLines === void 0) { scaleLines = 1; }
  76368. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76369. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76370. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76371. this.scaleLines = 1;
  76372. this.scaleLines = scaleLines;
  76373. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  76374. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  76375. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  76376. this._xmesh.renderingGroupId = 2;
  76377. this._ymesh.renderingGroupId = 2;
  76378. this._zmesh.renderingGroupId = 2;
  76379. this._xmesh.material.checkReadyOnlyOnce = true;
  76380. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  76381. this._ymesh.material.checkReadyOnlyOnce = true;
  76382. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  76383. this._zmesh.material.checkReadyOnlyOnce = true;
  76384. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  76385. this.scene = scene;
  76386. }
  76387. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  76388. var scaleLines = this.scaleLines;
  76389. if (this._xmesh) {
  76390. this._xmesh.position.copyFrom(position);
  76391. }
  76392. if (this._ymesh) {
  76393. this._ymesh.position.copyFrom(position);
  76394. }
  76395. if (this._zmesh) {
  76396. this._zmesh.position.copyFrom(position);
  76397. }
  76398. var point2 = this._xline[1];
  76399. point2.x = xaxis.x * scaleLines;
  76400. point2.y = xaxis.y * scaleLines;
  76401. point2.z = xaxis.z * scaleLines;
  76402. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  76403. point2 = this._yline[1];
  76404. point2.x = yaxis.x * scaleLines;
  76405. point2.y = yaxis.y * scaleLines;
  76406. point2.z = yaxis.z * scaleLines;
  76407. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  76408. point2 = this._zline[1];
  76409. point2.x = zaxis.x * scaleLines;
  76410. point2.y = zaxis.y * scaleLines;
  76411. point2.z = zaxis.z * scaleLines;
  76412. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  76413. };
  76414. AxesViewer.prototype.dispose = function () {
  76415. if (this._xmesh) {
  76416. this._xmesh.dispose();
  76417. }
  76418. if (this._ymesh) {
  76419. this._ymesh.dispose();
  76420. }
  76421. if (this._zmesh) {
  76422. this._zmesh.dispose();
  76423. }
  76424. this._xmesh = null;
  76425. this._ymesh = null;
  76426. this._zmesh = null;
  76427. this.scene = null;
  76428. };
  76429. return AxesViewer;
  76430. }());
  76431. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  76432. __extends(BoneAxesViewer, _super);
  76433. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  76434. if (scaleLines === void 0) { scaleLines = 1; }
  76435. var _this = _super.call(this, scene, scaleLines) || this;
  76436. _this.pos = BABYLON.Vector3.Zero();
  76437. _this.xaxis = BABYLON.Vector3.Zero();
  76438. _this.yaxis = BABYLON.Vector3.Zero();
  76439. _this.zaxis = BABYLON.Vector3.Zero();
  76440. _this.mesh = mesh;
  76441. _this.bone = bone;
  76442. return _this;
  76443. }
  76444. BoneAxesViewer.prototype.update = function () {
  76445. if (!this.mesh || !this.bone) {
  76446. return;
  76447. }
  76448. var bone = this.bone;
  76449. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  76450. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  76451. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  76452. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  76453. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  76454. };
  76455. BoneAxesViewer.prototype.dispose = function () {
  76456. if (this.mesh) {
  76457. this.mesh = null;
  76458. this.bone = null;
  76459. _super.prototype.dispose.call(this);
  76460. }
  76461. };
  76462. return BoneAxesViewer;
  76463. }(Debug.AxesViewer));
  76464. Debug.PhysicsViewer = /** @class */ (function () {
  76465. function PhysicsViewer(scene) {
  76466. this._impostors = [];
  76467. this._meshes = [];
  76468. this._numMeshes = 0;
  76469. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76470. var physicEngine = this._scene.getPhysicsEngine();
  76471. if (physicEngine) {
  76472. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  76473. }
  76474. }
  76475. PhysicsViewer.prototype._updateDebugMeshes = function () {
  76476. var plugin = this._physicsEnginePlugin;
  76477. for (var i = 0; i < this._numMeshes; i++) {
  76478. var impostor = this._impostors[i];
  76479. if (!impostor) {
  76480. continue;
  76481. }
  76482. if (impostor.isDisposed) {
  76483. this.hideImpostor(this._impostors[i--]);
  76484. }
  76485. else {
  76486. var mesh = this._meshes[i];
  76487. if (mesh && plugin) {
  76488. plugin.syncMeshWithImpostor(mesh, impostor);
  76489. }
  76490. }
  76491. }
  76492. };
  76493. PhysicsViewer.prototype.showImpostor = function (impostor) {
  76494. if (!this._scene) {
  76495. return;
  76496. }
  76497. for (var i = 0; i < this._numMeshes; i++) {
  76498. if (this._impostors[i] == impostor) {
  76499. return;
  76500. }
  76501. }
  76502. var debugMesh = this._getDebugMesh(impostor, this._scene);
  76503. if (debugMesh) {
  76504. this._impostors[this._numMeshes] = impostor;
  76505. this._meshes[this._numMeshes] = debugMesh;
  76506. if (this._numMeshes === 0) {
  76507. this._renderFunction = this._updateDebugMeshes.bind(this);
  76508. this._scene.registerBeforeRender(this._renderFunction);
  76509. }
  76510. this._numMeshes++;
  76511. }
  76512. };
  76513. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  76514. if (!impostor || !this._scene) {
  76515. return;
  76516. }
  76517. var removed = false;
  76518. for (var i = 0; i < this._numMeshes; i++) {
  76519. if (this._impostors[i] == impostor) {
  76520. var mesh = this._meshes[i];
  76521. if (!mesh) {
  76522. continue;
  76523. }
  76524. this._scene.removeMesh(mesh);
  76525. mesh.dispose();
  76526. this._numMeshes--;
  76527. if (this._numMeshes > 0) {
  76528. this._meshes[i] = this._meshes[this._numMeshes];
  76529. this._impostors[i] = this._impostors[this._numMeshes];
  76530. this._meshes[this._numMeshes] = null;
  76531. this._impostors[this._numMeshes] = null;
  76532. }
  76533. else {
  76534. this._meshes[0] = null;
  76535. this._impostors[0] = null;
  76536. }
  76537. removed = true;
  76538. break;
  76539. }
  76540. }
  76541. if (removed && this._numMeshes === 0) {
  76542. this._scene.unregisterBeforeRender(this._renderFunction);
  76543. }
  76544. };
  76545. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  76546. if (!this._debugMaterial) {
  76547. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  76548. this._debugMaterial.wireframe = true;
  76549. }
  76550. return this._debugMaterial;
  76551. };
  76552. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  76553. if (!this._debugBoxMesh) {
  76554. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  76555. this._debugBoxMesh.renderingGroupId = 1;
  76556. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76557. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  76558. scene.removeMesh(this._debugBoxMesh);
  76559. }
  76560. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  76561. };
  76562. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  76563. if (!this._debugSphereMesh) {
  76564. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  76565. this._debugSphereMesh.renderingGroupId = 1;
  76566. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76567. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  76568. scene.removeMesh(this._debugSphereMesh);
  76569. }
  76570. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  76571. };
  76572. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  76573. var mesh = null;
  76574. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  76575. mesh = this._getDebugBoxMesh(scene);
  76576. impostor.getBoxSizeToRef(mesh.scaling);
  76577. }
  76578. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  76579. mesh = this._getDebugSphereMesh(scene);
  76580. var radius = impostor.getRadius();
  76581. mesh.scaling.x = radius * 2;
  76582. mesh.scaling.y = radius * 2;
  76583. mesh.scaling.z = radius * 2;
  76584. }
  76585. return mesh;
  76586. };
  76587. PhysicsViewer.prototype.dispose = function () {
  76588. for (var i = 0; i < this._numMeshes; i++) {
  76589. this.hideImpostor(this._impostors[i]);
  76590. }
  76591. if (this._debugBoxMesh) {
  76592. this._debugBoxMesh.dispose();
  76593. }
  76594. if (this._debugSphereMesh) {
  76595. this._debugSphereMesh.dispose();
  76596. }
  76597. if (this._debugMaterial) {
  76598. this._debugMaterial.dispose();
  76599. }
  76600. this._impostors.length = 0;
  76601. this._scene = null;
  76602. this._physicsEnginePlugin = null;
  76603. };
  76604. return PhysicsViewer;
  76605. }());
  76606. Debug.SkeletonViewer = /** @class */ (function () {
  76607. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  76608. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  76609. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  76610. this.skeleton = skeleton;
  76611. this.mesh = mesh;
  76612. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  76613. this.renderingGroupId = renderingGroupId;
  76614. this.color = BABYLON.Color3.White();
  76615. this._debugLines = new Array();
  76616. this._isEnabled = false;
  76617. this._scene = scene;
  76618. this.update();
  76619. this._renderFunction = this.update.bind(this);
  76620. }
  76621. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  76622. get: function () {
  76623. return this._isEnabled;
  76624. },
  76625. set: function (value) {
  76626. if (this._isEnabled === value) {
  76627. return;
  76628. }
  76629. this._isEnabled = value;
  76630. if (value) {
  76631. this._scene.registerBeforeRender(this._renderFunction);
  76632. }
  76633. else {
  76634. this._scene.unregisterBeforeRender(this._renderFunction);
  76635. }
  76636. },
  76637. enumerable: true,
  76638. configurable: true
  76639. });
  76640. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  76641. if (x === void 0) { x = 0; }
  76642. if (y === void 0) { y = 0; }
  76643. if (z === void 0) { z = 0; }
  76644. var tmat = BABYLON.Tmp.Matrix[0];
  76645. var parentBone = bone.getParent();
  76646. tmat.copyFrom(bone.getLocalMatrix());
  76647. if (x !== 0 || y !== 0 || z !== 0) {
  76648. var tmat2 = BABYLON.Tmp.Matrix[1];
  76649. BABYLON.Matrix.IdentityToRef(tmat2);
  76650. tmat2.m[12] = x;
  76651. tmat2.m[13] = y;
  76652. tmat2.m[14] = z;
  76653. tmat2.multiplyToRef(tmat, tmat);
  76654. }
  76655. if (parentBone) {
  76656. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  76657. }
  76658. tmat.multiplyToRef(meshMat, tmat);
  76659. position.x = tmat.m[12];
  76660. position.y = tmat.m[13];
  76661. position.z = tmat.m[14];
  76662. };
  76663. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  76664. var len = bones.length;
  76665. var meshPos = this.mesh.position;
  76666. for (var i = 0; i < len; i++) {
  76667. var bone = bones[i];
  76668. var points = this._debugLines[i];
  76669. if (!points) {
  76670. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76671. this._debugLines[i] = points;
  76672. }
  76673. this._getBonePosition(points[0], bone, meshMat);
  76674. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  76675. points[0].subtractInPlace(meshPos);
  76676. points[1].subtractInPlace(meshPos);
  76677. }
  76678. };
  76679. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  76680. var len = bones.length;
  76681. var boneNum = 0;
  76682. var meshPos = this.mesh.position;
  76683. for (var i = len - 1; i >= 0; i--) {
  76684. var childBone = bones[i];
  76685. var parentBone = childBone.getParent();
  76686. if (!parentBone) {
  76687. continue;
  76688. }
  76689. var points = this._debugLines[boneNum];
  76690. if (!points) {
  76691. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76692. this._debugLines[boneNum] = points;
  76693. }
  76694. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  76695. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  76696. points[0].subtractInPlace(meshPos);
  76697. points[1].subtractInPlace(meshPos);
  76698. boneNum++;
  76699. }
  76700. };
  76701. SkeletonViewer.prototype.update = function () {
  76702. if (this.autoUpdateBonesMatrices) {
  76703. this.skeleton.computeAbsoluteTransforms();
  76704. }
  76705. if (this.skeleton.bones[0].length === undefined) {
  76706. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76707. }
  76708. else {
  76709. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76710. }
  76711. if (!this._debugMesh) {
  76712. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  76713. this._debugMesh.renderingGroupId = this.renderingGroupId;
  76714. }
  76715. else {
  76716. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  76717. }
  76718. this._debugMesh.position.copyFrom(this.mesh.position);
  76719. this._debugMesh.color = this.color;
  76720. };
  76721. SkeletonViewer.prototype.dispose = function () {
  76722. if (this._debugMesh) {
  76723. this.isEnabled = false;
  76724. this._debugMesh.dispose();
  76725. this._debugMesh = null;
  76726. }
  76727. };
  76728. return SkeletonViewer;
  76729. }());
  76730. return Debug;
  76731. }());
  76732. BABYLON.Debug = Debug;
  76733. })(BABYLON || (BABYLON = {}));
  76734. //# sourceMappingURL=babylon.debugModules.js.map
  76735. var BABYLON;
  76736. (function (BABYLON) {
  76737. var RayHelper = /** @class */ (function () {
  76738. function RayHelper(ray) {
  76739. this.ray = ray;
  76740. }
  76741. RayHelper.CreateAndShow = function (ray, scene, color) {
  76742. var helper = new RayHelper(ray);
  76743. helper.show(scene, color);
  76744. return helper;
  76745. };
  76746. RayHelper.prototype.show = function (scene, color) {
  76747. if (!this._renderFunction && this.ray) {
  76748. var ray = this.ray;
  76749. this._renderFunction = this._render.bind(this);
  76750. this._scene = scene;
  76751. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  76752. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  76753. if (this._renderFunction) {
  76754. this._scene.registerBeforeRender(this._renderFunction);
  76755. }
  76756. }
  76757. if (color && this._renderLine) {
  76758. this._renderLine.color.copyFrom(color);
  76759. }
  76760. };
  76761. RayHelper.prototype.hide = function () {
  76762. if (this._renderFunction && this._scene) {
  76763. this._scene.unregisterBeforeRender(this._renderFunction);
  76764. this._scene = null;
  76765. this._renderFunction = null;
  76766. if (this._renderLine) {
  76767. this._renderLine.dispose();
  76768. this._renderLine = null;
  76769. }
  76770. this._renderPoints = [];
  76771. }
  76772. };
  76773. RayHelper.prototype._render = function () {
  76774. var ray = this.ray;
  76775. if (!ray) {
  76776. return;
  76777. }
  76778. var point = this._renderPoints[1];
  76779. var len = Math.min(ray.length, 1000000);
  76780. point.copyFrom(ray.direction);
  76781. point.scaleInPlace(len);
  76782. point.addInPlace(ray.origin);
  76783. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  76784. };
  76785. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  76786. this._attachedToMesh = mesh;
  76787. var ray = this.ray;
  76788. if (!ray) {
  76789. return;
  76790. }
  76791. if (!ray.direction) {
  76792. ray.direction = BABYLON.Vector3.Zero();
  76793. }
  76794. if (!ray.origin) {
  76795. ray.origin = BABYLON.Vector3.Zero();
  76796. }
  76797. if (length) {
  76798. ray.length = length;
  76799. }
  76800. if (!meshSpaceOrigin) {
  76801. meshSpaceOrigin = BABYLON.Vector3.Zero();
  76802. }
  76803. if (!meshSpaceDirection) {
  76804. // -1 so that this will work with Mesh.lookAt
  76805. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  76806. }
  76807. if (!this._meshSpaceDirection) {
  76808. this._meshSpaceDirection = meshSpaceDirection.clone();
  76809. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  76810. }
  76811. else {
  76812. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  76813. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  76814. }
  76815. if (!this._updateToMeshFunction) {
  76816. this._updateToMeshFunction = this._updateToMesh.bind(this);
  76817. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  76818. }
  76819. this._updateToMesh();
  76820. };
  76821. RayHelper.prototype.detachFromMesh = function () {
  76822. if (this._attachedToMesh) {
  76823. if (this._updateToMeshFunction) {
  76824. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  76825. }
  76826. this._attachedToMesh = null;
  76827. this._updateToMeshFunction = null;
  76828. }
  76829. };
  76830. RayHelper.prototype._updateToMesh = function () {
  76831. var ray = this.ray;
  76832. if (!this._attachedToMesh || !ray) {
  76833. return;
  76834. }
  76835. if (this._attachedToMesh._isDisposed) {
  76836. this.detachFromMesh();
  76837. return;
  76838. }
  76839. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  76840. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  76841. };
  76842. RayHelper.prototype.dispose = function () {
  76843. this.hide();
  76844. this.detachFromMesh();
  76845. this.ray = null;
  76846. };
  76847. return RayHelper;
  76848. }());
  76849. BABYLON.RayHelper = RayHelper;
  76850. })(BABYLON || (BABYLON = {}));
  76851. //# sourceMappingURL=babylon.rayHelper.js.map
  76852. var BABYLON;
  76853. (function (BABYLON) {
  76854. // load the inspector using require, if not present in the global namespace.
  76855. var DebugLayer = /** @class */ (function () {
  76856. function DebugLayer(scene) {
  76857. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76858. this._scene = scene;
  76859. // load inspector using require, if it doesn't exist on the global namespace.
  76860. }
  76861. /** Creates the inspector window. */
  76862. DebugLayer.prototype._createInspector = function (config) {
  76863. if (config === void 0) { config = {}; }
  76864. var popup = config.popup || false;
  76865. var initialTab = config.initialTab || 0;
  76866. var parentElement = config.parentElement || null;
  76867. if (!this._inspector) {
  76868. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76869. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  76870. } // else nothing to do,; instance is already existing
  76871. };
  76872. DebugLayer.prototype.isVisible = function () {
  76873. if (!this._inspector) {
  76874. return false;
  76875. }
  76876. return true;
  76877. };
  76878. DebugLayer.prototype.hide = function () {
  76879. if (this._inspector) {
  76880. try {
  76881. this._inspector.dispose();
  76882. }
  76883. catch (e) {
  76884. // If the inspector has been removed directly from the inspector tool
  76885. }
  76886. this._inspector = null;
  76887. }
  76888. };
  76889. DebugLayer.prototype.show = function (config) {
  76890. if (config === void 0) { config = {}; }
  76891. if (typeof this.BJSINSPECTOR == 'undefined') {
  76892. // Load inspector and add it to the DOM
  76893. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  76894. }
  76895. else {
  76896. // Otherwise creates the inspector
  76897. this._createInspector(config);
  76898. }
  76899. };
  76900. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  76901. return DebugLayer;
  76902. }());
  76903. BABYLON.DebugLayer = DebugLayer;
  76904. })(BABYLON || (BABYLON = {}));
  76905. //# sourceMappingURL=babylon.debugLayer.js.map
  76906. var BABYLON;
  76907. (function (BABYLON) {
  76908. var BoundingBoxRenderer = /** @class */ (function () {
  76909. function BoundingBoxRenderer(scene) {
  76910. this.frontColor = new BABYLON.Color3(1, 1, 1);
  76911. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  76912. this.showBackLines = true;
  76913. this.renderList = new BABYLON.SmartArray(32);
  76914. this._vertexBuffers = {};
  76915. this._scene = scene;
  76916. }
  76917. BoundingBoxRenderer.prototype._prepareRessources = function () {
  76918. if (this._colorShader) {
  76919. return;
  76920. }
  76921. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  76922. attributes: [BABYLON.VertexBuffer.PositionKind],
  76923. uniforms: ["world", "viewProjection", "color"]
  76924. });
  76925. var engine = this._scene.getEngine();
  76926. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  76927. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  76928. this._createIndexBuffer();
  76929. };
  76930. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  76931. var engine = this._scene.getEngine();
  76932. 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]);
  76933. };
  76934. BoundingBoxRenderer.prototype._rebuild = function () {
  76935. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76936. if (vb) {
  76937. vb._rebuild();
  76938. }
  76939. this._createIndexBuffer();
  76940. };
  76941. BoundingBoxRenderer.prototype.reset = function () {
  76942. this.renderList.reset();
  76943. };
  76944. BoundingBoxRenderer.prototype.render = function () {
  76945. if (this.renderList.length === 0) {
  76946. return;
  76947. }
  76948. this._prepareRessources();
  76949. if (!this._colorShader.isReady()) {
  76950. return;
  76951. }
  76952. var engine = this._scene.getEngine();
  76953. engine.setDepthWrite(false);
  76954. this._colorShader._preBind();
  76955. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  76956. var boundingBox = this.renderList.data[boundingBoxIndex];
  76957. var min = boundingBox.minimum;
  76958. var max = boundingBox.maximum;
  76959. var diff = max.subtract(min);
  76960. var median = min.add(diff.scale(0.5));
  76961. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  76962. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  76963. .multiply(boundingBox.getWorldMatrix());
  76964. // VBOs
  76965. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  76966. if (this.showBackLines) {
  76967. // Back
  76968. engine.setDepthFunctionToGreaterOrEqual();
  76969. this._scene.resetCachedMaterial();
  76970. this._colorShader.setColor4("color", this.backColor.toColor4());
  76971. this._colorShader.bind(worldMatrix);
  76972. // Draw order
  76973. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76974. }
  76975. // Front
  76976. engine.setDepthFunctionToLess();
  76977. this._scene.resetCachedMaterial();
  76978. this._colorShader.setColor4("color", this.frontColor.toColor4());
  76979. this._colorShader.bind(worldMatrix);
  76980. // Draw order
  76981. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76982. }
  76983. this._colorShader.unbind();
  76984. engine.setDepthFunctionToLessOrEqual();
  76985. engine.setDepthWrite(true);
  76986. };
  76987. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  76988. this._prepareRessources();
  76989. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  76990. return;
  76991. }
  76992. var engine = this._scene.getEngine();
  76993. engine.setDepthWrite(false);
  76994. engine.setColorWrite(false);
  76995. this._colorShader._preBind();
  76996. var boundingBox = mesh._boundingInfo.boundingBox;
  76997. var min = boundingBox.minimum;
  76998. var max = boundingBox.maximum;
  76999. var diff = max.subtract(min);
  77000. var median = min.add(diff.scale(0.5));
  77001. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  77002. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  77003. .multiply(boundingBox.getWorldMatrix());
  77004. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  77005. engine.setDepthFunctionToLess();
  77006. this._scene.resetCachedMaterial();
  77007. this._colorShader.bind(worldMatrix);
  77008. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77009. this._colorShader.unbind();
  77010. engine.setDepthFunctionToLessOrEqual();
  77011. engine.setDepthWrite(true);
  77012. engine.setColorWrite(true);
  77013. };
  77014. BoundingBoxRenderer.prototype.dispose = function () {
  77015. if (!this._colorShader) {
  77016. return;
  77017. }
  77018. this.renderList.dispose();
  77019. this._colorShader.dispose();
  77020. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77021. if (buffer) {
  77022. buffer.dispose();
  77023. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77024. }
  77025. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77026. };
  77027. return BoundingBoxRenderer;
  77028. }());
  77029. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  77030. })(BABYLON || (BABYLON = {}));
  77031. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  77032. var BABYLON;
  77033. (function (BABYLON) {
  77034. var MorphTarget = /** @class */ (function () {
  77035. function MorphTarget(name, influence) {
  77036. if (influence === void 0) { influence = 0; }
  77037. this.name = name;
  77038. this.animations = new Array();
  77039. this._positions = null;
  77040. this._normals = null;
  77041. this._tangents = null;
  77042. this.onInfluenceChanged = new BABYLON.Observable();
  77043. this.influence = influence;
  77044. }
  77045. Object.defineProperty(MorphTarget.prototype, "influence", {
  77046. get: function () {
  77047. return this._influence;
  77048. },
  77049. set: function (influence) {
  77050. if (this._influence === influence) {
  77051. return;
  77052. }
  77053. var previous = this._influence;
  77054. this._influence = influence;
  77055. if (this.onInfluenceChanged.hasObservers) {
  77056. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  77057. }
  77058. },
  77059. enumerable: true,
  77060. configurable: true
  77061. });
  77062. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  77063. get: function () {
  77064. return !!this._positions;
  77065. },
  77066. enumerable: true,
  77067. configurable: true
  77068. });
  77069. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  77070. get: function () {
  77071. return !!this._normals;
  77072. },
  77073. enumerable: true,
  77074. configurable: true
  77075. });
  77076. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  77077. get: function () {
  77078. return !!this._tangents;
  77079. },
  77080. enumerable: true,
  77081. configurable: true
  77082. });
  77083. MorphTarget.prototype.setPositions = function (data) {
  77084. this._positions = data;
  77085. };
  77086. MorphTarget.prototype.getPositions = function () {
  77087. return this._positions;
  77088. };
  77089. MorphTarget.prototype.setNormals = function (data) {
  77090. this._normals = data;
  77091. };
  77092. MorphTarget.prototype.getNormals = function () {
  77093. return this._normals;
  77094. };
  77095. MorphTarget.prototype.setTangents = function (data) {
  77096. this._tangents = data;
  77097. };
  77098. MorphTarget.prototype.getTangents = function () {
  77099. return this._tangents;
  77100. };
  77101. /**
  77102. * Serializes the current target into a Serialization object.
  77103. * Returns the serialized object.
  77104. */
  77105. MorphTarget.prototype.serialize = function () {
  77106. var serializationObject = {};
  77107. serializationObject.name = this.name;
  77108. serializationObject.influence = this.influence;
  77109. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  77110. if (this.hasNormals) {
  77111. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  77112. }
  77113. if (this.hasTangents) {
  77114. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  77115. }
  77116. // Animations
  77117. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  77118. return serializationObject;
  77119. };
  77120. // Statics
  77121. MorphTarget.Parse = function (serializationObject) {
  77122. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  77123. result.setPositions(serializationObject.positions);
  77124. if (serializationObject.normals) {
  77125. result.setNormals(serializationObject.normals);
  77126. }
  77127. if (serializationObject.tangents) {
  77128. result.setTangents(serializationObject.tangents);
  77129. }
  77130. // Animations
  77131. if (serializationObject.animations) {
  77132. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  77133. var parsedAnimation = serializationObject.animations[animationIndex];
  77134. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  77135. }
  77136. }
  77137. return result;
  77138. };
  77139. MorphTarget.FromMesh = function (mesh, name, influence) {
  77140. if (!name) {
  77141. name = mesh.name;
  77142. }
  77143. var result = new MorphTarget(name, influence);
  77144. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77145. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  77146. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  77147. }
  77148. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  77149. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  77150. }
  77151. return result;
  77152. };
  77153. return MorphTarget;
  77154. }());
  77155. BABYLON.MorphTarget = MorphTarget;
  77156. })(BABYLON || (BABYLON = {}));
  77157. //# sourceMappingURL=babylon.morphTarget.js.map
  77158. var BABYLON;
  77159. (function (BABYLON) {
  77160. var MorphTargetManager = /** @class */ (function () {
  77161. function MorphTargetManager(scene) {
  77162. if (scene === void 0) { scene = null; }
  77163. this._targets = new Array();
  77164. this._targetObservable = new Array();
  77165. this._activeTargets = new BABYLON.SmartArray(16);
  77166. this._supportsNormals = false;
  77167. this._supportsTangents = false;
  77168. this._vertexCount = 0;
  77169. this._uniqueId = 0;
  77170. this._tempInfluences = new Array();
  77171. if (!scene) {
  77172. scene = BABYLON.Engine.LastCreatedScene;
  77173. }
  77174. this._scene = scene;
  77175. if (this._scene) {
  77176. this._scene.morphTargetManagers.push(this);
  77177. this._uniqueId = this._scene.getUniqueId();
  77178. }
  77179. }
  77180. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  77181. get: function () {
  77182. return this._uniqueId;
  77183. },
  77184. enumerable: true,
  77185. configurable: true
  77186. });
  77187. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  77188. get: function () {
  77189. return this._vertexCount;
  77190. },
  77191. enumerable: true,
  77192. configurable: true
  77193. });
  77194. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  77195. get: function () {
  77196. return this._supportsNormals;
  77197. },
  77198. enumerable: true,
  77199. configurable: true
  77200. });
  77201. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  77202. get: function () {
  77203. return this._supportsTangents;
  77204. },
  77205. enumerable: true,
  77206. configurable: true
  77207. });
  77208. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  77209. get: function () {
  77210. return this._targets.length;
  77211. },
  77212. enumerable: true,
  77213. configurable: true
  77214. });
  77215. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  77216. get: function () {
  77217. return this._activeTargets.length;
  77218. },
  77219. enumerable: true,
  77220. configurable: true
  77221. });
  77222. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  77223. get: function () {
  77224. return this._influences;
  77225. },
  77226. enumerable: true,
  77227. configurable: true
  77228. });
  77229. MorphTargetManager.prototype.getActiveTarget = function (index) {
  77230. return this._activeTargets.data[index];
  77231. };
  77232. MorphTargetManager.prototype.getTarget = function (index) {
  77233. return this._targets[index];
  77234. };
  77235. MorphTargetManager.prototype.addTarget = function (target) {
  77236. var _this = this;
  77237. this._targets.push(target);
  77238. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  77239. _this._syncActiveTargets(needUpdate);
  77240. }));
  77241. this._syncActiveTargets(true);
  77242. };
  77243. MorphTargetManager.prototype.removeTarget = function (target) {
  77244. var index = this._targets.indexOf(target);
  77245. if (index >= 0) {
  77246. this._targets.splice(index, 1);
  77247. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  77248. this._syncActiveTargets(true);
  77249. }
  77250. };
  77251. /**
  77252. * Serializes the current manager into a Serialization object.
  77253. * Returns the serialized object.
  77254. */
  77255. MorphTargetManager.prototype.serialize = function () {
  77256. var serializationObject = {};
  77257. serializationObject.id = this.uniqueId;
  77258. serializationObject.targets = [];
  77259. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77260. var target = _a[_i];
  77261. serializationObject.targets.push(target.serialize());
  77262. }
  77263. return serializationObject;
  77264. };
  77265. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  77266. var influenceCount = 0;
  77267. this._activeTargets.reset();
  77268. this._supportsNormals = true;
  77269. this._supportsTangents = true;
  77270. this._vertexCount = 0;
  77271. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77272. var target = _a[_i];
  77273. this._activeTargets.push(target);
  77274. this._tempInfluences[influenceCount++] = target.influence;
  77275. var positions = target.getPositions();
  77276. if (positions) {
  77277. this._supportsNormals = this._supportsNormals && target.hasNormals;
  77278. this._supportsTangents = this._supportsTangents && target.hasTangents;
  77279. var vertexCount = positions.length / 3;
  77280. if (this._vertexCount === 0) {
  77281. this._vertexCount = vertexCount;
  77282. }
  77283. else if (this._vertexCount !== vertexCount) {
  77284. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  77285. return;
  77286. }
  77287. }
  77288. }
  77289. if (!this._influences || this._influences.length !== influenceCount) {
  77290. this._influences = new Float32Array(influenceCount);
  77291. }
  77292. for (var index = 0; index < influenceCount; index++) {
  77293. this._influences[index] = this._tempInfluences[index];
  77294. }
  77295. if (needUpdate && this._scene) {
  77296. // Flag meshes as dirty to resync with the active targets
  77297. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  77298. var mesh = _c[_b];
  77299. if (mesh.morphTargetManager === this) {
  77300. mesh._syncGeometryWithMorphTargetManager();
  77301. }
  77302. }
  77303. }
  77304. };
  77305. // Statics
  77306. MorphTargetManager.Parse = function (serializationObject, scene) {
  77307. var result = new MorphTargetManager(scene);
  77308. result._uniqueId = serializationObject.id;
  77309. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  77310. var targetData = _a[_i];
  77311. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  77312. }
  77313. return result;
  77314. };
  77315. return MorphTargetManager;
  77316. }());
  77317. BABYLON.MorphTargetManager = MorphTargetManager;
  77318. })(BABYLON || (BABYLON = {}));
  77319. //# sourceMappingURL=babylon.morphTargetManager.js.map
  77320. var BABYLON;
  77321. (function (BABYLON) {
  77322. var Octree = /** @class */ (function () {
  77323. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  77324. if (maxDepth === void 0) { maxDepth = 2; }
  77325. this.maxDepth = maxDepth;
  77326. this.dynamicContent = new Array();
  77327. this._maxBlockCapacity = maxBlockCapacity || 64;
  77328. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  77329. this._creationFunc = creationFunc;
  77330. }
  77331. // Methods
  77332. Octree.prototype.update = function (worldMin, worldMax, entries) {
  77333. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  77334. };
  77335. Octree.prototype.addMesh = function (entry) {
  77336. for (var index = 0; index < this.blocks.length; index++) {
  77337. var block = this.blocks[index];
  77338. block.addEntry(entry);
  77339. }
  77340. };
  77341. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  77342. this._selectionContent.reset();
  77343. for (var index = 0; index < this.blocks.length; index++) {
  77344. var block = this.blocks[index];
  77345. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  77346. }
  77347. if (allowDuplicate) {
  77348. this._selectionContent.concat(this.dynamicContent);
  77349. }
  77350. else {
  77351. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77352. }
  77353. return this._selectionContent;
  77354. };
  77355. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  77356. this._selectionContent.reset();
  77357. for (var index = 0; index < this.blocks.length; index++) {
  77358. var block = this.blocks[index];
  77359. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  77360. }
  77361. if (allowDuplicate) {
  77362. this._selectionContent.concat(this.dynamicContent);
  77363. }
  77364. else {
  77365. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77366. }
  77367. return this._selectionContent;
  77368. };
  77369. Octree.prototype.intersectsRay = function (ray) {
  77370. this._selectionContent.reset();
  77371. for (var index = 0; index < this.blocks.length; index++) {
  77372. var block = this.blocks[index];
  77373. block.intersectsRay(ray, this._selectionContent);
  77374. }
  77375. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77376. return this._selectionContent;
  77377. };
  77378. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  77379. target.blocks = new Array();
  77380. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  77381. // Segmenting space
  77382. for (var x = 0; x < 2; x++) {
  77383. for (var y = 0; y < 2; y++) {
  77384. for (var z = 0; z < 2; z++) {
  77385. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  77386. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  77387. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  77388. block.addEntries(entries);
  77389. target.blocks.push(block);
  77390. }
  77391. }
  77392. }
  77393. };
  77394. Octree.CreationFuncForMeshes = function (entry, block) {
  77395. var boundingInfo = entry.getBoundingInfo();
  77396. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77397. block.entries.push(entry);
  77398. }
  77399. };
  77400. Octree.CreationFuncForSubMeshes = function (entry, block) {
  77401. var boundingInfo = entry.getBoundingInfo();
  77402. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77403. block.entries.push(entry);
  77404. }
  77405. };
  77406. return Octree;
  77407. }());
  77408. BABYLON.Octree = Octree;
  77409. })(BABYLON || (BABYLON = {}));
  77410. //# sourceMappingURL=babylon.octree.js.map
  77411. var BABYLON;
  77412. (function (BABYLON) {
  77413. var OctreeBlock = /** @class */ (function () {
  77414. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  77415. this.entries = new Array();
  77416. this._boundingVectors = new Array();
  77417. this._capacity = capacity;
  77418. this._depth = depth;
  77419. this._maxDepth = maxDepth;
  77420. this._creationFunc = creationFunc;
  77421. this._minPoint = minPoint;
  77422. this._maxPoint = maxPoint;
  77423. this._boundingVectors.push(minPoint.clone());
  77424. this._boundingVectors.push(maxPoint.clone());
  77425. this._boundingVectors.push(minPoint.clone());
  77426. this._boundingVectors[2].x = maxPoint.x;
  77427. this._boundingVectors.push(minPoint.clone());
  77428. this._boundingVectors[3].y = maxPoint.y;
  77429. this._boundingVectors.push(minPoint.clone());
  77430. this._boundingVectors[4].z = maxPoint.z;
  77431. this._boundingVectors.push(maxPoint.clone());
  77432. this._boundingVectors[5].z = minPoint.z;
  77433. this._boundingVectors.push(maxPoint.clone());
  77434. this._boundingVectors[6].x = minPoint.x;
  77435. this._boundingVectors.push(maxPoint.clone());
  77436. this._boundingVectors[7].y = minPoint.y;
  77437. }
  77438. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  77439. // Property
  77440. get: function () {
  77441. return this._capacity;
  77442. },
  77443. enumerable: true,
  77444. configurable: true
  77445. });
  77446. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  77447. get: function () {
  77448. return this._minPoint;
  77449. },
  77450. enumerable: true,
  77451. configurable: true
  77452. });
  77453. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  77454. get: function () {
  77455. return this._maxPoint;
  77456. },
  77457. enumerable: true,
  77458. configurable: true
  77459. });
  77460. // Methods
  77461. OctreeBlock.prototype.addEntry = function (entry) {
  77462. if (this.blocks) {
  77463. for (var index = 0; index < this.blocks.length; index++) {
  77464. var block = this.blocks[index];
  77465. block.addEntry(entry);
  77466. }
  77467. return;
  77468. }
  77469. this._creationFunc(entry, this);
  77470. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  77471. this.createInnerBlocks();
  77472. }
  77473. };
  77474. OctreeBlock.prototype.addEntries = function (entries) {
  77475. for (var index = 0; index < entries.length; index++) {
  77476. var mesh = entries[index];
  77477. this.addEntry(mesh);
  77478. }
  77479. };
  77480. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  77481. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  77482. if (this.blocks) {
  77483. for (var index = 0; index < this.blocks.length; index++) {
  77484. var block = this.blocks[index];
  77485. block.select(frustumPlanes, selection, allowDuplicate);
  77486. }
  77487. return;
  77488. }
  77489. if (allowDuplicate) {
  77490. selection.concat(this.entries);
  77491. }
  77492. else {
  77493. selection.concatWithNoDuplicate(this.entries);
  77494. }
  77495. }
  77496. };
  77497. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  77498. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  77499. if (this.blocks) {
  77500. for (var index = 0; index < this.blocks.length; index++) {
  77501. var block = this.blocks[index];
  77502. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  77503. }
  77504. return;
  77505. }
  77506. if (allowDuplicate) {
  77507. selection.concat(this.entries);
  77508. }
  77509. else {
  77510. selection.concatWithNoDuplicate(this.entries);
  77511. }
  77512. }
  77513. };
  77514. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  77515. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  77516. if (this.blocks) {
  77517. for (var index = 0; index < this.blocks.length; index++) {
  77518. var block = this.blocks[index];
  77519. block.intersectsRay(ray, selection);
  77520. }
  77521. return;
  77522. }
  77523. selection.concatWithNoDuplicate(this.entries);
  77524. }
  77525. };
  77526. OctreeBlock.prototype.createInnerBlocks = function () {
  77527. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  77528. };
  77529. return OctreeBlock;
  77530. }());
  77531. BABYLON.OctreeBlock = OctreeBlock;
  77532. })(BABYLON || (BABYLON = {}));
  77533. //# sourceMappingURL=babylon.octreeBlock.js.map
  77534. var BABYLON;
  77535. (function (BABYLON) {
  77536. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  77537. __extends(VRDistortionCorrectionPostProcess, _super);
  77538. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  77539. var _this = _super.call(this, name, "vrDistortionCorrection", [
  77540. 'LensCenter',
  77541. 'Scale',
  77542. 'ScaleIn',
  77543. 'HmdWarpParam'
  77544. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  77545. _this._isRightEye = isRightEye;
  77546. _this._distortionFactors = vrMetrics.distortionK;
  77547. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  77548. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  77549. _this.adaptScaleToCurrentViewport = true;
  77550. _this.onSizeChangedObservable.add(function () {
  77551. _this.aspectRatio = _this.width * .5 / _this.height;
  77552. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  77553. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  77554. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  77555. });
  77556. _this.onApplyObservable.add(function (effect) {
  77557. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  77558. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  77559. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  77560. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  77561. });
  77562. return _this;
  77563. }
  77564. return VRDistortionCorrectionPostProcess;
  77565. }(BABYLON.PostProcess));
  77566. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  77567. })(BABYLON || (BABYLON = {}));
  77568. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  77569. var BABYLON;
  77570. (function (BABYLON) {
  77571. var AnaglyphPostProcess = /** @class */ (function (_super) {
  77572. __extends(AnaglyphPostProcess, _super);
  77573. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  77574. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  77575. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77576. _this.onApplyObservable.add(function (effect) {
  77577. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  77578. });
  77579. return _this;
  77580. }
  77581. return AnaglyphPostProcess;
  77582. }(BABYLON.PostProcess));
  77583. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  77584. })(BABYLON || (BABYLON = {}));
  77585. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  77586. var BABYLON;
  77587. (function (BABYLON) {
  77588. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  77589. __extends(StereoscopicInterlacePostProcess, _super);
  77590. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  77591. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  77592. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77593. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77594. _this.onSizeChangedObservable.add(function () {
  77595. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77596. });
  77597. _this.onApplyObservable.add(function (effect) {
  77598. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  77599. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  77600. });
  77601. return _this;
  77602. }
  77603. return StereoscopicInterlacePostProcess;
  77604. }(BABYLON.PostProcess));
  77605. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  77606. })(BABYLON || (BABYLON = {}));
  77607. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  77608. var BABYLON;
  77609. (function (BABYLON) {
  77610. /**
  77611. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  77612. * Screen rotation is taken into account.
  77613. */
  77614. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  77615. function FreeCameraDeviceOrientationInput() {
  77616. var _this = this;
  77617. this._screenOrientationAngle = 0;
  77618. this._screenQuaternion = new BABYLON.Quaternion();
  77619. this._alpha = 0;
  77620. this._beta = 0;
  77621. this._gamma = 0;
  77622. this._orientationChanged = function () {
  77623. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  77624. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  77625. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  77626. };
  77627. this._deviceOrientation = function (evt) {
  77628. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  77629. _this._beta = evt.beta !== null ? evt.beta : 0;
  77630. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  77631. };
  77632. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  77633. this._orientationChanged();
  77634. }
  77635. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  77636. get: function () {
  77637. return this._camera;
  77638. },
  77639. set: function (camera) {
  77640. this._camera = camera;
  77641. if (this._camera != null && !this._camera.rotationQuaternion) {
  77642. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  77643. }
  77644. },
  77645. enumerable: true,
  77646. configurable: true
  77647. });
  77648. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77649. window.addEventListener("orientationchange", this._orientationChanged);
  77650. window.addEventListener("deviceorientation", this._deviceOrientation);
  77651. //In certain cases, the attach control is called AFTER orientation was changed,
  77652. //So this is needed.
  77653. this._orientationChanged();
  77654. };
  77655. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  77656. window.removeEventListener("orientationchange", this._orientationChanged);
  77657. window.removeEventListener("deviceorientation", this._deviceOrientation);
  77658. };
  77659. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  77660. //if no device orientation provided, don't update the rotation.
  77661. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  77662. if (!this._alpha)
  77663. return;
  77664. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  77665. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  77666. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  77667. //Mirror on XY Plane
  77668. this._camera.rotationQuaternion.z *= -1;
  77669. this._camera.rotationQuaternion.w *= -1;
  77670. };
  77671. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  77672. return "FreeCameraDeviceOrientationInput";
  77673. };
  77674. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  77675. return "deviceOrientation";
  77676. };
  77677. return FreeCameraDeviceOrientationInput;
  77678. }());
  77679. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  77680. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  77681. })(BABYLON || (BABYLON = {}));
  77682. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  77683. var BABYLON;
  77684. (function (BABYLON) {
  77685. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  77686. function ArcRotateCameraVRDeviceOrientationInput() {
  77687. this.alphaCorrection = 1;
  77688. this.betaCorrection = 1;
  77689. this.gammaCorrection = 1;
  77690. this._alpha = 0;
  77691. this._gamma = 0;
  77692. this._dirty = false;
  77693. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  77694. }
  77695. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77696. this.camera.attachControl(element, noPreventDefault);
  77697. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  77698. };
  77699. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  77700. if (evt.alpha !== null) {
  77701. this._alpha = +evt.alpha | 0;
  77702. }
  77703. if (evt.gamma !== null) {
  77704. this._gamma = +evt.gamma | 0;
  77705. }
  77706. this._dirty = true;
  77707. };
  77708. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  77709. if (this._dirty) {
  77710. this._dirty = false;
  77711. if (this._gamma < 0) {
  77712. this._gamma = 180 + this._gamma;
  77713. }
  77714. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  77715. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  77716. }
  77717. };
  77718. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  77719. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  77720. };
  77721. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  77722. return "ArcRotateCameraVRDeviceOrientationInput";
  77723. };
  77724. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  77725. return "VRDeviceOrientation";
  77726. };
  77727. return ArcRotateCameraVRDeviceOrientationInput;
  77728. }());
  77729. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  77730. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  77731. })(BABYLON || (BABYLON = {}));
  77732. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  77733. var BABYLON;
  77734. (function (BABYLON) {
  77735. var VRCameraMetrics = /** @class */ (function () {
  77736. function VRCameraMetrics() {
  77737. this.compensateDistortion = true;
  77738. }
  77739. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  77740. get: function () {
  77741. return this.hResolution / (2 * this.vResolution);
  77742. },
  77743. enumerable: true,
  77744. configurable: true
  77745. });
  77746. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  77747. get: function () {
  77748. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  77749. },
  77750. enumerable: true,
  77751. configurable: true
  77752. });
  77753. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  77754. get: function () {
  77755. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77756. var h = (4 * meters) / this.hScreenSize;
  77757. return BABYLON.Matrix.Translation(h, 0, 0);
  77758. },
  77759. enumerable: true,
  77760. configurable: true
  77761. });
  77762. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  77763. get: function () {
  77764. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77765. var h = (4 * meters) / this.hScreenSize;
  77766. return BABYLON.Matrix.Translation(-h, 0, 0);
  77767. },
  77768. enumerable: true,
  77769. configurable: true
  77770. });
  77771. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  77772. get: function () {
  77773. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  77774. },
  77775. enumerable: true,
  77776. configurable: true
  77777. });
  77778. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  77779. get: function () {
  77780. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  77781. },
  77782. enumerable: true,
  77783. configurable: true
  77784. });
  77785. VRCameraMetrics.GetDefault = function () {
  77786. var result = new VRCameraMetrics();
  77787. result.hResolution = 1280;
  77788. result.vResolution = 800;
  77789. result.hScreenSize = 0.149759993;
  77790. result.vScreenSize = 0.0935999975;
  77791. result.vScreenCenter = 0.0467999987;
  77792. result.eyeToScreenDistance = 0.0410000011;
  77793. result.lensSeparationDistance = 0.0635000020;
  77794. result.interpupillaryDistance = 0.0640000030;
  77795. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  77796. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  77797. result.postProcessScaleFactor = 1.714605507808412;
  77798. result.lensCenterOffset = 0.151976421;
  77799. return result;
  77800. };
  77801. return VRCameraMetrics;
  77802. }());
  77803. BABYLON.VRCameraMetrics = VRCameraMetrics;
  77804. })(BABYLON || (BABYLON = {}));
  77805. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  77806. var BABYLON;
  77807. (function (BABYLON) {
  77808. /**
  77809. * This represents a WebVR camera.
  77810. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  77811. * @example http://doc.babylonjs.com/how_to/webvr_camera
  77812. */
  77813. var WebVRFreeCamera = /** @class */ (function (_super) {
  77814. __extends(WebVRFreeCamera, _super);
  77815. /**
  77816. * Instantiates a WebVRFreeCamera.
  77817. * @param name The name of the WebVRFreeCamera
  77818. * @param position The starting anchor position for the camera
  77819. * @param scene The scene the camera belongs to
  77820. * @param webVROptions a set of customizable options for the webVRCamera
  77821. */
  77822. function WebVRFreeCamera(name, position, scene, webVROptions) {
  77823. if (webVROptions === void 0) { webVROptions = {}; }
  77824. var _this = _super.call(this, name, position, scene) || this;
  77825. _this.webVROptions = webVROptions;
  77826. /**
  77827. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  77828. */
  77829. _this._vrDevice = null;
  77830. /**
  77831. * The rawPose of the vrDevice.
  77832. */
  77833. _this.rawPose = null;
  77834. _this._specsVersion = "1.1";
  77835. _this._attached = false;
  77836. _this._descendants = [];
  77837. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  77838. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  77839. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  77840. _this._standingMatrix = null;
  77841. /**
  77842. * Represents device position in babylon space.
  77843. */
  77844. _this.devicePosition = BABYLON.Vector3.Zero();
  77845. /**
  77846. * Represents device rotation in babylon space.
  77847. */
  77848. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  77849. /**
  77850. * The scale of the device to be used when translating from device space to babylon space.
  77851. */
  77852. _this.deviceScaleFactor = 1;
  77853. _this._deviceToWorld = BABYLON.Matrix.Identity();
  77854. _this._worldToDevice = BABYLON.Matrix.Identity();
  77855. /**
  77856. * References to the webVR controllers for the vrDevice.
  77857. */
  77858. _this.controllers = [];
  77859. /**
  77860. * Emits an event when a controller is attached.
  77861. */
  77862. _this.onControllersAttachedObservable = new BABYLON.Observable();
  77863. /**
  77864. * Emits an event when a controller's mesh has been loaded;
  77865. */
  77866. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  77867. /**
  77868. * If the rig cameras be used as parent instead of this camera.
  77869. */
  77870. _this.rigParenting = true;
  77871. _this._defaultHeight = undefined;
  77872. _this._workingVector = BABYLON.Vector3.Zero();
  77873. _this._oneVector = BABYLON.Vector3.One();
  77874. _this._workingMatrix = BABYLON.Matrix.Identity();
  77875. _this._cache.position = BABYLON.Vector3.Zero();
  77876. if (webVROptions.defaultHeight) {
  77877. _this._defaultHeight = webVROptions.defaultHeight;
  77878. _this.position.y = _this._defaultHeight;
  77879. }
  77880. _this.minZ = 0.1;
  77881. //legacy support - the compensation boolean was removed.
  77882. if (arguments.length === 5) {
  77883. _this.webVROptions = arguments[4];
  77884. }
  77885. // default webVR options
  77886. if (_this.webVROptions.trackPosition == undefined) {
  77887. _this.webVROptions.trackPosition = true;
  77888. }
  77889. if (_this.webVROptions.controllerMeshes == undefined) {
  77890. _this.webVROptions.controllerMeshes = true;
  77891. }
  77892. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  77893. _this.webVROptions.defaultLightingOnControllers = true;
  77894. }
  77895. _this.rotationQuaternion = new BABYLON.Quaternion();
  77896. if (_this.webVROptions && _this.webVROptions.positionScale) {
  77897. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  77898. }
  77899. //enable VR
  77900. var engine = _this.getEngine();
  77901. _this._onVREnabled = function (success) { if (success) {
  77902. _this.initControllers();
  77903. } };
  77904. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  77905. engine.initWebVR().add(function (event) {
  77906. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  77907. return;
  77908. }
  77909. _this._vrDevice = event.vrDisplay;
  77910. //reset the rig parameters.
  77911. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  77912. if (_this._attached) {
  77913. _this.getEngine().enableVR();
  77914. }
  77915. });
  77916. if (typeof (VRFrameData) !== "undefined")
  77917. _this._frameData = new VRFrameData();
  77918. /**
  77919. * The idea behind the following lines:
  77920. * objects that have the camera as parent should actually have the rig cameras as a parent.
  77921. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  77922. * the second will not show it correctly.
  77923. *
  77924. * To solve this - each object that has the camera as parent will be added to a protected array.
  77925. * When the rig camera renders, it will take this array and set all of those to be its children.
  77926. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  77927. * Amazing!
  77928. */
  77929. scene.onBeforeCameraRenderObservable.add(function (camera) {
  77930. if (camera.parent === _this && _this.rigParenting) {
  77931. _this._descendants = _this.getDescendants(true, function (n) {
  77932. // don't take the cameras or the controllers!
  77933. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  77934. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  77935. return !isController && !isRigCamera;
  77936. });
  77937. _this._descendants.forEach(function (node) {
  77938. node.parent = camera;
  77939. });
  77940. }
  77941. });
  77942. scene.onAfterCameraRenderObservable.add(function (camera) {
  77943. if (camera.parent === _this && _this.rigParenting) {
  77944. _this._descendants.forEach(function (node) {
  77945. node.parent = _this;
  77946. });
  77947. }
  77948. });
  77949. return _this;
  77950. }
  77951. /**
  77952. * Gets the device distance from the ground.
  77953. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  77954. */
  77955. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  77956. if (this._standingMatrix && this._defaultHeight === undefined) {
  77957. // Add standing matrix offset to get real offset from ground in room
  77958. this._standingMatrix.getTranslationToRef(this._workingVector);
  77959. return this._deviceRoomPosition.y + this._workingVector.y;
  77960. }
  77961. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  77962. return this._defaultHeight || 0;
  77963. };
  77964. /**
  77965. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  77966. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  77967. */
  77968. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  77969. var _this = this;
  77970. if (callback === void 0) { callback = function (bool) { }; }
  77971. // Use standing matrix if available
  77972. if (!navigator || !navigator.getVRDisplays) {
  77973. callback(false);
  77974. }
  77975. else {
  77976. navigator.getVRDisplays().then(function (displays) {
  77977. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  77978. callback(false);
  77979. }
  77980. else {
  77981. _this._standingMatrix = new BABYLON.Matrix();
  77982. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  77983. if (!_this.getScene().useRightHandedSystem) {
  77984. [2, 6, 8, 9, 14].forEach(function (num) {
  77985. if (_this._standingMatrix) {
  77986. _this._standingMatrix.m[num] *= -1;
  77987. }
  77988. });
  77989. }
  77990. callback(true);
  77991. }
  77992. });
  77993. }
  77994. };
  77995. /**
  77996. * Disposes the camera
  77997. */
  77998. WebVRFreeCamera.prototype.dispose = function () {
  77999. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  78000. _super.prototype.dispose.call(this);
  78001. };
  78002. /**
  78003. * Gets a vrController by name.
  78004. * @param name The name of the controller to retreive
  78005. * @returns the controller matching the name specified or null if not found
  78006. */
  78007. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  78008. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  78009. var gp = _a[_i];
  78010. if (gp.hand === name) {
  78011. return gp;
  78012. }
  78013. }
  78014. return null;
  78015. };
  78016. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  78017. /**
  78018. * The controller corrisponding to the users left hand.
  78019. */
  78020. get: function () {
  78021. if (!this._leftController) {
  78022. this._leftController = this.getControllerByName("left");
  78023. }
  78024. return this._leftController;
  78025. },
  78026. enumerable: true,
  78027. configurable: true
  78028. });
  78029. ;
  78030. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  78031. /**
  78032. * The controller corrisponding to the users right hand.
  78033. */
  78034. get: function () {
  78035. if (!this._rightController) {
  78036. this._rightController = this.getControllerByName("right");
  78037. }
  78038. return this._rightController;
  78039. },
  78040. enumerable: true,
  78041. configurable: true
  78042. });
  78043. ;
  78044. /**
  78045. * Casts a ray forward from the vrCamera's gaze.
  78046. * @param length Length of the ray (default: 100)
  78047. * @returns the ray corrisponding to the gaze
  78048. */
  78049. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  78050. if (length === void 0) { length = 100; }
  78051. if (this.leftCamera) {
  78052. // Use left eye to avoid computation to compute center on every call
  78053. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  78054. }
  78055. else {
  78056. return _super.prototype.getForwardRay.call(this, length);
  78057. }
  78058. };
  78059. /**
  78060. * Updates the camera based on device's frame data
  78061. */
  78062. WebVRFreeCamera.prototype._checkInputs = function () {
  78063. if (this._vrDevice && this._vrDevice.isPresenting) {
  78064. this._vrDevice.getFrameData(this._frameData);
  78065. this.updateFromDevice(this._frameData.pose);
  78066. }
  78067. _super.prototype._checkInputs.call(this);
  78068. };
  78069. /**
  78070. * Updates the poseControlled values based on the input device pose.
  78071. * @param poseData Pose coming from the device
  78072. */
  78073. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  78074. if (poseData && poseData.orientation) {
  78075. this.rawPose = poseData;
  78076. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  78077. if (this.getScene().useRightHandedSystem) {
  78078. this._deviceRoomRotationQuaternion.z *= -1;
  78079. this._deviceRoomRotationQuaternion.w *= -1;
  78080. }
  78081. if (this.webVROptions.trackPosition && this.rawPose.position) {
  78082. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  78083. if (this.getScene().useRightHandedSystem) {
  78084. this._deviceRoomPosition.z *= -1;
  78085. }
  78086. }
  78087. }
  78088. };
  78089. /**
  78090. * WebVR's attach control will start broadcasting frames to the device.
  78091. * Note that in certain browsers (chrome for example) this function must be called
  78092. * within a user-interaction callback. Example:
  78093. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  78094. *
  78095. * @param element html element to attach the vrDevice to
  78096. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  78097. */
  78098. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  78099. _super.prototype.attachControl.call(this, element, noPreventDefault);
  78100. this._attached = true;
  78101. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  78102. if (this._vrDevice) {
  78103. this.getEngine().enableVR();
  78104. }
  78105. };
  78106. /**
  78107. * Detaches the camera from the html element and disables VR
  78108. *
  78109. * @param element html element to detach from
  78110. */
  78111. WebVRFreeCamera.prototype.detachControl = function (element) {
  78112. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78113. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78114. _super.prototype.detachControl.call(this, element);
  78115. this._attached = false;
  78116. this.getEngine().disableVR();
  78117. };
  78118. /**
  78119. * @returns the name of this class
  78120. */
  78121. WebVRFreeCamera.prototype.getClassName = function () {
  78122. return "WebVRFreeCamera";
  78123. };
  78124. /**
  78125. * Calls resetPose on the vrDisplay
  78126. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  78127. */
  78128. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  78129. //uses the vrDisplay's "resetPose()".
  78130. //pitch and roll won't be affected.
  78131. this._vrDevice.resetPose();
  78132. };
  78133. /**
  78134. * Updates the rig cameras (left and right eye)
  78135. */
  78136. WebVRFreeCamera.prototype._updateRigCameras = function () {
  78137. var camLeft = this._rigCameras[0];
  78138. var camRight = this._rigCameras[1];
  78139. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78140. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78141. camLeft.position.copyFrom(this._deviceRoomPosition);
  78142. camRight.position.copyFrom(this._deviceRoomPosition);
  78143. };
  78144. /**
  78145. * Updates the cached values of the camera
  78146. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  78147. */
  78148. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  78149. var _this = this;
  78150. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  78151. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  78152. if (!this.updateCacheCalled) {
  78153. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  78154. this.updateCacheCalled = true;
  78155. this.update();
  78156. }
  78157. // Set working vector to the device position in room space rotated by the new rotation
  78158. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  78159. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  78160. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  78161. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  78162. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  78163. // Add translation from anchor position
  78164. this._deviceToWorld.getTranslationToRef(this._workingVector);
  78165. this._workingVector.addInPlace(this.position);
  78166. this._workingVector.subtractInPlace(this._cache.position);
  78167. this._deviceToWorld.setTranslation(this._workingVector);
  78168. // Set an inverted matrix to be used when updating the camera
  78169. this._deviceToWorld.invertToRef(this._worldToDevice);
  78170. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  78171. this.controllers.forEach(function (controller) {
  78172. controller._deviceToWorld = _this._deviceToWorld;
  78173. controller.update();
  78174. });
  78175. }
  78176. if (!ignoreParentClass) {
  78177. _super.prototype._updateCache.call(this);
  78178. }
  78179. this.updateCacheCalled = false;
  78180. };
  78181. /**
  78182. * Updates the current device position and rotation in the babylon world
  78183. */
  78184. WebVRFreeCamera.prototype.update = function () {
  78185. // Get current device position in babylon world
  78186. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  78187. // Get current device rotation in babylon world
  78188. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  78189. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  78190. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  78191. _super.prototype.update.call(this);
  78192. };
  78193. /**
  78194. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  78195. * @returns an identity matrix
  78196. */
  78197. WebVRFreeCamera.prototype._getViewMatrix = function () {
  78198. return BABYLON.Matrix.Identity();
  78199. };
  78200. /**
  78201. * This function is called by the two RIG cameras.
  78202. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  78203. */
  78204. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  78205. var _this = this;
  78206. //WebVR 1.1
  78207. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  78208. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  78209. if (!this.getScene().useRightHandedSystem) {
  78210. [2, 6, 8, 9, 14].forEach(function (num) {
  78211. _this._webvrViewMatrix.m[num] *= -1;
  78212. });
  78213. }
  78214. // update the camera rotation matrix
  78215. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  78216. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  78217. // Computing target and final matrix
  78218. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  78219. var parentCamera = this._cameraRigParams["parentCamera"];
  78220. // should the view matrix be updated with scale and position offset?
  78221. if (parentCamera.deviceScaleFactor !== 1) {
  78222. this._webvrViewMatrix.invert();
  78223. // scale the position, if set
  78224. if (parentCamera.deviceScaleFactor) {
  78225. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  78226. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  78227. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  78228. }
  78229. this._webvrViewMatrix.invert();
  78230. }
  78231. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  78232. return this._webvrViewMatrix;
  78233. };
  78234. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  78235. var _this = this;
  78236. var parentCamera = this.parent;
  78237. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  78238. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  78239. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  78240. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  78241. //babylon compatible matrix
  78242. if (!this.getScene().useRightHandedSystem) {
  78243. [8, 9, 10, 11].forEach(function (num) {
  78244. _this._projectionMatrix.m[num] *= -1;
  78245. });
  78246. }
  78247. return this._projectionMatrix;
  78248. };
  78249. /**
  78250. * Initializes the controllers and their meshes
  78251. */
  78252. WebVRFreeCamera.prototype.initControllers = function () {
  78253. var _this = this;
  78254. this.controllers = [];
  78255. var manager = this.getScene().gamepadManager;
  78256. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78257. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78258. var webVrController = gamepad;
  78259. if (webVrController.defaultModel) {
  78260. webVrController.defaultModel.setEnabled(false);
  78261. }
  78262. if (webVrController.hand === "right") {
  78263. _this._rightController = null;
  78264. }
  78265. if (webVrController.hand === "left") {
  78266. _this._rightController = null;
  78267. }
  78268. var controllerIndex = _this.controllers.indexOf(webVrController);
  78269. if (controllerIndex !== -1) {
  78270. _this.controllers.splice(controllerIndex, 1);
  78271. }
  78272. }
  78273. });
  78274. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78275. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78276. var webVrController_1 = gamepad;
  78277. webVrController_1._deviceToWorld = _this._deviceToWorld;
  78278. if (_this.webVROptions.controllerMeshes) {
  78279. if (webVrController_1.defaultModel) {
  78280. webVrController_1.defaultModel.setEnabled(true);
  78281. }
  78282. else {
  78283. // Load the meshes
  78284. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  78285. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  78286. if (_this.webVROptions.defaultLightingOnControllers) {
  78287. if (!_this._lightOnControllers) {
  78288. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  78289. }
  78290. var activateLightOnSubMeshes_1 = function (mesh, light) {
  78291. var children = mesh.getChildren();
  78292. if (children.length !== 0) {
  78293. children.forEach(function (mesh) {
  78294. light.includedOnlyMeshes.push(mesh);
  78295. activateLightOnSubMeshes_1(mesh, light);
  78296. });
  78297. }
  78298. };
  78299. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  78300. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  78301. }
  78302. });
  78303. }
  78304. }
  78305. webVrController_1.attachToPoseControlledCamera(_this);
  78306. // since this is async - sanity check. Is the controller already stored?
  78307. if (_this.controllers.indexOf(webVrController_1) === -1) {
  78308. //add to the controllers array
  78309. _this.controllers.push(webVrController_1);
  78310. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  78311. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  78312. // So we're overriding setting left & right manually to be sure
  78313. var firstViveWandDetected = false;
  78314. for (var i = 0; i < _this.controllers.length; i++) {
  78315. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  78316. if (!firstViveWandDetected) {
  78317. firstViveWandDetected = true;
  78318. _this.controllers[i].hand = "left";
  78319. }
  78320. else {
  78321. _this.controllers[i].hand = "right";
  78322. }
  78323. }
  78324. }
  78325. //did we find enough controllers? Great! let the developer know.
  78326. if (_this.controllers.length >= 2) {
  78327. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  78328. }
  78329. }
  78330. }
  78331. });
  78332. };
  78333. return WebVRFreeCamera;
  78334. }(BABYLON.FreeCamera));
  78335. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  78336. })(BABYLON || (BABYLON = {}));
  78337. //# sourceMappingURL=babylon.webVRCamera.js.map
  78338. var BABYLON;
  78339. (function (BABYLON) {
  78340. // We're mainly based on the logic defined into the FreeCamera code
  78341. /**
  78342. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  78343. * being tilted forward or back and left or right.
  78344. */
  78345. var DeviceOrientationCamera = /** @class */ (function (_super) {
  78346. __extends(DeviceOrientationCamera, _super);
  78347. /**
  78348. * Creates a new device orientation camera. @see DeviceOrientationCamera
  78349. * @param name The name of the camera
  78350. * @param position The start position camera
  78351. * @param scene The scene the camera belongs to
  78352. */
  78353. function DeviceOrientationCamera(name, position, scene) {
  78354. var _this = _super.call(this, name, position, scene) || this;
  78355. _this._quaternionCache = new BABYLON.Quaternion();
  78356. _this.inputs.addDeviceOrientation();
  78357. return _this;
  78358. }
  78359. /**
  78360. * Gets the current instance class name ("DeviceOrientationCamera").
  78361. * This helps avoiding instanceof at run time.
  78362. * @returns the class name
  78363. */
  78364. DeviceOrientationCamera.prototype.getClassName = function () {
  78365. return "DeviceOrientationCamera";
  78366. };
  78367. /**
  78368. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  78369. */
  78370. DeviceOrientationCamera.prototype._checkInputs = function () {
  78371. _super.prototype._checkInputs.call(this);
  78372. this._quaternionCache.copyFrom(this.rotationQuaternion);
  78373. if (this._initialQuaternion) {
  78374. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78375. }
  78376. };
  78377. /**
  78378. * Reset the camera to its default orientation on the specified axis only.
  78379. * @param axis The axis to reset
  78380. */
  78381. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  78382. var _this = this;
  78383. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  78384. //can only work if this camera has a rotation quaternion already.
  78385. if (!this.rotationQuaternion)
  78386. return;
  78387. if (!this._initialQuaternion) {
  78388. this._initialQuaternion = new BABYLON.Quaternion();
  78389. }
  78390. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  78391. ['x', 'y', 'z'].forEach(function (axisName) {
  78392. if (!axis[axisName]) {
  78393. _this._initialQuaternion[axisName] = 0;
  78394. }
  78395. else {
  78396. _this._initialQuaternion[axisName] *= -1;
  78397. }
  78398. });
  78399. this._initialQuaternion.normalize();
  78400. //force rotation update
  78401. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78402. };
  78403. return DeviceOrientationCamera;
  78404. }(BABYLON.FreeCamera));
  78405. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  78406. })(BABYLON || (BABYLON = {}));
  78407. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  78408. var BABYLON;
  78409. (function (BABYLON) {
  78410. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  78411. __extends(VRDeviceOrientationFreeCamera, _super);
  78412. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78413. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78414. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78415. var _this = _super.call(this, name, position, scene) || this;
  78416. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78417. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78418. return _this;
  78419. }
  78420. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  78421. return "VRDeviceOrientationFreeCamera";
  78422. };
  78423. return VRDeviceOrientationFreeCamera;
  78424. }(BABYLON.DeviceOrientationCamera));
  78425. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  78426. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  78427. __extends(VRDeviceOrientationGamepadCamera, _super);
  78428. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78429. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78430. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78431. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  78432. _this.inputs.addGamepad();
  78433. return _this;
  78434. }
  78435. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  78436. return "VRDeviceOrientationGamepadCamera";
  78437. };
  78438. return VRDeviceOrientationGamepadCamera;
  78439. }(VRDeviceOrientationFreeCamera));
  78440. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  78441. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  78442. __extends(VRDeviceOrientationArcRotateCamera, _super);
  78443. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  78444. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78445. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78446. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78447. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78448. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78449. _this.inputs.addVRDeviceOrientation();
  78450. return _this;
  78451. }
  78452. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  78453. return "VRDeviceOrientationArcRotateCamera";
  78454. };
  78455. return VRDeviceOrientationArcRotateCamera;
  78456. }(BABYLON.ArcRotateCamera));
  78457. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  78458. })(BABYLON || (BABYLON = {}));
  78459. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  78460. var BABYLON;
  78461. (function (BABYLON) {
  78462. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  78463. __extends(AnaglyphFreeCamera, _super);
  78464. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  78465. var _this = _super.call(this, name, position, scene) || this;
  78466. _this.interaxialDistance = interaxialDistance;
  78467. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78468. return _this;
  78469. }
  78470. AnaglyphFreeCamera.prototype.getClassName = function () {
  78471. return "AnaglyphFreeCamera";
  78472. };
  78473. return AnaglyphFreeCamera;
  78474. }(BABYLON.FreeCamera));
  78475. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  78476. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  78477. __extends(AnaglyphArcRotateCamera, _super);
  78478. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  78479. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78480. _this.interaxialDistance = interaxialDistance;
  78481. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78482. return _this;
  78483. }
  78484. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  78485. return "AnaglyphArcRotateCamera";
  78486. };
  78487. return AnaglyphArcRotateCamera;
  78488. }(BABYLON.ArcRotateCamera));
  78489. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  78490. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  78491. __extends(AnaglyphGamepadCamera, _super);
  78492. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  78493. var _this = _super.call(this, name, position, scene) || this;
  78494. _this.interaxialDistance = interaxialDistance;
  78495. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78496. return _this;
  78497. }
  78498. AnaglyphGamepadCamera.prototype.getClassName = function () {
  78499. return "AnaglyphGamepadCamera";
  78500. };
  78501. return AnaglyphGamepadCamera;
  78502. }(BABYLON.GamepadCamera));
  78503. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  78504. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  78505. __extends(AnaglyphUniversalCamera, _super);
  78506. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  78507. var _this = _super.call(this, name, position, scene) || this;
  78508. _this.interaxialDistance = interaxialDistance;
  78509. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78510. return _this;
  78511. }
  78512. AnaglyphUniversalCamera.prototype.getClassName = function () {
  78513. return "AnaglyphUniversalCamera";
  78514. };
  78515. return AnaglyphUniversalCamera;
  78516. }(BABYLON.UniversalCamera));
  78517. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  78518. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  78519. __extends(StereoscopicFreeCamera, _super);
  78520. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78521. var _this = _super.call(this, name, position, scene) || this;
  78522. _this.interaxialDistance = interaxialDistance;
  78523. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78524. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78525. return _this;
  78526. }
  78527. StereoscopicFreeCamera.prototype.getClassName = function () {
  78528. return "StereoscopicFreeCamera";
  78529. };
  78530. return StereoscopicFreeCamera;
  78531. }(BABYLON.FreeCamera));
  78532. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  78533. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  78534. __extends(StereoscopicArcRotateCamera, _super);
  78535. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  78536. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78537. _this.interaxialDistance = interaxialDistance;
  78538. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78539. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78540. return _this;
  78541. }
  78542. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  78543. return "StereoscopicArcRotateCamera";
  78544. };
  78545. return StereoscopicArcRotateCamera;
  78546. }(BABYLON.ArcRotateCamera));
  78547. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  78548. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  78549. __extends(StereoscopicGamepadCamera, _super);
  78550. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78551. var _this = _super.call(this, name, position, scene) || this;
  78552. _this.interaxialDistance = interaxialDistance;
  78553. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78554. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78555. return _this;
  78556. }
  78557. StereoscopicGamepadCamera.prototype.getClassName = function () {
  78558. return "StereoscopicGamepadCamera";
  78559. };
  78560. return StereoscopicGamepadCamera;
  78561. }(BABYLON.GamepadCamera));
  78562. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  78563. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  78564. __extends(StereoscopicUniversalCamera, _super);
  78565. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78566. var _this = _super.call(this, name, position, scene) || this;
  78567. _this.interaxialDistance = interaxialDistance;
  78568. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78569. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78570. return _this;
  78571. }
  78572. StereoscopicUniversalCamera.prototype.getClassName = function () {
  78573. return "StereoscopicUniversalCamera";
  78574. };
  78575. return StereoscopicUniversalCamera;
  78576. }(BABYLON.UniversalCamera));
  78577. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  78578. })(BABYLON || (BABYLON = {}));
  78579. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  78580. var BABYLON;
  78581. (function (BABYLON) {
  78582. /**
  78583. * Helps to quickly add VR support to an existing scene.
  78584. * See http://doc.babylonjs.com/how_to/webvr_helper
  78585. */
  78586. var VRExperienceHelper = /** @class */ (function () {
  78587. /**
  78588. * Instantiates a VRExperienceHelper.
  78589. * Helps to quickly add VR support to an existing scene.
  78590. * @param scene The scene the VRExperienceHelper belongs to.
  78591. * @param webVROptions Options to modify the vr experience helper's behavior.
  78592. */
  78593. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  78594. if (webVROptions === void 0) { webVROptions = {}; }
  78595. var _this = this;
  78596. this.webVROptions = webVROptions;
  78597. // Can the system support WebVR, even if a headset isn't plugged in?
  78598. this._webVRsupported = false;
  78599. // If WebVR is supported, is a headset plugged in and are we ready to present?
  78600. this._webVRready = false;
  78601. // Are we waiting for the requestPresent callback to complete?
  78602. this._webVRrequesting = false;
  78603. // Are we presenting to the headset right now?
  78604. this._webVRpresenting = false;
  78605. // Are we presenting in the fullscreen fallback?
  78606. this._fullscreenVRpresenting = false;
  78607. /**
  78608. * Observable raised when entering VR.
  78609. */
  78610. this.onEnteringVRObservable = new BABYLON.Observable();
  78611. /**
  78612. * Observable raised when exiting VR.
  78613. */
  78614. this.onExitingVRObservable = new BABYLON.Observable();
  78615. /**
  78616. * Observable raised when controller mesh is loaded.
  78617. */
  78618. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  78619. this._useCustomVRButton = false;
  78620. this._teleportationRequested = false;
  78621. this._teleportationEnabledOnLeftController = false;
  78622. this._teleportationEnabledOnRightController = false;
  78623. this._interactionsEnabledOnLeftController = false;
  78624. this._interactionsEnabledOnRightController = false;
  78625. this._leftControllerReady = false;
  78626. this._rightControllerReady = false;
  78627. this._floorMeshesCollection = [];
  78628. this._teleportationAllowed = false;
  78629. this._rotationAllowed = true;
  78630. this._teleportationRequestInitiated = false;
  78631. this._teleportationBackRequestInitiated = false;
  78632. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  78633. this._rotationRightAsked = false;
  78634. this._rotationLeftAsked = false;
  78635. this._isDefaultTeleportationTarget = true;
  78636. this._teleportationFillColor = "#444444";
  78637. this._teleportationBorderColor = "#FFFFFF";
  78638. this._rotationAngle = 0;
  78639. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  78640. this._padSensibilityUp = 0.65;
  78641. this._padSensibilityDown = 0.35;
  78642. /**
  78643. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  78644. */
  78645. this.onNewMeshSelected = new BABYLON.Observable();
  78646. /**
  78647. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  78648. */
  78649. this.onNewMeshPicked = new BABYLON.Observable();
  78650. /**
  78651. * Observable raised before camera teleportation
  78652. */
  78653. this.onBeforeCameraTeleport = new BABYLON.Observable();
  78654. /**
  78655. * Observable raised after camera teleportation
  78656. */
  78657. this.onAfterCameraTeleport = new BABYLON.Observable();
  78658. /**
  78659. * Observable raised when current selected mesh gets unselected
  78660. */
  78661. this.onSelectedMeshUnselected = new BABYLON.Observable();
  78662. /**
  78663. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  78664. */
  78665. this.teleportationEnabled = true;
  78666. this._pointerDownOnMeshAsked = false;
  78667. this._isActionableMesh = false;
  78668. this._teleportationInitialized = false;
  78669. this._interactionsEnabled = false;
  78670. this._interactionsRequested = false;
  78671. this._displayGaze = true;
  78672. this._displayLaserPointer = true;
  78673. this._dpadPressed = true;
  78674. this._onResize = function () {
  78675. _this.moveButtonToBottomRight();
  78676. if (_this._fullscreenVRpresenting && _this._webVRready) {
  78677. _this.exitVR();
  78678. }
  78679. };
  78680. this._onFullscreenChange = function () {
  78681. if (document.fullscreen !== undefined) {
  78682. _this._fullscreenVRpresenting = document.fullscreen;
  78683. }
  78684. else if (document.mozFullScreen !== undefined) {
  78685. _this._fullscreenVRpresenting = document.mozFullScreen;
  78686. }
  78687. else if (document.webkitIsFullScreen !== undefined) {
  78688. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  78689. }
  78690. else if (document.msIsFullScreen !== undefined) {
  78691. _this._fullscreenVRpresenting = document.msIsFullScreen;
  78692. }
  78693. if (!_this._fullscreenVRpresenting && _this._canvas) {
  78694. _this.exitVR();
  78695. if (!_this._useCustomVRButton) {
  78696. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  78697. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  78698. }
  78699. }
  78700. };
  78701. this.beforeRender = function () {
  78702. _this._castRayAndSelectObject();
  78703. };
  78704. this._onNewGamepadConnected = function (gamepad) {
  78705. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78706. if (gamepad.leftStick) {
  78707. gamepad.onleftstickchanged(function (stickValues) {
  78708. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  78709. // Listening to classic/xbox gamepad only if no VR controller is active
  78710. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  78711. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  78712. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  78713. _this._checkTeleportWithRay(stickValues);
  78714. _this._checkTeleportBackwards(stickValues);
  78715. }
  78716. }
  78717. });
  78718. }
  78719. if (gamepad.rightStick) {
  78720. gamepad.onrightstickchanged(function (stickValues) {
  78721. if (_this._teleportationInitialized) {
  78722. _this._checkRotate(stickValues);
  78723. }
  78724. });
  78725. }
  78726. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  78727. gamepad.onbuttondown(function (buttonPressed) {
  78728. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78729. _this._selectionPointerDown();
  78730. }
  78731. });
  78732. gamepad.onbuttonup(function (buttonPressed) {
  78733. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78734. _this._selectionPointerUp();
  78735. }
  78736. });
  78737. }
  78738. }
  78739. else {
  78740. var webVRController = gamepad;
  78741. _this._tryEnableInteractionOnController(webVRController);
  78742. }
  78743. };
  78744. // 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
  78745. this._tryEnableInteractionOnController = function (webVRController) {
  78746. if (webVRController.hand === "left") {
  78747. _this._leftControllerReady = true;
  78748. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  78749. _this._enableInteractionOnController(webVRController);
  78750. }
  78751. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  78752. _this._enableTeleportationOnController(webVRController);
  78753. }
  78754. }
  78755. if (webVRController.hand === "right") {
  78756. _this._rightControllerReady = true;
  78757. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  78758. _this._enableInteractionOnController(webVRController);
  78759. }
  78760. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  78761. _this._enableTeleportationOnController(webVRController);
  78762. }
  78763. }
  78764. };
  78765. this._onNewGamepadDisconnected = function (gamepad) {
  78766. if (gamepad instanceof BABYLON.WebVRController) {
  78767. if (gamepad.hand === "left") {
  78768. _this._interactionsEnabledOnLeftController = false;
  78769. _this._teleportationEnabledOnLeftController = false;
  78770. _this._leftControllerReady = false;
  78771. if (_this._leftLaserPointer) {
  78772. _this._leftLaserPointer.dispose();
  78773. }
  78774. }
  78775. if (gamepad.hand === "right") {
  78776. _this._interactionsEnabledOnRightController = false;
  78777. _this._teleportationEnabledOnRightController = false;
  78778. _this._rightControllerReady = false;
  78779. if (_this._rightLaserPointer) {
  78780. _this._rightLaserPointer.dispose();
  78781. }
  78782. }
  78783. }
  78784. };
  78785. this._workingVector = BABYLON.Vector3.Zero();
  78786. this._workingQuaternion = BABYLON.Quaternion.Identity();
  78787. this._workingMatrix = BABYLON.Matrix.Identity();
  78788. this._scene = scene;
  78789. this._canvas = scene.getEngine().getRenderingCanvas();
  78790. // Parse options
  78791. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  78792. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  78793. }
  78794. if (webVROptions.createDeviceOrientationCamera === undefined) {
  78795. webVROptions.createDeviceOrientationCamera = true;
  78796. }
  78797. if (webVROptions.defaultHeight === undefined) {
  78798. webVROptions.defaultHeight = 1.7;
  78799. }
  78800. if (webVROptions.useCustomVRButton) {
  78801. this._useCustomVRButton = true;
  78802. if (webVROptions.customVRButton) {
  78803. this._btnVR = webVROptions.customVRButton;
  78804. }
  78805. }
  78806. if (webVROptions.rayLength) {
  78807. this._rayLength = webVROptions.rayLength;
  78808. }
  78809. this._defaultHeight = webVROptions.defaultHeight;
  78810. // Set position
  78811. if (this._scene.activeCamera) {
  78812. this._position = this._scene.activeCamera.position.clone();
  78813. }
  78814. else {
  78815. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  78816. }
  78817. // Set non-vr camera
  78818. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  78819. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  78820. // Copy data from existing camera
  78821. if (this._scene.activeCamera) {
  78822. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  78823. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  78824. // Set rotation from previous camera
  78825. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  78826. var targetCamera = this._scene.activeCamera;
  78827. if (targetCamera.rotationQuaternion) {
  78828. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  78829. }
  78830. else {
  78831. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  78832. }
  78833. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  78834. }
  78835. }
  78836. this._scene.activeCamera = this._deviceOrientationCamera;
  78837. if (this._canvas) {
  78838. this._scene.activeCamera.attachControl(this._canvas);
  78839. }
  78840. }
  78841. else {
  78842. this._existingCamera = this._scene.activeCamera;
  78843. }
  78844. // Create VR cameras
  78845. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78846. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  78847. }
  78848. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  78849. this._webVRCamera.useStandingMatrix();
  78850. // Create default button
  78851. if (!this._useCustomVRButton) {
  78852. this._btnVR = document.createElement("BUTTON");
  78853. this._btnVR.className = "babylonVRicon";
  78854. this._btnVR.id = "babylonVRiconbtn";
  78855. this._btnVR.title = "Click to switch to VR";
  78856. 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) }";
  78857. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  78858. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  78859. // css += ".babylonVRicon.vrdisplaysupported { }";
  78860. // css += ".babylonVRicon.vrdisplayready { }";
  78861. // css += ".babylonVRicon.vrdisplayrequesting { }";
  78862. var style = document.createElement('style');
  78863. style.appendChild(document.createTextNode(css));
  78864. document.getElementsByTagName('head')[0].appendChild(style);
  78865. this.moveButtonToBottomRight();
  78866. }
  78867. // VR button click event
  78868. if (this._btnVR) {
  78869. this._btnVR.addEventListener("click", function () {
  78870. if (!_this.isInVRMode) {
  78871. _this.enterVR();
  78872. }
  78873. else {
  78874. _this.exitVR();
  78875. }
  78876. });
  78877. }
  78878. // Window events
  78879. window.addEventListener("resize", this._onResize);
  78880. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  78881. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  78882. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  78883. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  78884. // Display vr button when headset is connected
  78885. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78886. this.displayVRButton();
  78887. }
  78888. else {
  78889. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  78890. if (e.vrDisplay) {
  78891. _this.displayVRButton();
  78892. }
  78893. });
  78894. }
  78895. // Exiting VR mode using 'ESC' key on desktop
  78896. this._onKeyDown = function (event) {
  78897. if (event.keyCode === 27 && _this.isInVRMode) {
  78898. _this.exitVR();
  78899. }
  78900. };
  78901. document.addEventListener("keydown", this._onKeyDown);
  78902. // Exiting VR mode double tapping the touch screen
  78903. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  78904. if (_this.isInVRMode) {
  78905. _this.exitVR();
  78906. if (_this._fullscreenVRpresenting) {
  78907. _this._scene.getEngine().switchFullscreen(true);
  78908. }
  78909. }
  78910. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  78911. // Listen for WebVR display changes
  78912. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  78913. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  78914. this._onVRRequestPresentStart = function () {
  78915. _this._webVRrequesting = true;
  78916. _this.updateButtonVisibility();
  78917. };
  78918. this._onVRRequestPresentComplete = function (success) {
  78919. _this._webVRrequesting = false;
  78920. _this.updateButtonVisibility();
  78921. };
  78922. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  78923. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  78924. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  78925. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  78926. scene.onDisposeObservable.add(function () {
  78927. _this.dispose();
  78928. });
  78929. // Gamepad connection events
  78930. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  78931. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  78932. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  78933. this.updateButtonVisibility();
  78934. //create easing functions
  78935. this._circleEase = new BABYLON.CircleEase();
  78936. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  78937. }
  78938. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  78939. /** Return this.onEnteringVRObservable
  78940. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  78941. */
  78942. get: function () {
  78943. return this.onEnteringVRObservable;
  78944. },
  78945. enumerable: true,
  78946. configurable: true
  78947. });
  78948. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  78949. /** Return this.onExitingVRObservable
  78950. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  78951. */
  78952. get: function () {
  78953. return this.onExitingVRObservable;
  78954. },
  78955. enumerable: true,
  78956. configurable: true
  78957. });
  78958. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  78959. /** Return this.onControllerMeshLoadedObservable
  78960. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  78961. */
  78962. get: function () {
  78963. return this.onControllerMeshLoadedObservable;
  78964. },
  78965. enumerable: true,
  78966. configurable: true
  78967. });
  78968. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  78969. /**
  78970. * The mesh used to display where the user is going to teleport.
  78971. */
  78972. get: function () {
  78973. return this._teleportationTarget;
  78974. },
  78975. /**
  78976. * Sets the mesh to be used to display where the user is going to teleport.
  78977. */
  78978. set: function (value) {
  78979. if (value) {
  78980. value.name = "teleportationTarget";
  78981. this._isDefaultTeleportationTarget = false;
  78982. this._teleportationTarget = value;
  78983. }
  78984. },
  78985. enumerable: true,
  78986. configurable: true
  78987. });
  78988. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  78989. /**
  78990. * The mesh used to display where the user is selecting.
  78991. */
  78992. get: function () {
  78993. return this._gazeTracker;
  78994. },
  78995. /**
  78996. * Sets the mesh to be used to display where the user is selecting.
  78997. */
  78998. set: function (value) {
  78999. if (value) {
  79000. this._gazeTracker = value;
  79001. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79002. this._gazeTracker.isPickable = false;
  79003. this._gazeTracker.isVisible = false;
  79004. }
  79005. },
  79006. enumerable: true,
  79007. configurable: true
  79008. });
  79009. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  79010. /**
  79011. * If the ray of the gaze should be displayed.
  79012. */
  79013. get: function () {
  79014. return this._displayGaze;
  79015. },
  79016. /**
  79017. * Sets if the ray of the gaze should be displayed.
  79018. */
  79019. set: function (value) {
  79020. this._displayGaze = value;
  79021. if (!value) {
  79022. this._gazeTracker.isVisible = false;
  79023. }
  79024. },
  79025. enumerable: true,
  79026. configurable: true
  79027. });
  79028. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  79029. /**
  79030. * If the ray of the LaserPointer should be displayed.
  79031. */
  79032. get: function () {
  79033. return this._displayLaserPointer;
  79034. },
  79035. /**
  79036. * Sets if the ray of the LaserPointer should be displayed.
  79037. */
  79038. set: function (value) {
  79039. this._displayLaserPointer = value;
  79040. if (!value) {
  79041. if (this._rightLaserPointer) {
  79042. this._rightLaserPointer.isVisible = false;
  79043. }
  79044. if (this._leftLaserPointer) {
  79045. this._leftLaserPointer.isVisible = false;
  79046. }
  79047. }
  79048. else {
  79049. if (this._rightLaserPointer) {
  79050. this._rightLaserPointer.isVisible = true;
  79051. }
  79052. else if (this._leftLaserPointer) {
  79053. this._leftLaserPointer.isVisible = true;
  79054. }
  79055. }
  79056. },
  79057. enumerable: true,
  79058. configurable: true
  79059. });
  79060. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  79061. /**
  79062. * The deviceOrientationCamera used as the camera when not in VR.
  79063. */
  79064. get: function () {
  79065. return this._deviceOrientationCamera;
  79066. },
  79067. enumerable: true,
  79068. configurable: true
  79069. });
  79070. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  79071. /**
  79072. * Based on the current WebVR support, returns the current VR camera used.
  79073. */
  79074. get: function () {
  79075. if (this._webVRready) {
  79076. return this._webVRCamera;
  79077. }
  79078. else {
  79079. return this._scene.activeCamera;
  79080. }
  79081. },
  79082. enumerable: true,
  79083. configurable: true
  79084. });
  79085. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  79086. /**
  79087. * The webVRCamera which is used when in VR.
  79088. */
  79089. get: function () {
  79090. return this._webVRCamera;
  79091. },
  79092. enumerable: true,
  79093. configurable: true
  79094. });
  79095. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  79096. /**
  79097. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  79098. */
  79099. get: function () {
  79100. return this._vrDeviceOrientationCamera;
  79101. },
  79102. enumerable: true,
  79103. configurable: true
  79104. });
  79105. // Raised when one of the controller has loaded successfully its associated default mesh
  79106. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  79107. this._tryEnableInteractionOnController(webVRController);
  79108. try {
  79109. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  79110. }
  79111. catch (err) {
  79112. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  79113. }
  79114. };
  79115. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  79116. /**
  79117. * Gets a value indicating if we are currently in VR mode.
  79118. */
  79119. get: function () {
  79120. return this._webVRpresenting || this._fullscreenVRpresenting;
  79121. },
  79122. enumerable: true,
  79123. configurable: true
  79124. });
  79125. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  79126. var vrDisplay = this._scene.getEngine().getVRDevice();
  79127. if (vrDisplay) {
  79128. var wasPresenting = this._webVRpresenting;
  79129. // A VR display is connected
  79130. this._webVRpresenting = vrDisplay.isPresenting;
  79131. if (wasPresenting && !this._webVRpresenting)
  79132. this.exitVR();
  79133. }
  79134. else {
  79135. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  79136. }
  79137. this.updateButtonVisibility();
  79138. };
  79139. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  79140. this._webVRsupported = eventArgs.vrSupported;
  79141. this._webVRready = !!eventArgs.vrDisplay;
  79142. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  79143. this.updateButtonVisibility();
  79144. };
  79145. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  79146. if (this._canvas && !this._useCustomVRButton) {
  79147. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  79148. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  79149. }
  79150. };
  79151. VRExperienceHelper.prototype.displayVRButton = function () {
  79152. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  79153. document.body.appendChild(this._btnVR);
  79154. this._btnVRDisplayed = true;
  79155. }
  79156. };
  79157. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  79158. if (!this._btnVR || this._useCustomVRButton) {
  79159. return;
  79160. }
  79161. this._btnVR.className = "babylonVRicon";
  79162. if (this.isInVRMode) {
  79163. this._btnVR.className += " vrdisplaypresenting";
  79164. }
  79165. else {
  79166. if (this._webVRready)
  79167. this._btnVR.className += " vrdisplayready";
  79168. if (this._webVRsupported)
  79169. this._btnVR.className += " vrdisplaysupported";
  79170. if (this._webVRrequesting)
  79171. this._btnVR.className += " vrdisplayrequesting";
  79172. }
  79173. };
  79174. /**
  79175. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  79176. * Otherwise, will use the fullscreen API.
  79177. */
  79178. VRExperienceHelper.prototype.enterVR = function () {
  79179. if (this.onEnteringVRObservable) {
  79180. try {
  79181. this.onEnteringVRObservable.notifyObservers(this);
  79182. }
  79183. catch (err) {
  79184. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  79185. }
  79186. }
  79187. if (this._scene.activeCamera) {
  79188. this._position = this._scene.activeCamera.position.clone();
  79189. // make sure that we return to the last active camera
  79190. this._existingCamera = this._scene.activeCamera;
  79191. }
  79192. if (this._webVRrequesting)
  79193. return;
  79194. // If WebVR is supported and a headset is connected
  79195. if (this._webVRready) {
  79196. if (!this._webVRpresenting) {
  79197. this._webVRCamera.position = this._position;
  79198. this._scene.activeCamera = this._webVRCamera;
  79199. }
  79200. }
  79201. else if (this._vrDeviceOrientationCamera) {
  79202. this._vrDeviceOrientationCamera.position = this._position;
  79203. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  79204. this._scene.getEngine().switchFullscreen(true);
  79205. this.updateButtonVisibility();
  79206. }
  79207. if (this._scene.activeCamera && this._canvas) {
  79208. this._scene.activeCamera.attachControl(this._canvas);
  79209. }
  79210. if (this._interactionsEnabled) {
  79211. this._scene.registerBeforeRender(this.beforeRender);
  79212. }
  79213. };
  79214. /**
  79215. * Attempt to exit VR, or fullscreen.
  79216. */
  79217. VRExperienceHelper.prototype.exitVR = function () {
  79218. if (this.onExitingVRObservable) {
  79219. try {
  79220. this.onExitingVRObservable.notifyObservers(this);
  79221. }
  79222. catch (err) {
  79223. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  79224. }
  79225. }
  79226. if (this._webVRpresenting) {
  79227. this._scene.getEngine().disableVR();
  79228. }
  79229. if (this._scene.activeCamera) {
  79230. this._position = this._scene.activeCamera.position.clone();
  79231. }
  79232. if (this._deviceOrientationCamera) {
  79233. this._deviceOrientationCamera.position = this._position;
  79234. this._scene.activeCamera = this._deviceOrientationCamera;
  79235. if (this._canvas) {
  79236. this._scene.activeCamera.attachControl(this._canvas);
  79237. }
  79238. }
  79239. else if (this._existingCamera) {
  79240. this._existingCamera.position = this._position;
  79241. this._scene.activeCamera = this._existingCamera;
  79242. }
  79243. this.updateButtonVisibility();
  79244. if (this._interactionsEnabled) {
  79245. this._scene.unregisterBeforeRender(this.beforeRender);
  79246. }
  79247. };
  79248. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  79249. /**
  79250. * The position of the vr experience helper.
  79251. */
  79252. get: function () {
  79253. return this._position;
  79254. },
  79255. /**
  79256. * Sets the position of the vr experience helper.
  79257. */
  79258. set: function (value) {
  79259. this._position = value;
  79260. if (this._scene.activeCamera) {
  79261. this._scene.activeCamera.position = value;
  79262. }
  79263. },
  79264. enumerable: true,
  79265. configurable: true
  79266. });
  79267. /**
  79268. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  79269. */
  79270. VRExperienceHelper.prototype.enableInteractions = function () {
  79271. var _this = this;
  79272. if (!this._interactionsEnabled) {
  79273. this._interactionsRequested = true;
  79274. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79275. this._enableInteractionOnController(this._webVRCamera.leftController);
  79276. }
  79277. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79278. this._enableInteractionOnController(this._webVRCamera.rightController);
  79279. }
  79280. if (!this._gazeTracker) {
  79281. this._createGazeTracker();
  79282. }
  79283. this.raySelectionPredicate = function (mesh) {
  79284. return mesh.isVisible;
  79285. };
  79286. this.meshSelectionPredicate = function (mesh) {
  79287. return true;
  79288. };
  79289. this._raySelectionPredicate = function (mesh) {
  79290. if (_this._isTeleportationFloor(mesh) || (mesh != _this._gazeTracker
  79291. && mesh.name.indexOf("teleportationTarget") === -1
  79292. && mesh.name.indexOf("torusTeleportation") === -1
  79293. && mesh.name.indexOf("laserPointer") === -1)) {
  79294. return _this.raySelectionPredicate(mesh);
  79295. }
  79296. return false;
  79297. };
  79298. this._interactionsEnabled = true;
  79299. }
  79300. };
  79301. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  79302. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  79303. if (this._floorMeshesCollection[i].id === mesh.id) {
  79304. return true;
  79305. }
  79306. }
  79307. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  79308. return true;
  79309. }
  79310. return false;
  79311. };
  79312. /**
  79313. * Adds a floor mesh to be used for teleportation.
  79314. * @param floorMesh the mesh to be used for teleportation.
  79315. */
  79316. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  79317. if (!this._floorMeshesCollection) {
  79318. return;
  79319. }
  79320. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  79321. return;
  79322. }
  79323. this._floorMeshesCollection.push(floorMesh);
  79324. };
  79325. /**
  79326. * Removes a floor mesh from being used for teleportation.
  79327. * @param floorMesh the mesh to be removed.
  79328. */
  79329. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  79330. if (!this._floorMeshesCollection) {
  79331. return;
  79332. }
  79333. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  79334. if (meshIndex !== -1) {
  79335. this._floorMeshesCollection.splice(meshIndex, 1);
  79336. }
  79337. };
  79338. /**
  79339. * Enables interactions and teleportation using the VR controllers and gaze.
  79340. * @param vrTeleportationOptions options to modify teleportation behavior.
  79341. */
  79342. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  79343. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  79344. if (!this._teleportationInitialized) {
  79345. this._teleportationRequested = true;
  79346. this.enableInteractions();
  79347. if (vrTeleportationOptions.floorMeshName) {
  79348. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  79349. }
  79350. if (vrTeleportationOptions.floorMeshes) {
  79351. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  79352. }
  79353. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79354. this._enableTeleportationOnController(this._webVRCamera.leftController);
  79355. }
  79356. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79357. this._enableTeleportationOnController(this._webVRCamera.rightController);
  79358. }
  79359. // Creates an image processing post process for the vignette not relying
  79360. // on the main scene configuration for image processing to reduce setup and spaces
  79361. // (gamma/linear) conflicts.
  79362. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  79363. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  79364. imageProcessingConfiguration.vignetteEnabled = true;
  79365. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  79366. this._webVRCamera.detachPostProcess(this._postProcessMove);
  79367. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  79368. this._teleportationInitialized = true;
  79369. if (this._isDefaultTeleportationTarget) {
  79370. this._createTeleportationCircles();
  79371. }
  79372. }
  79373. };
  79374. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  79375. var _this = this;
  79376. var controllerMesh = webVRController.mesh;
  79377. if (controllerMesh) {
  79378. var makeNotPick = function (root) {
  79379. root.name += " laserPointer";
  79380. root.getChildMeshes().forEach(function (c) {
  79381. makeNotPick(c);
  79382. });
  79383. };
  79384. makeNotPick(controllerMesh);
  79385. var childMeshes = controllerMesh.getChildMeshes();
  79386. for (var i = 0; i < childMeshes.length; i++) {
  79387. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  79388. controllerMesh = childMeshes[i];
  79389. break;
  79390. }
  79391. }
  79392. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  79393. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  79394. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79395. laserPointerMaterial.alpha = 0.6;
  79396. laserPointer.material = laserPointerMaterial;
  79397. laserPointer.rotation.x = Math.PI / 2;
  79398. laserPointer.parent = controllerMesh;
  79399. laserPointer.position.z = -0.5;
  79400. laserPointer.isVisible = false;
  79401. if (webVRController.hand === "left") {
  79402. this._leftLaserPointer = laserPointer;
  79403. this._interactionsEnabledOnLeftController = true;
  79404. if (!this._rightLaserPointer) {
  79405. this._leftLaserPointer.isVisible = true;
  79406. }
  79407. }
  79408. else {
  79409. this._rightLaserPointer = laserPointer;
  79410. this._interactionsEnabledOnRightController = true;
  79411. if (!this._leftLaserPointer) {
  79412. this._rightLaserPointer.isVisible = true;
  79413. }
  79414. }
  79415. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  79416. // Enabling / disabling laserPointer
  79417. if (_this._displayLaserPointer && stateObject.value === 1) {
  79418. laserPointer.isVisible = !laserPointer.isVisible;
  79419. // Laser pointer can only be active on left or right, not both at the same time
  79420. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  79421. _this._rightLaserPointer.isVisible = false;
  79422. }
  79423. else if (_this._leftLaserPointer) {
  79424. _this._leftLaserPointer.isVisible = false;
  79425. }
  79426. }
  79427. });
  79428. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  79429. if (!_this._pointerDownOnMeshAsked) {
  79430. if (stateObject.value > _this._padSensibilityUp) {
  79431. _this._selectionPointerDown();
  79432. }
  79433. }
  79434. else if (stateObject.value < _this._padSensibilityDown) {
  79435. _this._selectionPointerUp();
  79436. }
  79437. });
  79438. }
  79439. };
  79440. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  79441. if (webVRController === void 0) { webVRController = null; }
  79442. if (!this._teleportationRequestInitiated) {
  79443. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  79444. if (webVRController) {
  79445. // If laser pointer wasn't enabled yet
  79446. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  79447. this._leftLaserPointer.isVisible = true;
  79448. if (this._rightLaserPointer) {
  79449. this._rightLaserPointer.isVisible = false;
  79450. }
  79451. }
  79452. else if (this._displayLaserPointer && this._rightLaserPointer) {
  79453. this._rightLaserPointer.isVisible = true;
  79454. if (this._leftLaserPointer) {
  79455. this._leftLaserPointer.isVisible = false;
  79456. }
  79457. }
  79458. }
  79459. this._teleportationRequestInitiated = true;
  79460. }
  79461. }
  79462. else {
  79463. // Listening to the proper controller values changes to confirm teleportation
  79464. if (webVRController == null
  79465. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  79466. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  79467. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  79468. if (this._teleportationAllowed) {
  79469. this._teleportationAllowed = false;
  79470. this._teleportCamera();
  79471. }
  79472. this._teleportationRequestInitiated = false;
  79473. }
  79474. }
  79475. }
  79476. };
  79477. VRExperienceHelper.prototype._selectionPointerDown = function () {
  79478. this._pointerDownOnMeshAsked = true;
  79479. if (this._currentMeshSelected && this._currentHit) {
  79480. this._scene.simulatePointerDown(this._currentHit);
  79481. }
  79482. };
  79483. VRExperienceHelper.prototype._selectionPointerUp = function () {
  79484. if (this._currentMeshSelected && this._currentHit) {
  79485. this._scene.simulatePointerUp(this._currentHit);
  79486. }
  79487. this._pointerDownOnMeshAsked = false;
  79488. };
  79489. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  79490. // Only rotate when user is not currently selecting a teleportation location
  79491. if (this._teleportationRequestInitiated) {
  79492. return;
  79493. }
  79494. if (!this._rotationLeftAsked) {
  79495. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  79496. this._rotationLeftAsked = true;
  79497. if (this._rotationAllowed) {
  79498. this._rotateCamera(false);
  79499. }
  79500. }
  79501. }
  79502. else {
  79503. if (stateObject.x > -this._padSensibilityDown) {
  79504. this._rotationLeftAsked = false;
  79505. }
  79506. }
  79507. if (!this._rotationRightAsked) {
  79508. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  79509. this._rotationRightAsked = true;
  79510. if (this._rotationAllowed) {
  79511. this._rotateCamera(true);
  79512. }
  79513. }
  79514. }
  79515. else {
  79516. if (stateObject.x < this._padSensibilityDown) {
  79517. this._rotationRightAsked = false;
  79518. }
  79519. }
  79520. };
  79521. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  79522. // Only teleport backwards when user is not currently selecting a teleportation location
  79523. if (this._teleportationRequestInitiated) {
  79524. return;
  79525. }
  79526. // Teleport backwards
  79527. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  79528. if (!this._teleportationBackRequestInitiated) {
  79529. if (!this.currentVRCamera) {
  79530. return;
  79531. }
  79532. // Get rotation and position of the current camera
  79533. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  79534. var position = this.currentVRCamera.position;
  79535. // If the camera has device position, use that instead
  79536. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  79537. rotation = this.currentVRCamera.deviceRotationQuaternion;
  79538. position = this.currentVRCamera.devicePosition;
  79539. }
  79540. // Get matrix with only the y rotation of the device rotation
  79541. rotation.toEulerAnglesToRef(this._workingVector);
  79542. this._workingVector.z = 0;
  79543. this._workingVector.x = 0;
  79544. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  79545. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  79546. // Rotate backwards ray by device rotation to cast at the ground behind the user
  79547. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  79548. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  79549. var ray = new BABYLON.Ray(position, this._workingVector);
  79550. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79551. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  79552. this._teleportCamera(hit.pickedPoint);
  79553. }
  79554. this._teleportationBackRequestInitiated = true;
  79555. }
  79556. }
  79557. else {
  79558. this._teleportationBackRequestInitiated = false;
  79559. }
  79560. };
  79561. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  79562. var _this = this;
  79563. var controllerMesh = webVRController.mesh;
  79564. if (controllerMesh) {
  79565. if (webVRController.hand === "left") {
  79566. if (!this._interactionsEnabledOnLeftController) {
  79567. this._enableInteractionOnController(webVRController);
  79568. }
  79569. this._teleportationEnabledOnLeftController = true;
  79570. }
  79571. else {
  79572. if (!this._interactionsEnabledOnRightController) {
  79573. this._enableInteractionOnController(webVRController);
  79574. }
  79575. this._teleportationEnabledOnRightController = true;
  79576. }
  79577. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79578. this._dpadPressed = false;
  79579. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  79580. _this._dpadPressed = stateObject.pressed;
  79581. if (!_this._dpadPressed) {
  79582. _this._rotationLeftAsked = false;
  79583. _this._rotationRightAsked = false;
  79584. _this._teleportationBackRequestInitiated = false;
  79585. }
  79586. });
  79587. }
  79588. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  79589. if (_this.teleportationEnabled) {
  79590. _this._checkTeleportBackwards(stateObject);
  79591. _this._checkTeleportWithRay(stateObject, webVRController);
  79592. }
  79593. _this._checkRotate(stateObject);
  79594. });
  79595. }
  79596. };
  79597. // Gaze support used to point to teleport or to interact with an object
  79598. VRExperienceHelper.prototype._createGazeTracker = function () {
  79599. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  79600. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79601. this._gazeTracker.isPickable = false;
  79602. this._gazeTracker.isVisible = false;
  79603. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  79604. targetMat.specularColor = BABYLON.Color3.Black();
  79605. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79606. targetMat.backFaceCulling = false;
  79607. this._gazeTracker.material = targetMat;
  79608. };
  79609. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  79610. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  79611. this._teleportationTarget.isPickable = false;
  79612. var length = 512;
  79613. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  79614. dynamicTexture.hasAlpha = true;
  79615. var context = dynamicTexture.getContext();
  79616. var centerX = length / 2;
  79617. var centerY = length / 2;
  79618. var radius = 200;
  79619. context.beginPath();
  79620. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  79621. context.fillStyle = this._teleportationFillColor;
  79622. context.fill();
  79623. context.lineWidth = 10;
  79624. context.strokeStyle = this._teleportationBorderColor;
  79625. context.stroke();
  79626. context.closePath();
  79627. dynamicTexture.update();
  79628. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  79629. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  79630. this._teleportationTarget.material = teleportationCircleMaterial;
  79631. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  79632. torus.isPickable = false;
  79633. torus.parent = this._teleportationTarget;
  79634. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  79635. var keys = [];
  79636. keys.push({
  79637. frame: 0,
  79638. value: 0
  79639. });
  79640. keys.push({
  79641. frame: 30,
  79642. value: 0.4
  79643. });
  79644. keys.push({
  79645. frame: 60,
  79646. value: 0
  79647. });
  79648. animationInnerCircle.setKeys(keys);
  79649. var easingFunction = new BABYLON.SineEase();
  79650. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  79651. animationInnerCircle.setEasingFunction(easingFunction);
  79652. torus.animations = [];
  79653. torus.animations.push(animationInnerCircle);
  79654. this._scene.beginAnimation(torus, 0, 60, true);
  79655. this._hideTeleportationTarget();
  79656. };
  79657. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  79658. if (this._teleportationInitialized) {
  79659. this._teleportationTarget.isVisible = true;
  79660. if (this._isDefaultTeleportationTarget) {
  79661. this._teleportationTarget.getChildren()[0].isVisible = true;
  79662. }
  79663. }
  79664. };
  79665. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  79666. if (this._teleportationInitialized) {
  79667. this._teleportationTarget.isVisible = false;
  79668. if (this._isDefaultTeleportationTarget) {
  79669. this._teleportationTarget.getChildren()[0].isVisible = false;
  79670. }
  79671. }
  79672. };
  79673. VRExperienceHelper.prototype._rotateCamera = function (right) {
  79674. var _this = this;
  79675. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79676. return;
  79677. }
  79678. if (right) {
  79679. this._rotationAngle++;
  79680. }
  79681. else {
  79682. this._rotationAngle--;
  79683. }
  79684. this.currentVRCamera.animations = [];
  79685. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  79686. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79687. var animationRotationKeys = [];
  79688. animationRotationKeys.push({
  79689. frame: 0,
  79690. value: this.currentVRCamera.rotationQuaternion
  79691. });
  79692. animationRotationKeys.push({
  79693. frame: 6,
  79694. value: target
  79695. });
  79696. animationRotation.setKeys(animationRotationKeys);
  79697. animationRotation.setEasingFunction(this._circleEase);
  79698. this.currentVRCamera.animations.push(animationRotation);
  79699. this._postProcessMove.animations = [];
  79700. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79701. var vignetteWeightKeys = [];
  79702. vignetteWeightKeys.push({
  79703. frame: 0,
  79704. value: 0
  79705. });
  79706. vignetteWeightKeys.push({
  79707. frame: 3,
  79708. value: 4
  79709. });
  79710. vignetteWeightKeys.push({
  79711. frame: 6,
  79712. value: 0
  79713. });
  79714. animationPP.setKeys(vignetteWeightKeys);
  79715. animationPP.setEasingFunction(this._circleEase);
  79716. this._postProcessMove.animations.push(animationPP);
  79717. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79718. var vignetteStretchKeys = [];
  79719. vignetteStretchKeys.push({
  79720. frame: 0,
  79721. value: 0
  79722. });
  79723. vignetteStretchKeys.push({
  79724. frame: 3,
  79725. value: 10
  79726. });
  79727. vignetteStretchKeys.push({
  79728. frame: 6,
  79729. value: 0
  79730. });
  79731. animationPP2.setKeys(vignetteStretchKeys);
  79732. animationPP2.setEasingFunction(this._circleEase);
  79733. this._postProcessMove.animations.push(animationPP2);
  79734. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79735. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79736. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79737. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  79738. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79739. });
  79740. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  79741. };
  79742. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  79743. if (hit.pickedPoint) {
  79744. this._teleportationAllowed = true;
  79745. if (this._teleportationRequestInitiated) {
  79746. this._displayTeleportationTarget();
  79747. }
  79748. else {
  79749. this._hideTeleportationTarget();
  79750. }
  79751. this._haloCenter.copyFrom(hit.pickedPoint);
  79752. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  79753. var pickNormal = hit.getNormal(true, false);
  79754. if (pickNormal) {
  79755. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79756. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79757. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  79758. }
  79759. this._teleportationTarget.position.y += 0.1;
  79760. }
  79761. };
  79762. VRExperienceHelper.prototype._teleportCamera = function (location) {
  79763. var _this = this;
  79764. if (location === void 0) { location = null; }
  79765. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79766. return;
  79767. }
  79768. if (!location) {
  79769. location = this._haloCenter;
  79770. }
  79771. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  79772. // offset of the headset from the anchor.
  79773. if (this.webVRCamera.leftCamera) {
  79774. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  79775. this._workingVector.subtractInPlace(this.webVRCamera.position);
  79776. location.subtractToRef(this._workingVector, this._workingVector);
  79777. }
  79778. else {
  79779. this._workingVector.copyFrom(location);
  79780. }
  79781. // Add height to account for user's height offset
  79782. if (this.isInVRMode) {
  79783. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  79784. }
  79785. else {
  79786. this._workingVector.y += this._defaultHeight;
  79787. }
  79788. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  79789. // Create animation from the camera's position to the new location
  79790. this.currentVRCamera.animations = [];
  79791. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79792. var animationCameraTeleportationKeys = [{
  79793. frame: 0,
  79794. value: this.currentVRCamera.position
  79795. },
  79796. {
  79797. frame: 11,
  79798. value: this._workingVector
  79799. }
  79800. ];
  79801. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  79802. animationCameraTeleportation.setEasingFunction(this._circleEase);
  79803. this.currentVRCamera.animations.push(animationCameraTeleportation);
  79804. this._postProcessMove.animations = [];
  79805. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79806. var vignetteWeightKeys = [];
  79807. vignetteWeightKeys.push({
  79808. frame: 0,
  79809. value: 0
  79810. });
  79811. vignetteWeightKeys.push({
  79812. frame: 5,
  79813. value: 8
  79814. });
  79815. vignetteWeightKeys.push({
  79816. frame: 11,
  79817. value: 0
  79818. });
  79819. animationPP.setKeys(vignetteWeightKeys);
  79820. this._postProcessMove.animations.push(animationPP);
  79821. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79822. var vignetteStretchKeys = [];
  79823. vignetteStretchKeys.push({
  79824. frame: 0,
  79825. value: 0
  79826. });
  79827. vignetteStretchKeys.push({
  79828. frame: 5,
  79829. value: 10
  79830. });
  79831. vignetteStretchKeys.push({
  79832. frame: 11,
  79833. value: 0
  79834. });
  79835. animationPP2.setKeys(vignetteStretchKeys);
  79836. this._postProcessMove.animations.push(animationPP2);
  79837. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79838. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79839. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79840. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  79841. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79842. });
  79843. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  79844. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  79845. });
  79846. };
  79847. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  79848. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79849. return;
  79850. }
  79851. var ray;
  79852. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  79853. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  79854. }
  79855. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  79856. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  79857. }
  79858. else {
  79859. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  79860. }
  79861. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79862. // Moving the gazeTracker on the mesh face targetted
  79863. if (hit && hit.pickedPoint) {
  79864. if (this._displayGaze) {
  79865. var multiplier = 1;
  79866. this._gazeTracker.isVisible = true;
  79867. if (this._isActionableMesh) {
  79868. multiplier = 3;
  79869. }
  79870. this._gazeTracker.scaling.x = hit.distance * multiplier;
  79871. this._gazeTracker.scaling.y = hit.distance * multiplier;
  79872. this._gazeTracker.scaling.z = hit.distance * multiplier;
  79873. var pickNormal = hit.getNormal();
  79874. // To avoid z-fighting
  79875. var deltaFighting = 0.002;
  79876. if (pickNormal) {
  79877. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79878. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79879. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  79880. }
  79881. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  79882. if (this._gazeTracker.position.x < 0) {
  79883. this._gazeTracker.position.x += deltaFighting;
  79884. }
  79885. else {
  79886. this._gazeTracker.position.x -= deltaFighting;
  79887. }
  79888. if (this._gazeTracker.position.y < 0) {
  79889. this._gazeTracker.position.y += deltaFighting;
  79890. }
  79891. else {
  79892. this._gazeTracker.position.y -= deltaFighting;
  79893. }
  79894. if (this._gazeTracker.position.z < 0) {
  79895. this._gazeTracker.position.z += deltaFighting;
  79896. }
  79897. else {
  79898. this._gazeTracker.position.z -= deltaFighting;
  79899. }
  79900. }
  79901. // Changing the size of the laser pointer based on the distance from the targetted point
  79902. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  79903. this._rightLaserPointer.scaling.y = hit.distance;
  79904. this._rightLaserPointer.position.z = -hit.distance / 2;
  79905. }
  79906. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  79907. this._leftLaserPointer.scaling.y = hit.distance;
  79908. this._leftLaserPointer.position.z = -hit.distance / 2;
  79909. }
  79910. }
  79911. else {
  79912. this._gazeTracker.isVisible = false;
  79913. }
  79914. if (hit && hit.pickedMesh) {
  79915. this._currentHit = hit;
  79916. if (this._pointerDownOnMeshAsked) {
  79917. this._scene.simulatePointerMove(this._currentHit);
  79918. }
  79919. // The object selected is the floor, we're in a teleportation scenario
  79920. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  79921. // Moving the teleportation area to this targetted point
  79922. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  79923. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  79924. this._notifySelectedMeshUnselected();
  79925. }
  79926. this._currentMeshSelected = null;
  79927. this._moveTeleportationSelectorTo(hit);
  79928. return;
  79929. }
  79930. // If not, we're in a selection scenario
  79931. this._hideTeleportationTarget();
  79932. this._teleportationAllowed = false;
  79933. if (hit.pickedMesh !== this._currentMeshSelected) {
  79934. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  79935. this.onNewMeshPicked.notifyObservers(hit);
  79936. this._currentMeshSelected = hit.pickedMesh;
  79937. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  79938. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  79939. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  79940. this._isActionableMesh = true;
  79941. }
  79942. else {
  79943. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79944. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79945. this._isActionableMesh = false;
  79946. }
  79947. try {
  79948. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  79949. }
  79950. catch (err) {
  79951. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  79952. }
  79953. }
  79954. else {
  79955. this._notifySelectedMeshUnselected();
  79956. this._currentMeshSelected = null;
  79957. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79958. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79959. }
  79960. }
  79961. }
  79962. else {
  79963. this._currentHit = null;
  79964. this._notifySelectedMeshUnselected();
  79965. this._currentMeshSelected = null;
  79966. this._teleportationAllowed = false;
  79967. this._hideTeleportationTarget();
  79968. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79969. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79970. }
  79971. };
  79972. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  79973. if (this._currentMeshSelected) {
  79974. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  79975. }
  79976. };
  79977. /**
  79978. * Sets the color of the laser ray from the vr controllers.
  79979. * @param color new color for the ray.
  79980. */
  79981. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  79982. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  79983. this._leftLaserPointer.material.emissiveColor = color;
  79984. }
  79985. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  79986. this._rightLaserPointer.material.emissiveColor = color;
  79987. }
  79988. };
  79989. /**
  79990. * Sets the color of the ray from the vr headsets gaze.
  79991. * @param color new color for the ray.
  79992. */
  79993. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  79994. if (this._gazeTracker.material) {
  79995. this._gazeTracker.material.emissiveColor = color;
  79996. }
  79997. };
  79998. /**
  79999. * Exits VR and disposes of the vr experience helper
  80000. */
  80001. VRExperienceHelper.prototype.dispose = function () {
  80002. if (this.isInVRMode) {
  80003. this.exitVR();
  80004. }
  80005. if (this._passProcessMove) {
  80006. this._passProcessMove.dispose();
  80007. }
  80008. if (this._postProcessMove) {
  80009. this._postProcessMove.dispose();
  80010. }
  80011. if (this._webVRCamera) {
  80012. this._webVRCamera.dispose();
  80013. }
  80014. if (this._vrDeviceOrientationCamera) {
  80015. this._vrDeviceOrientationCamera.dispose();
  80016. }
  80017. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  80018. document.body.removeChild(this._btnVR);
  80019. }
  80020. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  80021. this._deviceOrientationCamera.dispose();
  80022. }
  80023. if (this._gazeTracker) {
  80024. this._gazeTracker.dispose();
  80025. }
  80026. if (this._teleportationTarget) {
  80027. this._teleportationTarget.dispose();
  80028. }
  80029. this._floorMeshesCollection = [];
  80030. document.removeEventListener("keydown", this._onKeyDown);
  80031. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80032. window.removeEventListener("resize", this._onResize);
  80033. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  80034. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  80035. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  80036. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  80037. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  80038. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  80039. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  80040. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80041. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  80042. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  80043. this._scene.unregisterBeforeRender(this.beforeRender);
  80044. };
  80045. /**
  80046. * Gets the name of the VRExperienceHelper class
  80047. * @returns "VRExperienceHelper"
  80048. */
  80049. VRExperienceHelper.prototype.getClassName = function () {
  80050. return "VRExperienceHelper";
  80051. };
  80052. return VRExperienceHelper;
  80053. }());
  80054. BABYLON.VRExperienceHelper = VRExperienceHelper;
  80055. })(BABYLON || (BABYLON = {}));
  80056. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  80057. // Mainly based on these 2 articles :
  80058. // 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
  80059. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  80060. var BABYLON;
  80061. (function (BABYLON) {
  80062. var JoystickAxis;
  80063. (function (JoystickAxis) {
  80064. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  80065. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  80066. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  80067. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  80068. var VirtualJoystick = /** @class */ (function () {
  80069. function VirtualJoystick(leftJoystick) {
  80070. var _this = this;
  80071. if (leftJoystick) {
  80072. this._leftJoystick = true;
  80073. }
  80074. else {
  80075. this._leftJoystick = false;
  80076. }
  80077. VirtualJoystick._globalJoystickIndex++;
  80078. // By default left & right arrow keys are moving the X
  80079. // and up & down keys are moving the Y
  80080. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80081. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80082. this.reverseLeftRight = false;
  80083. this.reverseUpDown = false;
  80084. // collections of pointers
  80085. this._touches = new BABYLON.StringDictionary();
  80086. this.deltaPosition = BABYLON.Vector3.Zero();
  80087. this._joystickSensibility = 25;
  80088. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80089. this._onResize = function (evt) {
  80090. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  80091. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  80092. if (VirtualJoystick.vjCanvas) {
  80093. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  80094. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  80095. }
  80096. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  80097. };
  80098. // injecting a canvas element on top of the canvas 3D game
  80099. if (!VirtualJoystick.vjCanvas) {
  80100. window.addEventListener("resize", this._onResize, false);
  80101. VirtualJoystick.vjCanvas = document.createElement("canvas");
  80102. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  80103. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  80104. VirtualJoystick.vjCanvas.width = window.innerWidth;
  80105. VirtualJoystick.vjCanvas.height = window.innerHeight;
  80106. VirtualJoystick.vjCanvas.style.width = "100%";
  80107. VirtualJoystick.vjCanvas.style.height = "100%";
  80108. VirtualJoystick.vjCanvas.style.position = "absolute";
  80109. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  80110. VirtualJoystick.vjCanvas.style.top = "0px";
  80111. VirtualJoystick.vjCanvas.style.left = "0px";
  80112. VirtualJoystick.vjCanvas.style.zIndex = "5";
  80113. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  80114. // Support for jQuery PEP polyfill
  80115. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  80116. var context = VirtualJoystick.vjCanvas.getContext('2d');
  80117. if (!context) {
  80118. throw new Error("Unable to create canvas for virtual joystick");
  80119. }
  80120. VirtualJoystick.vjCanvasContext = context;
  80121. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  80122. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80123. document.body.appendChild(VirtualJoystick.vjCanvas);
  80124. }
  80125. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  80126. this.pressed = false;
  80127. // default joystick color
  80128. this._joystickColor = "cyan";
  80129. this._joystickPointerID = -1;
  80130. // current joystick position
  80131. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  80132. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  80133. // origin joystick position
  80134. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  80135. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  80136. this._onPointerDownHandlerRef = function (evt) {
  80137. _this._onPointerDown(evt);
  80138. };
  80139. this._onPointerMoveHandlerRef = function (evt) {
  80140. _this._onPointerMove(evt);
  80141. };
  80142. this._onPointerUpHandlerRef = function (evt) {
  80143. _this._onPointerUp(evt);
  80144. };
  80145. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  80146. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  80147. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  80148. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  80149. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  80150. evt.preventDefault(); // Disables system menu
  80151. }, false);
  80152. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80153. }
  80154. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  80155. this._joystickSensibility = newJoystickSensibility;
  80156. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80157. };
  80158. VirtualJoystick.prototype._onPointerDown = function (e) {
  80159. var positionOnScreenCondition;
  80160. e.preventDefault();
  80161. if (this._leftJoystick === true) {
  80162. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  80163. }
  80164. else {
  80165. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  80166. }
  80167. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  80168. // First contact will be dedicated to the virtual joystick
  80169. this._joystickPointerID = e.pointerId;
  80170. this._joystickPointerStartPos.x = e.clientX;
  80171. this._joystickPointerStartPos.y = e.clientY;
  80172. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  80173. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  80174. this._deltaJoystickVector.x = 0;
  80175. this._deltaJoystickVector.y = 0;
  80176. this.pressed = true;
  80177. this._touches.add(e.pointerId.toString(), e);
  80178. }
  80179. else {
  80180. // You can only trigger the action buttons with a joystick declared
  80181. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  80182. this._action();
  80183. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  80184. }
  80185. }
  80186. };
  80187. VirtualJoystick.prototype._onPointerMove = function (e) {
  80188. // If the current pointer is the one associated to the joystick (first touch contact)
  80189. if (this._joystickPointerID == e.pointerId) {
  80190. this._joystickPointerPos.x = e.clientX;
  80191. this._joystickPointerPos.y = e.clientY;
  80192. this._deltaJoystickVector = this._joystickPointerPos.clone();
  80193. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  80194. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  80195. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  80196. switch (this._axisTargetedByLeftAndRight) {
  80197. case JoystickAxis.X:
  80198. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  80199. break;
  80200. case JoystickAxis.Y:
  80201. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  80202. break;
  80203. case JoystickAxis.Z:
  80204. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  80205. break;
  80206. }
  80207. var directionUpDown = this.reverseUpDown ? 1 : -1;
  80208. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  80209. switch (this._axisTargetedByUpAndDown) {
  80210. case JoystickAxis.X:
  80211. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  80212. break;
  80213. case JoystickAxis.Y:
  80214. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  80215. break;
  80216. case JoystickAxis.Z:
  80217. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  80218. break;
  80219. }
  80220. }
  80221. else {
  80222. var data = this._touches.get(e.pointerId.toString());
  80223. if (data) {
  80224. data.x = e.clientX;
  80225. data.y = e.clientY;
  80226. }
  80227. }
  80228. };
  80229. VirtualJoystick.prototype._onPointerUp = function (e) {
  80230. if (this._joystickPointerID == e.pointerId) {
  80231. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  80232. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  80233. this._joystickPointerID = -1;
  80234. this.pressed = false;
  80235. }
  80236. else {
  80237. var touch = this._touches.get(e.pointerId.toString());
  80238. if (touch) {
  80239. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80240. }
  80241. }
  80242. this._deltaJoystickVector.x = 0;
  80243. this._deltaJoystickVector.y = 0;
  80244. this._touches.remove(e.pointerId.toString());
  80245. };
  80246. /**
  80247. * Change the color of the virtual joystick
  80248. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  80249. */
  80250. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  80251. this._joystickColor = newColor;
  80252. };
  80253. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  80254. this._action = action;
  80255. };
  80256. // Define which axis you'd like to control for left & right
  80257. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  80258. switch (axis) {
  80259. case JoystickAxis.X:
  80260. case JoystickAxis.Y:
  80261. case JoystickAxis.Z:
  80262. this._axisTargetedByLeftAndRight = axis;
  80263. break;
  80264. default:
  80265. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80266. break;
  80267. }
  80268. };
  80269. // Define which axis you'd like to control for up & down
  80270. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  80271. switch (axis) {
  80272. case JoystickAxis.X:
  80273. case JoystickAxis.Y:
  80274. case JoystickAxis.Z:
  80275. this._axisTargetedByUpAndDown = axis;
  80276. break;
  80277. default:
  80278. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80279. break;
  80280. }
  80281. };
  80282. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  80283. var _this = this;
  80284. if (this.pressed) {
  80285. this._touches.forEach(function (key, touch) {
  80286. if (touch.pointerId === _this._joystickPointerID) {
  80287. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  80288. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  80289. VirtualJoystick.vjCanvasContext.beginPath();
  80290. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80291. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80292. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  80293. VirtualJoystick.vjCanvasContext.stroke();
  80294. VirtualJoystick.vjCanvasContext.closePath();
  80295. VirtualJoystick.vjCanvasContext.beginPath();
  80296. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80297. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80298. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  80299. VirtualJoystick.vjCanvasContext.stroke();
  80300. VirtualJoystick.vjCanvasContext.closePath();
  80301. VirtualJoystick.vjCanvasContext.beginPath();
  80302. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80303. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  80304. VirtualJoystick.vjCanvasContext.stroke();
  80305. VirtualJoystick.vjCanvasContext.closePath();
  80306. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  80307. }
  80308. else {
  80309. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80310. VirtualJoystick.vjCanvasContext.beginPath();
  80311. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  80312. VirtualJoystick.vjCanvasContext.beginPath();
  80313. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  80314. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80315. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  80316. VirtualJoystick.vjCanvasContext.stroke();
  80317. VirtualJoystick.vjCanvasContext.closePath();
  80318. touch.prevX = touch.x;
  80319. touch.prevY = touch.y;
  80320. }
  80321. ;
  80322. });
  80323. }
  80324. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80325. };
  80326. VirtualJoystick.prototype.releaseCanvas = function () {
  80327. if (VirtualJoystick.vjCanvas) {
  80328. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  80329. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  80330. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  80331. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  80332. window.removeEventListener("resize", this._onResize);
  80333. document.body.removeChild(VirtualJoystick.vjCanvas);
  80334. VirtualJoystick.vjCanvas = null;
  80335. }
  80336. };
  80337. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  80338. VirtualJoystick._globalJoystickIndex = 0;
  80339. return VirtualJoystick;
  80340. }());
  80341. BABYLON.VirtualJoystick = VirtualJoystick;
  80342. })(BABYLON || (BABYLON = {}));
  80343. //# sourceMappingURL=babylon.virtualJoystick.js.map
  80344. var BABYLON;
  80345. (function (BABYLON) {
  80346. // We're mainly based on the logic defined into the FreeCamera code
  80347. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  80348. __extends(VirtualJoysticksCamera, _super);
  80349. function VirtualJoysticksCamera(name, position, scene) {
  80350. var _this = _super.call(this, name, position, scene) || this;
  80351. _this.inputs.addVirtualJoystick();
  80352. return _this;
  80353. }
  80354. VirtualJoysticksCamera.prototype.getClassName = function () {
  80355. return "VirtualJoysticksCamera";
  80356. };
  80357. return VirtualJoysticksCamera;
  80358. }(BABYLON.FreeCamera));
  80359. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  80360. })(BABYLON || (BABYLON = {}));
  80361. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  80362. var BABYLON;
  80363. (function (BABYLON) {
  80364. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  80365. function FreeCameraVirtualJoystickInput() {
  80366. }
  80367. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  80368. return this._leftjoystick;
  80369. };
  80370. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  80371. return this._rightjoystick;
  80372. };
  80373. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  80374. if (this._leftjoystick) {
  80375. var camera = this.camera;
  80376. var speed = camera._computeLocalCameraSpeed() * 50;
  80377. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  80378. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  80379. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  80380. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  80381. if (!this._leftjoystick.pressed) {
  80382. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  80383. }
  80384. if (!this._rightjoystick.pressed) {
  80385. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  80386. }
  80387. }
  80388. };
  80389. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  80390. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  80391. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  80392. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  80393. this._leftjoystick.setJoystickSensibility(0.15);
  80394. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  80395. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  80396. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  80397. this._rightjoystick.reverseUpDown = true;
  80398. this._rightjoystick.setJoystickSensibility(0.05);
  80399. this._rightjoystick.setJoystickColor("yellow");
  80400. };
  80401. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  80402. this._leftjoystick.releaseCanvas();
  80403. this._rightjoystick.releaseCanvas();
  80404. };
  80405. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  80406. return "FreeCameraVirtualJoystickInput";
  80407. };
  80408. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  80409. return "virtualJoystick";
  80410. };
  80411. return FreeCameraVirtualJoystickInput;
  80412. }());
  80413. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  80414. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  80415. })(BABYLON || (BABYLON = {}));
  80416. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  80417. var BABYLON;
  80418. (function (BABYLON) {
  80419. var SimplificationSettings = /** @class */ (function () {
  80420. function SimplificationSettings(quality, distance, optimizeMesh) {
  80421. this.quality = quality;
  80422. this.distance = distance;
  80423. this.optimizeMesh = optimizeMesh;
  80424. }
  80425. return SimplificationSettings;
  80426. }());
  80427. BABYLON.SimplificationSettings = SimplificationSettings;
  80428. var SimplificationQueue = /** @class */ (function () {
  80429. function SimplificationQueue() {
  80430. this.running = false;
  80431. this._simplificationArray = [];
  80432. }
  80433. SimplificationQueue.prototype.addTask = function (task) {
  80434. this._simplificationArray.push(task);
  80435. };
  80436. SimplificationQueue.prototype.executeNext = function () {
  80437. var task = this._simplificationArray.pop();
  80438. if (task) {
  80439. this.running = true;
  80440. this.runSimplification(task);
  80441. }
  80442. else {
  80443. this.running = false;
  80444. }
  80445. };
  80446. SimplificationQueue.prototype.runSimplification = function (task) {
  80447. var _this = this;
  80448. if (task.parallelProcessing) {
  80449. //parallel simplifier
  80450. task.settings.forEach(function (setting) {
  80451. var simplifier = _this.getSimplifier(task);
  80452. simplifier.simplify(setting, function (newMesh) {
  80453. task.mesh.addLODLevel(setting.distance, newMesh);
  80454. newMesh.isVisible = true;
  80455. //check if it is the last
  80456. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  80457. //all done, run the success callback.
  80458. task.successCallback();
  80459. }
  80460. _this.executeNext();
  80461. });
  80462. });
  80463. }
  80464. else {
  80465. //single simplifier.
  80466. var simplifier = this.getSimplifier(task);
  80467. var runDecimation = function (setting, callback) {
  80468. simplifier.simplify(setting, function (newMesh) {
  80469. task.mesh.addLODLevel(setting.distance, newMesh);
  80470. newMesh.isVisible = true;
  80471. //run the next quality level
  80472. callback();
  80473. });
  80474. };
  80475. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  80476. runDecimation(task.settings[loop.index], function () {
  80477. loop.executeNext();
  80478. });
  80479. }, function () {
  80480. //execution ended, run the success callback.
  80481. if (task.successCallback) {
  80482. task.successCallback();
  80483. }
  80484. _this.executeNext();
  80485. });
  80486. }
  80487. };
  80488. SimplificationQueue.prototype.getSimplifier = function (task) {
  80489. switch (task.simplificationType) {
  80490. case SimplificationType.QUADRATIC:
  80491. default:
  80492. return new QuadraticErrorSimplification(task.mesh);
  80493. }
  80494. };
  80495. return SimplificationQueue;
  80496. }());
  80497. BABYLON.SimplificationQueue = SimplificationQueue;
  80498. /**
  80499. * The implemented types of simplification.
  80500. * At the moment only Quadratic Error Decimation is implemented.
  80501. */
  80502. var SimplificationType;
  80503. (function (SimplificationType) {
  80504. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  80505. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  80506. var DecimationTriangle = /** @class */ (function () {
  80507. function DecimationTriangle(vertices) {
  80508. this.vertices = vertices;
  80509. this.error = new Array(4);
  80510. this.deleted = false;
  80511. this.isDirty = false;
  80512. this.deletePending = false;
  80513. this.borderFactor = 0;
  80514. }
  80515. return DecimationTriangle;
  80516. }());
  80517. BABYLON.DecimationTriangle = DecimationTriangle;
  80518. var DecimationVertex = /** @class */ (function () {
  80519. function DecimationVertex(position, id) {
  80520. this.position = position;
  80521. this.id = id;
  80522. this.isBorder = true;
  80523. this.q = new QuadraticMatrix();
  80524. this.triangleCount = 0;
  80525. this.triangleStart = 0;
  80526. this.originalOffsets = [];
  80527. }
  80528. DecimationVertex.prototype.updatePosition = function (newPosition) {
  80529. this.position.copyFrom(newPosition);
  80530. };
  80531. return DecimationVertex;
  80532. }());
  80533. BABYLON.DecimationVertex = DecimationVertex;
  80534. var QuadraticMatrix = /** @class */ (function () {
  80535. function QuadraticMatrix(data) {
  80536. this.data = new Array(10);
  80537. for (var i = 0; i < 10; ++i) {
  80538. if (data && data[i]) {
  80539. this.data[i] = data[i];
  80540. }
  80541. else {
  80542. this.data[i] = 0;
  80543. }
  80544. }
  80545. }
  80546. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  80547. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  80548. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  80549. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  80550. return det;
  80551. };
  80552. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  80553. for (var i = 0; i < 10; ++i) {
  80554. this.data[i] += matrix.data[i];
  80555. }
  80556. };
  80557. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  80558. for (var i = 0; i < 10; ++i) {
  80559. this.data[i] += data[i];
  80560. }
  80561. };
  80562. QuadraticMatrix.prototype.add = function (matrix) {
  80563. var m = new QuadraticMatrix();
  80564. for (var i = 0; i < 10; ++i) {
  80565. m.data[i] = this.data[i] + matrix.data[i];
  80566. }
  80567. return m;
  80568. };
  80569. QuadraticMatrix.FromData = function (a, b, c, d) {
  80570. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  80571. };
  80572. //returning an array to avoid garbage collection
  80573. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  80574. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  80575. };
  80576. return QuadraticMatrix;
  80577. }());
  80578. BABYLON.QuadraticMatrix = QuadraticMatrix;
  80579. var Reference = /** @class */ (function () {
  80580. function Reference(vertexId, triangleId) {
  80581. this.vertexId = vertexId;
  80582. this.triangleId = triangleId;
  80583. }
  80584. return Reference;
  80585. }());
  80586. BABYLON.Reference = Reference;
  80587. /**
  80588. * An implementation of the Quadratic Error simplification algorithm.
  80589. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  80590. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  80591. * @author RaananW
  80592. */
  80593. var QuadraticErrorSimplification = /** @class */ (function () {
  80594. function QuadraticErrorSimplification(_mesh) {
  80595. this._mesh = _mesh;
  80596. this.syncIterations = 5000;
  80597. this.aggressiveness = 7;
  80598. this.decimationIterations = 100;
  80599. this.boundingBoxEpsilon = BABYLON.Epsilon;
  80600. }
  80601. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  80602. var _this = this;
  80603. this.initDecimatedMesh();
  80604. //iterating through the submeshes array, one after the other.
  80605. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  80606. _this.initWithMesh(loop.index, function () {
  80607. _this.runDecimation(settings, loop.index, function () {
  80608. loop.executeNext();
  80609. });
  80610. }, settings.optimizeMesh);
  80611. }, function () {
  80612. setTimeout(function () {
  80613. successCallback(_this._reconstructedMesh);
  80614. }, 0);
  80615. });
  80616. };
  80617. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  80618. var _this = this;
  80619. var targetCount = ~~(this.triangles.length * settings.quality);
  80620. var deletedTriangles = 0;
  80621. var triangleCount = this.triangles.length;
  80622. var iterationFunction = function (iteration, callback) {
  80623. setTimeout(function () {
  80624. if (iteration % 5 === 0) {
  80625. _this.updateMesh(iteration === 0);
  80626. }
  80627. for (var i = 0; i < _this.triangles.length; ++i) {
  80628. _this.triangles[i].isDirty = false;
  80629. }
  80630. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  80631. var trianglesIterator = function (i) {
  80632. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  80633. var t = _this.triangles[tIdx];
  80634. if (!t)
  80635. return;
  80636. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  80637. return;
  80638. }
  80639. for (var j = 0; j < 3; ++j) {
  80640. if (t.error[j] < threshold) {
  80641. var deleted0 = [];
  80642. var deleted1 = [];
  80643. var v0 = t.vertices[j];
  80644. var v1 = t.vertices[(j + 1) % 3];
  80645. if (v0.isBorder || v1.isBorder)
  80646. continue;
  80647. var p = BABYLON.Vector3.Zero();
  80648. var n = BABYLON.Vector3.Zero();
  80649. var uv = BABYLON.Vector2.Zero();
  80650. var color = new BABYLON.Color4(0, 0, 0, 1);
  80651. _this.calculateError(v0, v1, p, n, uv, color);
  80652. var delTr = new Array();
  80653. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  80654. continue;
  80655. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  80656. continue;
  80657. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  80658. continue;
  80659. var uniqueArray = new Array();
  80660. delTr.forEach(function (deletedT) {
  80661. if (uniqueArray.indexOf(deletedT) === -1) {
  80662. deletedT.deletePending = true;
  80663. uniqueArray.push(deletedT);
  80664. }
  80665. });
  80666. if (uniqueArray.length % 2 !== 0) {
  80667. continue;
  80668. }
  80669. v0.q = v1.q.add(v0.q);
  80670. v0.updatePosition(p);
  80671. var tStart = _this.references.length;
  80672. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  80673. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  80674. var tCount = _this.references.length - tStart;
  80675. if (tCount <= v0.triangleCount) {
  80676. if (tCount) {
  80677. for (var c = 0; c < tCount; c++) {
  80678. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  80679. }
  80680. }
  80681. }
  80682. else {
  80683. v0.triangleStart = tStart;
  80684. }
  80685. v0.triangleCount = tCount;
  80686. break;
  80687. }
  80688. }
  80689. };
  80690. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  80691. }, 0);
  80692. };
  80693. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  80694. if (triangleCount - deletedTriangles <= targetCount)
  80695. loop.breakLoop();
  80696. else {
  80697. iterationFunction(loop.index, function () {
  80698. loop.executeNext();
  80699. });
  80700. }
  80701. }, function () {
  80702. setTimeout(function () {
  80703. //reconstruct this part of the mesh
  80704. _this.reconstructMesh(submeshIndex);
  80705. successCallback();
  80706. }, 0);
  80707. });
  80708. };
  80709. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  80710. var _this = this;
  80711. this.vertices = [];
  80712. this.triangles = [];
  80713. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  80714. var indices = this._mesh.getIndices();
  80715. var submesh = this._mesh.subMeshes[submeshIndex];
  80716. var findInVertices = function (positionToSearch) {
  80717. if (optimizeMesh) {
  80718. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  80719. if (_this.vertices[ii].position.equals(positionToSearch)) {
  80720. return _this.vertices[ii];
  80721. }
  80722. }
  80723. }
  80724. return null;
  80725. };
  80726. var vertexReferences = [];
  80727. var vertexInit = function (i) {
  80728. if (!positionData) {
  80729. return;
  80730. }
  80731. var offset = i + submesh.verticesStart;
  80732. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  80733. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  80734. vertex.originalOffsets.push(offset);
  80735. if (vertex.id === _this.vertices.length) {
  80736. _this.vertices.push(vertex);
  80737. }
  80738. vertexReferences.push(vertex.id);
  80739. };
  80740. //var totalVertices = mesh.getTotalVertices();
  80741. var totalVertices = submesh.verticesCount;
  80742. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  80743. var indicesInit = function (i) {
  80744. if (!indices) {
  80745. return;
  80746. }
  80747. var offset = (submesh.indexStart / 3) + i;
  80748. var pos = (offset * 3);
  80749. var i0 = indices[pos + 0];
  80750. var i1 = indices[pos + 1];
  80751. var i2 = indices[pos + 2];
  80752. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  80753. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  80754. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  80755. var triangle = new DecimationTriangle([v0, v1, v2]);
  80756. triangle.originalOffset = pos;
  80757. _this.triangles.push(triangle);
  80758. };
  80759. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  80760. _this.init(callback);
  80761. });
  80762. });
  80763. };
  80764. QuadraticErrorSimplification.prototype.init = function (callback) {
  80765. var _this = this;
  80766. var triangleInit1 = function (i) {
  80767. var t = _this.triangles[i];
  80768. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  80769. for (var j = 0; j < 3; j++) {
  80770. 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))));
  80771. }
  80772. };
  80773. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  80774. var triangleInit2 = function (i) {
  80775. var t = _this.triangles[i];
  80776. for (var j = 0; j < 3; ++j) {
  80777. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  80778. }
  80779. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80780. };
  80781. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  80782. callback();
  80783. });
  80784. });
  80785. };
  80786. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  80787. var newTriangles = [];
  80788. var i;
  80789. for (i = 0; i < this.vertices.length; ++i) {
  80790. this.vertices[i].triangleCount = 0;
  80791. }
  80792. var t;
  80793. var j;
  80794. for (i = 0; i < this.triangles.length; ++i) {
  80795. if (!this.triangles[i].deleted) {
  80796. t = this.triangles[i];
  80797. for (j = 0; j < 3; ++j) {
  80798. t.vertices[j].triangleCount = 1;
  80799. }
  80800. newTriangles.push(t);
  80801. }
  80802. }
  80803. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  80804. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  80805. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  80806. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  80807. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  80808. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80809. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  80810. var vertexCount = 0;
  80811. for (i = 0; i < this.vertices.length; ++i) {
  80812. var vertex = this.vertices[i];
  80813. vertex.id = vertexCount;
  80814. if (vertex.triangleCount) {
  80815. vertex.originalOffsets.forEach(function (originalOffset) {
  80816. if (!normalData) {
  80817. return;
  80818. }
  80819. newPositionData.push(vertex.position.x);
  80820. newPositionData.push(vertex.position.y);
  80821. newPositionData.push(vertex.position.z);
  80822. newNormalData.push(normalData[originalOffset * 3]);
  80823. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  80824. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  80825. if (uvs && uvs.length) {
  80826. newUVsData.push(uvs[(originalOffset * 2)]);
  80827. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  80828. }
  80829. else if (colorsData && colorsData.length) {
  80830. newColorsData.push(colorsData[(originalOffset * 4)]);
  80831. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  80832. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  80833. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  80834. }
  80835. ++vertexCount;
  80836. });
  80837. }
  80838. }
  80839. var startingIndex = this._reconstructedMesh.getTotalIndices();
  80840. var startingVertex = this._reconstructedMesh.getTotalVertices();
  80841. var submeshesArray = this._reconstructedMesh.subMeshes;
  80842. this._reconstructedMesh.subMeshes = [];
  80843. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  80844. var originalIndices = this._mesh.getIndices();
  80845. for (i = 0; i < newTriangles.length; ++i) {
  80846. t = newTriangles[i]; //now get the new referencing point for each vertex
  80847. [0, 1, 2].forEach(function (idx) {
  80848. var id = originalIndices[t.originalOffset + idx];
  80849. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  80850. if (offset < 0)
  80851. offset = 0;
  80852. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  80853. });
  80854. }
  80855. //overwriting the old vertex buffers and indices.
  80856. this._reconstructedMesh.setIndices(newIndicesArray);
  80857. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  80858. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  80859. if (newUVsData.length > 0)
  80860. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  80861. if (newColorsData.length > 0)
  80862. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  80863. //create submesh
  80864. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  80865. if (submeshIndex > 0) {
  80866. this._reconstructedMesh.subMeshes = [];
  80867. submeshesArray.forEach(function (submesh) {
  80868. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  80869. });
  80870. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  80871. }
  80872. };
  80873. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  80874. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  80875. this._reconstructedMesh.material = this._mesh.material;
  80876. this._reconstructedMesh.parent = this._mesh.parent;
  80877. this._reconstructedMesh.isVisible = false;
  80878. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  80879. };
  80880. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  80881. for (var i = 0; i < vertex1.triangleCount; ++i) {
  80882. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  80883. if (t.deleted)
  80884. continue;
  80885. var s = this.references[vertex1.triangleStart + i].vertexId;
  80886. var v1 = t.vertices[(s + 1) % 3];
  80887. var v2 = t.vertices[(s + 2) % 3];
  80888. if ((v1 === vertex2 || v2 === vertex2)) {
  80889. deletedArray[i] = true;
  80890. delTr.push(t);
  80891. continue;
  80892. }
  80893. var d1 = v1.position.subtract(point);
  80894. d1 = d1.normalize();
  80895. var d2 = v2.position.subtract(point);
  80896. d2 = d2.normalize();
  80897. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  80898. return true;
  80899. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  80900. deletedArray[i] = false;
  80901. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  80902. return true;
  80903. }
  80904. return false;
  80905. };
  80906. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  80907. var newDeleted = deletedTriangles;
  80908. for (var i = 0; i < vertex.triangleCount; ++i) {
  80909. var ref = this.references[vertex.triangleStart + i];
  80910. var t = this.triangles[ref.triangleId];
  80911. if (t.deleted)
  80912. continue;
  80913. if (deletedArray[i] && t.deletePending) {
  80914. t.deleted = true;
  80915. newDeleted++;
  80916. continue;
  80917. }
  80918. t.vertices[ref.vertexId] = origVertex;
  80919. t.isDirty = true;
  80920. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  80921. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  80922. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  80923. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80924. this.references.push(ref);
  80925. }
  80926. return newDeleted;
  80927. };
  80928. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  80929. for (var i = 0; i < this.vertices.length; ++i) {
  80930. var vCount = [];
  80931. var vId = [];
  80932. var v = this.vertices[i];
  80933. var j;
  80934. for (j = 0; j < v.triangleCount; ++j) {
  80935. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  80936. for (var ii = 0; ii < 3; ii++) {
  80937. var ofs = 0;
  80938. var vv = triangle.vertices[ii];
  80939. while (ofs < vCount.length) {
  80940. if (vId[ofs] === vv.id)
  80941. break;
  80942. ++ofs;
  80943. }
  80944. if (ofs === vCount.length) {
  80945. vCount.push(1);
  80946. vId.push(vv.id);
  80947. }
  80948. else {
  80949. vCount[ofs]++;
  80950. }
  80951. }
  80952. }
  80953. for (j = 0; j < vCount.length; ++j) {
  80954. if (vCount[j] === 1) {
  80955. this.vertices[vId[j]].isBorder = true;
  80956. }
  80957. else {
  80958. this.vertices[vId[j]].isBorder = false;
  80959. }
  80960. }
  80961. }
  80962. };
  80963. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  80964. if (identifyBorders === void 0) { identifyBorders = false; }
  80965. var i;
  80966. if (!identifyBorders) {
  80967. var newTrianglesVector = [];
  80968. for (i = 0; i < this.triangles.length; ++i) {
  80969. if (!this.triangles[i].deleted) {
  80970. newTrianglesVector.push(this.triangles[i]);
  80971. }
  80972. }
  80973. this.triangles = newTrianglesVector;
  80974. }
  80975. for (i = 0; i < this.vertices.length; ++i) {
  80976. this.vertices[i].triangleCount = 0;
  80977. this.vertices[i].triangleStart = 0;
  80978. }
  80979. var t;
  80980. var j;
  80981. var v;
  80982. for (i = 0; i < this.triangles.length; ++i) {
  80983. t = this.triangles[i];
  80984. for (j = 0; j < 3; ++j) {
  80985. v = t.vertices[j];
  80986. v.triangleCount++;
  80987. }
  80988. }
  80989. var tStart = 0;
  80990. for (i = 0; i < this.vertices.length; ++i) {
  80991. this.vertices[i].triangleStart = tStart;
  80992. tStart += this.vertices[i].triangleCount;
  80993. this.vertices[i].triangleCount = 0;
  80994. }
  80995. var newReferences = new Array(this.triangles.length * 3);
  80996. for (i = 0; i < this.triangles.length; ++i) {
  80997. t = this.triangles[i];
  80998. for (j = 0; j < 3; ++j) {
  80999. v = t.vertices[j];
  81000. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  81001. v.triangleCount++;
  81002. }
  81003. }
  81004. this.references = newReferences;
  81005. if (identifyBorders) {
  81006. this.identifyBorder();
  81007. }
  81008. };
  81009. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  81010. var x = point.x;
  81011. var y = point.y;
  81012. var z = point.z;
  81013. 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
  81014. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  81015. };
  81016. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  81017. var q = vertex1.q.add(vertex2.q);
  81018. var border = vertex1.isBorder && vertex2.isBorder;
  81019. var error = 0;
  81020. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  81021. if (qDet !== 0 && !border) {
  81022. if (!pointResult) {
  81023. pointResult = BABYLON.Vector3.Zero();
  81024. }
  81025. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  81026. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  81027. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  81028. error = this.vertexError(q, pointResult);
  81029. }
  81030. else {
  81031. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  81032. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  81033. var error1 = this.vertexError(q, vertex1.position);
  81034. var error2 = this.vertexError(q, vertex2.position);
  81035. var error3 = this.vertexError(q, p3);
  81036. error = Math.min(error1, error2, error3);
  81037. if (error === error1) {
  81038. if (pointResult) {
  81039. pointResult.copyFrom(vertex1.position);
  81040. }
  81041. }
  81042. else if (error === error2) {
  81043. if (pointResult) {
  81044. pointResult.copyFrom(vertex2.position);
  81045. }
  81046. }
  81047. else {
  81048. if (pointResult) {
  81049. pointResult.copyFrom(p3);
  81050. }
  81051. }
  81052. }
  81053. return error;
  81054. };
  81055. return QuadraticErrorSimplification;
  81056. }());
  81057. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  81058. })(BABYLON || (BABYLON = {}));
  81059. //# sourceMappingURL=babylon.meshSimplification.js.map
  81060. var BABYLON;
  81061. (function (BABYLON) {
  81062. var MeshLODLevel = /** @class */ (function () {
  81063. function MeshLODLevel(distance, mesh) {
  81064. this.distance = distance;
  81065. this.mesh = mesh;
  81066. }
  81067. return MeshLODLevel;
  81068. }());
  81069. BABYLON.MeshLODLevel = MeshLODLevel;
  81070. })(BABYLON || (BABYLON = {}));
  81071. //# sourceMappingURL=babylon.meshLODLevel.js.map
  81072. var BABYLON;
  81073. (function (BABYLON) {
  81074. /**
  81075. * Defines the root class used to create scene optimization to use with SceneOptimizer
  81076. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81077. */
  81078. var SceneOptimization = /** @class */ (function () {
  81079. /**
  81080. * Creates the SceneOptimization object
  81081. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81082. * @param desc defines the description associated with the optimization
  81083. */
  81084. function SceneOptimization(
  81085. /**
  81086. * Defines the priority of this optimization (0 by default which means first in the list)
  81087. */
  81088. priority) {
  81089. if (priority === void 0) { priority = 0; }
  81090. this.priority = priority;
  81091. }
  81092. /**
  81093. * Gets a string describing the action executed by the current optimization
  81094. * @returns description string
  81095. */
  81096. SceneOptimization.prototype.getDescription = function () {
  81097. return "";
  81098. };
  81099. /**
  81100. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81101. * @param scene defines the current scene where to apply this optimization
  81102. * @param optimizer defines the current optimizer
  81103. * @returns true if everything that can be done was applied
  81104. */
  81105. SceneOptimization.prototype.apply = function (scene, optimizer) {
  81106. return true;
  81107. };
  81108. ;
  81109. return SceneOptimization;
  81110. }());
  81111. BABYLON.SceneOptimization = SceneOptimization;
  81112. /**
  81113. * Defines an optimization used to reduce the size of render target textures
  81114. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81115. */
  81116. var TextureOptimization = /** @class */ (function (_super) {
  81117. __extends(TextureOptimization, _super);
  81118. /**
  81119. * Creates the TextureOptimization object
  81120. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81121. * @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
  81122. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  81123. */
  81124. function TextureOptimization(
  81125. /**
  81126. * Defines the priority of this optimization (0 by default which means first in the list)
  81127. */
  81128. priority,
  81129. /**
  81130. * 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
  81131. */
  81132. maximumSize,
  81133. /**
  81134. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  81135. */
  81136. step) {
  81137. if (priority === void 0) { priority = 0; }
  81138. if (maximumSize === void 0) { maximumSize = 1024; }
  81139. if (step === void 0) { step = 0.5; }
  81140. var _this = _super.call(this, priority) || this;
  81141. _this.priority = priority;
  81142. _this.maximumSize = maximumSize;
  81143. _this.step = step;
  81144. return _this;
  81145. }
  81146. /**
  81147. * Gets a string describing the action executed by the current optimization
  81148. * @returns description string
  81149. */
  81150. TextureOptimization.prototype.getDescription = function () {
  81151. return "Reducing render target texture size to " + this.maximumSize;
  81152. };
  81153. /**
  81154. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81155. * @param scene defines the current scene where to apply this optimization
  81156. * @param optimizer defines the current optimizer
  81157. * @returns true if everything that can be done was applied
  81158. */
  81159. TextureOptimization.prototype.apply = function (scene, optimizer) {
  81160. var allDone = true;
  81161. for (var index = 0; index < scene.textures.length; index++) {
  81162. var texture = scene.textures[index];
  81163. if (!texture.canRescale || texture.getContext) {
  81164. continue;
  81165. }
  81166. var currentSize = texture.getSize();
  81167. var maxDimension = Math.max(currentSize.width, currentSize.height);
  81168. if (maxDimension > this.maximumSize) {
  81169. texture.scale(this.step);
  81170. allDone = false;
  81171. }
  81172. }
  81173. return allDone;
  81174. };
  81175. return TextureOptimization;
  81176. }(SceneOptimization));
  81177. BABYLON.TextureOptimization = TextureOptimization;
  81178. /**
  81179. * Defines an optimization used to increase or decrease the rendering resolution
  81180. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81181. */
  81182. var HardwareScalingOptimization = /** @class */ (function (_super) {
  81183. __extends(HardwareScalingOptimization, _super);
  81184. /**
  81185. * Creates the HardwareScalingOptimization object
  81186. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81187. * @param maximumScale defines the maximum scale to use (2 by default)
  81188. * @param step defines the step to use between two passes (0.5 by default)
  81189. */
  81190. function HardwareScalingOptimization(
  81191. /**
  81192. * Defines the priority of this optimization (0 by default which means first in the list)
  81193. */
  81194. priority,
  81195. /**
  81196. * Defines the maximum scale to use (2 by default)
  81197. */
  81198. maximumScale,
  81199. /**
  81200. * Defines the step to use between two passes (0.5 by default)
  81201. */
  81202. step) {
  81203. if (priority === void 0) { priority = 0; }
  81204. if (maximumScale === void 0) { maximumScale = 2; }
  81205. if (step === void 0) { step = 0.25; }
  81206. var _this = _super.call(this, priority) || this;
  81207. _this.priority = priority;
  81208. _this.maximumScale = maximumScale;
  81209. _this.step = step;
  81210. _this._currentScale = -1;
  81211. _this._directionOffset = 1;
  81212. return _this;
  81213. }
  81214. /**
  81215. * Gets a string describing the action executed by the current optimization
  81216. * @return description string
  81217. */
  81218. HardwareScalingOptimization.prototype.getDescription = function () {
  81219. return "Setting hardware scaling level to " + this._currentScale;
  81220. };
  81221. /**
  81222. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81223. * @param scene defines the current scene where to apply this optimization
  81224. * @param optimizer defines the current optimizer
  81225. * @returns true if everything that can be done was applied
  81226. */
  81227. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  81228. if (this._currentScale === -1) {
  81229. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  81230. if (this._currentScale > this.maximumScale) {
  81231. this._directionOffset = -1;
  81232. }
  81233. }
  81234. this._currentScale += this._directionOffset * this.step;
  81235. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  81236. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  81237. };
  81238. ;
  81239. return HardwareScalingOptimization;
  81240. }(SceneOptimization));
  81241. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  81242. /**
  81243. * Defines an optimization used to remove shadows
  81244. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81245. */
  81246. var ShadowsOptimization = /** @class */ (function (_super) {
  81247. __extends(ShadowsOptimization, _super);
  81248. function ShadowsOptimization() {
  81249. return _super !== null && _super.apply(this, arguments) || this;
  81250. }
  81251. /**
  81252. * Gets a string describing the action executed by the current optimization
  81253. * @return description string
  81254. */
  81255. ShadowsOptimization.prototype.getDescription = function () {
  81256. return "Turning shadows on/off";
  81257. };
  81258. /**
  81259. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81260. * @param scene defines the current scene where to apply this optimization
  81261. * @param optimizer defines the current optimizer
  81262. * @returns true if everything that can be done was applied
  81263. */
  81264. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  81265. scene.shadowsEnabled = optimizer.isInImprovementMode;
  81266. return true;
  81267. };
  81268. ;
  81269. return ShadowsOptimization;
  81270. }(SceneOptimization));
  81271. BABYLON.ShadowsOptimization = ShadowsOptimization;
  81272. /**
  81273. * Defines an optimization used to turn post-processes off
  81274. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81275. */
  81276. var PostProcessesOptimization = /** @class */ (function (_super) {
  81277. __extends(PostProcessesOptimization, _super);
  81278. function PostProcessesOptimization() {
  81279. return _super !== null && _super.apply(this, arguments) || this;
  81280. }
  81281. /**
  81282. * Gets a string describing the action executed by the current optimization
  81283. * @return description string
  81284. */
  81285. PostProcessesOptimization.prototype.getDescription = function () {
  81286. return "Turning post-processes on/off";
  81287. };
  81288. /**
  81289. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81290. * @param scene defines the current scene where to apply this optimization
  81291. * @param optimizer defines the current optimizer
  81292. * @returns true if everything that can be done was applied
  81293. */
  81294. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  81295. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  81296. return true;
  81297. };
  81298. ;
  81299. return PostProcessesOptimization;
  81300. }(SceneOptimization));
  81301. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  81302. /**
  81303. * Defines an optimization used to turn lens flares off
  81304. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81305. */
  81306. var LensFlaresOptimization = /** @class */ (function (_super) {
  81307. __extends(LensFlaresOptimization, _super);
  81308. function LensFlaresOptimization() {
  81309. return _super !== null && _super.apply(this, arguments) || this;
  81310. }
  81311. /**
  81312. * Gets a string describing the action executed by the current optimization
  81313. * @return description string
  81314. */
  81315. LensFlaresOptimization.prototype.getDescription = function () {
  81316. return "Turning lens flares on/off";
  81317. };
  81318. /**
  81319. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81320. * @param scene defines the current scene where to apply this optimization
  81321. * @param optimizer defines the current optimizer
  81322. * @returns true if everything that can be done was applied
  81323. */
  81324. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  81325. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  81326. return true;
  81327. };
  81328. ;
  81329. return LensFlaresOptimization;
  81330. }(SceneOptimization));
  81331. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  81332. /**
  81333. * Defines an optimization based on user defined callback.
  81334. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81335. */
  81336. var CustomOptimization = /** @class */ (function (_super) {
  81337. __extends(CustomOptimization, _super);
  81338. function CustomOptimization() {
  81339. return _super !== null && _super.apply(this, arguments) || this;
  81340. }
  81341. /**
  81342. * Gets a string describing the action executed by the current optimization
  81343. * @returns description string
  81344. */
  81345. CustomOptimization.prototype.getDescription = function () {
  81346. if (this.onGetDescription) {
  81347. return this.onGetDescription();
  81348. }
  81349. return "Running user defined callback";
  81350. };
  81351. /**
  81352. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81353. * @param scene defines the current scene where to apply this optimization
  81354. * @param optimizer defines the current optimizer
  81355. * @returns true if everything that can be done was applied
  81356. */
  81357. CustomOptimization.prototype.apply = function (scene, optimizer) {
  81358. if (this.onApply) {
  81359. return this.onApply(scene, optimizer);
  81360. }
  81361. return true;
  81362. };
  81363. ;
  81364. return CustomOptimization;
  81365. }(SceneOptimization));
  81366. BABYLON.CustomOptimization = CustomOptimization;
  81367. /**
  81368. * Defines an optimization used to turn particles off
  81369. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81370. */
  81371. var ParticlesOptimization = /** @class */ (function (_super) {
  81372. __extends(ParticlesOptimization, _super);
  81373. function ParticlesOptimization() {
  81374. return _super !== null && _super.apply(this, arguments) || this;
  81375. }
  81376. /**
  81377. * Gets a string describing the action executed by the current optimization
  81378. * @return description string
  81379. */
  81380. ParticlesOptimization.prototype.getDescription = function () {
  81381. return "Turning particles on/off";
  81382. };
  81383. /**
  81384. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81385. * @param scene defines the current scene where to apply this optimization
  81386. * @param optimizer defines the current optimizer
  81387. * @returns true if everything that can be done was applied
  81388. */
  81389. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  81390. scene.particlesEnabled = optimizer.isInImprovementMode;
  81391. return true;
  81392. };
  81393. ;
  81394. return ParticlesOptimization;
  81395. }(SceneOptimization));
  81396. BABYLON.ParticlesOptimization = ParticlesOptimization;
  81397. /**
  81398. * Defines an optimization used to turn render targets off
  81399. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81400. */
  81401. var RenderTargetsOptimization = /** @class */ (function (_super) {
  81402. __extends(RenderTargetsOptimization, _super);
  81403. function RenderTargetsOptimization() {
  81404. return _super !== null && _super.apply(this, arguments) || this;
  81405. }
  81406. /**
  81407. * Gets a string describing the action executed by the current optimization
  81408. * @return description string
  81409. */
  81410. RenderTargetsOptimization.prototype.getDescription = function () {
  81411. return "Turning render targets off";
  81412. };
  81413. /**
  81414. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81415. * @param scene defines the current scene where to apply this optimization
  81416. * @param optimizer defines the current optimizer
  81417. * @returns true if everything that can be done was applied
  81418. */
  81419. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  81420. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  81421. return true;
  81422. };
  81423. ;
  81424. return RenderTargetsOptimization;
  81425. }(SceneOptimization));
  81426. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  81427. /**
  81428. * Defines an optimization used to merge meshes with compatible materials
  81429. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81430. */
  81431. var MergeMeshesOptimization = /** @class */ (function (_super) {
  81432. __extends(MergeMeshesOptimization, _super);
  81433. function MergeMeshesOptimization() {
  81434. var _this = _super !== null && _super.apply(this, arguments) || this;
  81435. _this._canBeMerged = function (abstractMesh) {
  81436. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  81437. return false;
  81438. }
  81439. var mesh = abstractMesh;
  81440. if (!mesh.isVisible || !mesh.isEnabled()) {
  81441. return false;
  81442. }
  81443. if (mesh.instances.length > 0) {
  81444. return false;
  81445. }
  81446. if (mesh.skeleton || mesh.hasLODLevels) {
  81447. return false;
  81448. }
  81449. if (mesh.parent) {
  81450. return false;
  81451. }
  81452. return true;
  81453. };
  81454. return _this;
  81455. }
  81456. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  81457. /**
  81458. * Gets or sets a boolean which defines if optimization octree has to be updated
  81459. */
  81460. get: function () {
  81461. return MergeMeshesOptimization._UpdateSelectionTree;
  81462. },
  81463. /**
  81464. * Gets or sets a boolean which defines if optimization octree has to be updated
  81465. */
  81466. set: function (value) {
  81467. MergeMeshesOptimization._UpdateSelectionTree = value;
  81468. },
  81469. enumerable: true,
  81470. configurable: true
  81471. });
  81472. /**
  81473. * Gets a string describing the action executed by the current optimization
  81474. * @return description string
  81475. */
  81476. MergeMeshesOptimization.prototype.getDescription = function () {
  81477. return "Merging similar meshes together";
  81478. };
  81479. /**
  81480. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81481. * @param scene defines the current scene where to apply this optimization
  81482. * @param optimizer defines the current optimizer
  81483. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  81484. * @returns true if everything that can be done was applied
  81485. */
  81486. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  81487. var globalPool = scene.meshes.slice(0);
  81488. var globalLength = globalPool.length;
  81489. for (var index = 0; index < globalLength; index++) {
  81490. var currentPool = new Array();
  81491. var current = globalPool[index];
  81492. // Checks
  81493. if (!this._canBeMerged(current)) {
  81494. continue;
  81495. }
  81496. currentPool.push(current);
  81497. // Find compatible meshes
  81498. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  81499. var otherMesh = globalPool[subIndex];
  81500. if (!this._canBeMerged(otherMesh)) {
  81501. continue;
  81502. }
  81503. if (otherMesh.material !== current.material) {
  81504. continue;
  81505. }
  81506. if (otherMesh.checkCollisions !== current.checkCollisions) {
  81507. continue;
  81508. }
  81509. currentPool.push(otherMesh);
  81510. globalLength--;
  81511. globalPool.splice(subIndex, 1);
  81512. subIndex--;
  81513. }
  81514. if (currentPool.length < 2) {
  81515. continue;
  81516. }
  81517. // Merge meshes
  81518. BABYLON.Mesh.MergeMeshes(currentPool);
  81519. }
  81520. if (updateSelectionTree != undefined) {
  81521. if (updateSelectionTree) {
  81522. scene.createOrUpdateSelectionOctree();
  81523. }
  81524. }
  81525. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  81526. scene.createOrUpdateSelectionOctree();
  81527. }
  81528. return true;
  81529. };
  81530. ;
  81531. MergeMeshesOptimization._UpdateSelectionTree = false;
  81532. return MergeMeshesOptimization;
  81533. }(SceneOptimization));
  81534. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  81535. /**
  81536. * Defines a list of options used by SceneOptimizer
  81537. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81538. */
  81539. var SceneOptimizerOptions = /** @class */ (function () {
  81540. /**
  81541. * Creates a new list of options used by SceneOptimizer
  81542. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  81543. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  81544. */
  81545. function SceneOptimizerOptions(
  81546. /**
  81547. * Defines the target frame rate to reach (60 by default)
  81548. */
  81549. targetFrameRate,
  81550. /**
  81551. * Defines the interval between two checkes (2000ms by default)
  81552. */
  81553. trackerDuration) {
  81554. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  81555. if (trackerDuration === void 0) { trackerDuration = 2000; }
  81556. this.targetFrameRate = targetFrameRate;
  81557. this.trackerDuration = trackerDuration;
  81558. /**
  81559. * Gets the list of optimizations to apply
  81560. */
  81561. this.optimizations = new Array();
  81562. }
  81563. /**
  81564. * Add a new optimization
  81565. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  81566. * @returns the current SceneOptimizerOptions
  81567. */
  81568. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  81569. this.optimizations.push(optimization);
  81570. return this;
  81571. };
  81572. /**
  81573. * Add a new custom optimization
  81574. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  81575. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  81576. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81577. * @returns the current SceneOptimizerOptions
  81578. */
  81579. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  81580. if (priority === void 0) { priority = 0; }
  81581. var optimization = new CustomOptimization(priority);
  81582. optimization.onApply = onApply;
  81583. optimization.onGetDescription = onGetDescription;
  81584. this.optimizations.push(optimization);
  81585. return this;
  81586. };
  81587. /**
  81588. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  81589. * @param targetFrameRate defines the target frame rate (60 by default)
  81590. * @returns a SceneOptimizerOptions object
  81591. */
  81592. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  81593. var result = new SceneOptimizerOptions(targetFrameRate);
  81594. var priority = 0;
  81595. result.addOptimization(new MergeMeshesOptimization(priority));
  81596. result.addOptimization(new ShadowsOptimization(priority));
  81597. result.addOptimization(new LensFlaresOptimization(priority));
  81598. // Next priority
  81599. priority++;
  81600. result.addOptimization(new PostProcessesOptimization(priority));
  81601. result.addOptimization(new ParticlesOptimization(priority));
  81602. // Next priority
  81603. priority++;
  81604. result.addOptimization(new TextureOptimization(priority, 1024));
  81605. return result;
  81606. };
  81607. /**
  81608. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  81609. * @param targetFrameRate defines the target frame rate (60 by default)
  81610. * @returns a SceneOptimizerOptions object
  81611. */
  81612. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  81613. var result = new SceneOptimizerOptions(targetFrameRate);
  81614. var priority = 0;
  81615. result.addOptimization(new MergeMeshesOptimization(priority));
  81616. result.addOptimization(new ShadowsOptimization(priority));
  81617. result.addOptimization(new LensFlaresOptimization(priority));
  81618. // Next priority
  81619. priority++;
  81620. result.addOptimization(new PostProcessesOptimization(priority));
  81621. result.addOptimization(new ParticlesOptimization(priority));
  81622. // Next priority
  81623. priority++;
  81624. result.addOptimization(new TextureOptimization(priority, 512));
  81625. // Next priority
  81626. priority++;
  81627. result.addOptimization(new RenderTargetsOptimization(priority));
  81628. // Next priority
  81629. priority++;
  81630. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  81631. return result;
  81632. };
  81633. /**
  81634. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  81635. * @param targetFrameRate defines the target frame rate (60 by default)
  81636. * @returns a SceneOptimizerOptions object
  81637. */
  81638. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  81639. var result = new SceneOptimizerOptions(targetFrameRate);
  81640. var priority = 0;
  81641. result.addOptimization(new MergeMeshesOptimization(priority));
  81642. result.addOptimization(new ShadowsOptimization(priority));
  81643. result.addOptimization(new LensFlaresOptimization(priority));
  81644. // Next priority
  81645. priority++;
  81646. result.addOptimization(new PostProcessesOptimization(priority));
  81647. result.addOptimization(new ParticlesOptimization(priority));
  81648. // Next priority
  81649. priority++;
  81650. result.addOptimization(new TextureOptimization(priority, 256));
  81651. // Next priority
  81652. priority++;
  81653. result.addOptimization(new RenderTargetsOptimization(priority));
  81654. // Next priority
  81655. priority++;
  81656. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  81657. return result;
  81658. };
  81659. return SceneOptimizerOptions;
  81660. }());
  81661. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  81662. /**
  81663. * Class used to run optimizations in order to reach a target frame rate
  81664. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81665. */
  81666. var SceneOptimizer = /** @class */ (function () {
  81667. /**
  81668. * Creates a new SceneOptimizer
  81669. * @param scene defines the scene to work on
  81670. * @param options defines the options to use with the SceneOptimizer
  81671. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  81672. * @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)
  81673. */
  81674. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  81675. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  81676. if (improvementMode === void 0) { improvementMode = false; }
  81677. var _this = this;
  81678. this._isRunning = false;
  81679. this._currentPriorityLevel = 0;
  81680. this._targetFrameRate = 60;
  81681. this._trackerDuration = 2000;
  81682. this._currentFrameRate = 0;
  81683. this._improvementMode = false;
  81684. /**
  81685. * Defines an observable called when the optimizer reaches the target frame rate
  81686. */
  81687. this.onSuccessObservable = new BABYLON.Observable();
  81688. /**
  81689. * Defines an observable called when the optimizer enables an optimization
  81690. */
  81691. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  81692. /**
  81693. * Defines an observable called when the optimizer is not able to reach the target frame rate
  81694. */
  81695. this.onFailureObservable = new BABYLON.Observable();
  81696. if (!options) {
  81697. this._options = new SceneOptimizerOptions();
  81698. }
  81699. else {
  81700. this._options = options;
  81701. }
  81702. if (this._options.targetFrameRate) {
  81703. this._targetFrameRate = this._options.targetFrameRate;
  81704. }
  81705. if (this._options.trackerDuration) {
  81706. this._trackerDuration = this._options.trackerDuration;
  81707. }
  81708. if (autoGeneratePriorities) {
  81709. var priority = 0;
  81710. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  81711. var optim = _a[_i];
  81712. optim.priority = priority++;
  81713. }
  81714. }
  81715. this._improvementMode = improvementMode;
  81716. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81717. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  81718. _this._sceneDisposeObserver = null;
  81719. _this.dispose();
  81720. });
  81721. }
  81722. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  81723. /**
  81724. * Gets a boolean indicating if the optimizer is in improvement mode
  81725. */
  81726. get: function () {
  81727. return this._improvementMode;
  81728. },
  81729. enumerable: true,
  81730. configurable: true
  81731. });
  81732. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  81733. /**
  81734. * Gets the current priority level (0 at start)
  81735. */
  81736. get: function () {
  81737. return this._currentPriorityLevel;
  81738. },
  81739. enumerable: true,
  81740. configurable: true
  81741. });
  81742. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  81743. /**
  81744. * Gets the current frame rate checked by the SceneOptimizer
  81745. */
  81746. get: function () {
  81747. return this._currentFrameRate;
  81748. },
  81749. enumerable: true,
  81750. configurable: true
  81751. });
  81752. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  81753. /**
  81754. * Gets or sets the current target frame rate (60 by default)
  81755. */
  81756. get: function () {
  81757. return this._targetFrameRate;
  81758. },
  81759. /**
  81760. * Gets or sets the current target frame rate (60 by default)
  81761. */
  81762. set: function (value) {
  81763. this._targetFrameRate = value;
  81764. },
  81765. enumerable: true,
  81766. configurable: true
  81767. });
  81768. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  81769. /**
  81770. * Gets or sets the current interval between two checks (every 2000ms by default)
  81771. */
  81772. get: function () {
  81773. return this._trackerDuration;
  81774. },
  81775. /**
  81776. * Gets or sets the current interval between two checks (every 2000ms by default)
  81777. */
  81778. set: function (value) {
  81779. this._trackerDuration = value;
  81780. },
  81781. enumerable: true,
  81782. configurable: true
  81783. });
  81784. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  81785. /**
  81786. * Gets the list of active optimizations
  81787. */
  81788. get: function () {
  81789. return this._options.optimizations;
  81790. },
  81791. enumerable: true,
  81792. configurable: true
  81793. });
  81794. /**
  81795. * Stops the current optimizer
  81796. */
  81797. SceneOptimizer.prototype.stop = function () {
  81798. this._isRunning = false;
  81799. };
  81800. /**
  81801. * Reset the optimizer to initial step (current priority level = 0)
  81802. */
  81803. SceneOptimizer.prototype.reset = function () {
  81804. this._currentPriorityLevel = 0;
  81805. };
  81806. /**
  81807. * Start the optimizer. By default it will try to reach a specific framerate
  81808. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  81809. */
  81810. SceneOptimizer.prototype.start = function () {
  81811. var _this = this;
  81812. if (this._isRunning) {
  81813. return;
  81814. }
  81815. this._isRunning = true;
  81816. // Let's wait for the scene to be ready before running our check
  81817. this._scene.executeWhenReady(function () {
  81818. setTimeout(function () {
  81819. _this._checkCurrentState();
  81820. }, _this._trackerDuration);
  81821. });
  81822. };
  81823. SceneOptimizer.prototype._checkCurrentState = function () {
  81824. var _this = this;
  81825. if (!this._isRunning) {
  81826. return;
  81827. }
  81828. var scene = this._scene;
  81829. var options = this._options;
  81830. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  81831. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  81832. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  81833. this._isRunning = false;
  81834. this.onSuccessObservable.notifyObservers(this);
  81835. return;
  81836. }
  81837. // Apply current level of optimizations
  81838. var allDone = true;
  81839. var noOptimizationApplied = true;
  81840. for (var index = 0; index < options.optimizations.length; index++) {
  81841. var optimization = options.optimizations[index];
  81842. if (optimization.priority === this._currentPriorityLevel) {
  81843. noOptimizationApplied = false;
  81844. allDone = allDone && optimization.apply(scene, this);
  81845. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  81846. }
  81847. }
  81848. // If no optimization was applied, this is a failure :(
  81849. if (noOptimizationApplied) {
  81850. this._isRunning = false;
  81851. this.onFailureObservable.notifyObservers(this);
  81852. return;
  81853. }
  81854. // If all optimizations were done, move to next level
  81855. if (allDone) {
  81856. this._currentPriorityLevel++;
  81857. }
  81858. // Let's the system running for a specific amount of time before checking FPS
  81859. scene.executeWhenReady(function () {
  81860. setTimeout(function () {
  81861. _this._checkCurrentState();
  81862. }, _this._trackerDuration);
  81863. });
  81864. };
  81865. /**
  81866. * Release all resources
  81867. */
  81868. SceneOptimizer.prototype.dispose = function () {
  81869. this.stop();
  81870. this.onSuccessObservable.clear();
  81871. this.onFailureObservable.clear();
  81872. this.onNewOptimizationAppliedObservable.clear();
  81873. if (this._sceneDisposeObserver) {
  81874. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  81875. }
  81876. };
  81877. /**
  81878. * Helper function to create a SceneOptimizer with one single line of code
  81879. * @param scene defines the scene to work on
  81880. * @param options defines the options to use with the SceneOptimizer
  81881. * @param onSuccess defines a callback to call on success
  81882. * @param onFailure defines a callback to call on failure
  81883. * @returns the new SceneOptimizer object
  81884. */
  81885. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  81886. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  81887. if (onSuccess) {
  81888. optimizer.onSuccessObservable.add(function () {
  81889. onSuccess();
  81890. });
  81891. }
  81892. if (onFailure) {
  81893. optimizer.onFailureObservable.add(function () {
  81894. onFailure();
  81895. });
  81896. }
  81897. optimizer.start();
  81898. return optimizer;
  81899. };
  81900. return SceneOptimizer;
  81901. }());
  81902. BABYLON.SceneOptimizer = SceneOptimizer;
  81903. })(BABYLON || (BABYLON = {}));
  81904. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  81905. var BABYLON;
  81906. (function (BABYLON) {
  81907. var OutlineRenderer = /** @class */ (function () {
  81908. function OutlineRenderer(scene) {
  81909. this.zOffset = 1;
  81910. this._scene = scene;
  81911. }
  81912. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  81913. var _this = this;
  81914. if (useOverlay === void 0) { useOverlay = false; }
  81915. var scene = this._scene;
  81916. var engine = this._scene.getEngine();
  81917. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  81918. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  81919. return;
  81920. }
  81921. var mesh = subMesh.getRenderingMesh();
  81922. var material = subMesh.getMaterial();
  81923. if (!material || !scene.activeCamera) {
  81924. return;
  81925. }
  81926. engine.enableEffect(this._effect);
  81927. // Logarithmic depth
  81928. if (material.useLogarithmicDepth) {
  81929. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  81930. }
  81931. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  81932. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  81933. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  81934. // Bones
  81935. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81936. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81937. }
  81938. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  81939. // Alpha test
  81940. if (material && material.needAlphaTesting()) {
  81941. var alphaTexture = material.getAlphaTestTexture();
  81942. if (alphaTexture) {
  81943. this._effect.setTexture("diffuseSampler", alphaTexture);
  81944. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81945. }
  81946. }
  81947. engine.setZOffset(-this.zOffset);
  81948. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  81949. engine.setZOffset(0);
  81950. };
  81951. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  81952. var defines = [];
  81953. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81954. var mesh = subMesh.getMesh();
  81955. var material = subMesh.getMaterial();
  81956. if (material) {
  81957. // Alpha test
  81958. if (material.needAlphaTesting()) {
  81959. defines.push("#define ALPHATEST");
  81960. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81961. attribs.push(BABYLON.VertexBuffer.UVKind);
  81962. defines.push("#define UV1");
  81963. }
  81964. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81965. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81966. defines.push("#define UV2");
  81967. }
  81968. }
  81969. //Logarithmic depth
  81970. if (material.useLogarithmicDepth) {
  81971. defines.push("#define LOGARITHMICDEPTH");
  81972. }
  81973. }
  81974. // Bones
  81975. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81976. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81977. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81978. if (mesh.numBoneInfluencers > 4) {
  81979. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  81980. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  81981. }
  81982. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81983. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  81984. }
  81985. else {
  81986. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81987. }
  81988. // Instances
  81989. if (useInstances) {
  81990. defines.push("#define INSTANCES");
  81991. attribs.push("world0");
  81992. attribs.push("world1");
  81993. attribs.push("world2");
  81994. attribs.push("world3");
  81995. }
  81996. // Get correct effect
  81997. var join = defines.join("\n");
  81998. if (this._cachedDefines !== join) {
  81999. this._cachedDefines = join;
  82000. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  82001. }
  82002. return this._effect.isReady();
  82003. };
  82004. return OutlineRenderer;
  82005. }());
  82006. BABYLON.OutlineRenderer = OutlineRenderer;
  82007. })(BABYLON || (BABYLON = {}));
  82008. //# sourceMappingURL=babylon.outlineRenderer.js.map
  82009. var BABYLON;
  82010. (function (BABYLON) {
  82011. var FaceAdjacencies = /** @class */ (function () {
  82012. function FaceAdjacencies() {
  82013. this.edges = new Array();
  82014. this.edgesConnectedCount = 0;
  82015. }
  82016. return FaceAdjacencies;
  82017. }());
  82018. var EdgesRenderer = /** @class */ (function () {
  82019. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  82020. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  82021. if (epsilon === void 0) { epsilon = 0.95; }
  82022. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  82023. this.edgesWidthScalerForOrthographic = 1000.0;
  82024. this.edgesWidthScalerForPerspective = 50.0;
  82025. this._linesPositions = new Array();
  82026. this._linesNormals = new Array();
  82027. this._linesIndices = new Array();
  82028. this._buffers = {};
  82029. this._checkVerticesInsteadOfIndices = false;
  82030. this._source = source;
  82031. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  82032. this._epsilon = epsilon;
  82033. this._prepareRessources();
  82034. this._generateEdgesLines();
  82035. }
  82036. EdgesRenderer.prototype._prepareRessources = function () {
  82037. if (this._lineShader) {
  82038. return;
  82039. }
  82040. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  82041. attributes: ["position", "normal"],
  82042. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  82043. });
  82044. this._lineShader.disableDepthWrite = true;
  82045. this._lineShader.backFaceCulling = false;
  82046. };
  82047. EdgesRenderer.prototype._rebuild = function () {
  82048. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  82049. if (buffer) {
  82050. buffer._rebuild();
  82051. }
  82052. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  82053. if (buffer) {
  82054. buffer._rebuild();
  82055. }
  82056. var scene = this._source.getScene();
  82057. var engine = scene.getEngine();
  82058. this._ib = engine.createIndexBuffer(this._linesIndices);
  82059. };
  82060. EdgesRenderer.prototype.dispose = function () {
  82061. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  82062. if (buffer) {
  82063. buffer.dispose();
  82064. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  82065. }
  82066. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  82067. if (buffer) {
  82068. buffer.dispose();
  82069. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  82070. }
  82071. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  82072. this._lineShader.dispose();
  82073. };
  82074. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  82075. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  82076. return 0;
  82077. }
  82078. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  82079. return 1;
  82080. }
  82081. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  82082. return 2;
  82083. }
  82084. return -1;
  82085. };
  82086. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  82087. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  82088. return 0;
  82089. }
  82090. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  82091. return 1;
  82092. }
  82093. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  82094. return 2;
  82095. }
  82096. return -1;
  82097. };
  82098. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  82099. var needToCreateLine;
  82100. if (edge === undefined) {
  82101. needToCreateLine = true;
  82102. }
  82103. else {
  82104. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  82105. needToCreateLine = dotProduct < this._epsilon;
  82106. }
  82107. if (needToCreateLine) {
  82108. var offset = this._linesPositions.length / 3;
  82109. var normal = p0.subtract(p1);
  82110. normal.normalize();
  82111. // Positions
  82112. this._linesPositions.push(p0.x);
  82113. this._linesPositions.push(p0.y);
  82114. this._linesPositions.push(p0.z);
  82115. this._linesPositions.push(p0.x);
  82116. this._linesPositions.push(p0.y);
  82117. this._linesPositions.push(p0.z);
  82118. this._linesPositions.push(p1.x);
  82119. this._linesPositions.push(p1.y);
  82120. this._linesPositions.push(p1.z);
  82121. this._linesPositions.push(p1.x);
  82122. this._linesPositions.push(p1.y);
  82123. this._linesPositions.push(p1.z);
  82124. // Normals
  82125. this._linesNormals.push(p1.x);
  82126. this._linesNormals.push(p1.y);
  82127. this._linesNormals.push(p1.z);
  82128. this._linesNormals.push(-1);
  82129. this._linesNormals.push(p1.x);
  82130. this._linesNormals.push(p1.y);
  82131. this._linesNormals.push(p1.z);
  82132. this._linesNormals.push(1);
  82133. this._linesNormals.push(p0.x);
  82134. this._linesNormals.push(p0.y);
  82135. this._linesNormals.push(p0.z);
  82136. this._linesNormals.push(-1);
  82137. this._linesNormals.push(p0.x);
  82138. this._linesNormals.push(p0.y);
  82139. this._linesNormals.push(p0.z);
  82140. this._linesNormals.push(1);
  82141. // Indices
  82142. this._linesIndices.push(offset);
  82143. this._linesIndices.push(offset + 1);
  82144. this._linesIndices.push(offset + 2);
  82145. this._linesIndices.push(offset);
  82146. this._linesIndices.push(offset + 2);
  82147. this._linesIndices.push(offset + 3);
  82148. }
  82149. };
  82150. EdgesRenderer.prototype._generateEdgesLines = function () {
  82151. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82152. var indices = this._source.getIndices();
  82153. if (!indices || !positions) {
  82154. return;
  82155. }
  82156. // First let's find adjacencies
  82157. var adjacencies = new Array();
  82158. var faceNormals = new Array();
  82159. var index;
  82160. var faceAdjacencies;
  82161. // Prepare faces
  82162. for (index = 0; index < indices.length; index += 3) {
  82163. faceAdjacencies = new FaceAdjacencies();
  82164. var p0Index = indices[index];
  82165. var p1Index = indices[index + 1];
  82166. var p2Index = indices[index + 2];
  82167. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  82168. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  82169. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  82170. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  82171. faceNormal.normalize();
  82172. faceNormals.push(faceNormal);
  82173. adjacencies.push(faceAdjacencies);
  82174. }
  82175. // Scan
  82176. for (index = 0; index < adjacencies.length; index++) {
  82177. faceAdjacencies = adjacencies[index];
  82178. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  82179. var otherFaceAdjacencies = adjacencies[otherIndex];
  82180. if (faceAdjacencies.edgesConnectedCount === 3) {
  82181. break;
  82182. }
  82183. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  82184. continue;
  82185. }
  82186. var otherP0 = indices[otherIndex * 3];
  82187. var otherP1 = indices[otherIndex * 3 + 1];
  82188. var otherP2 = indices[otherIndex * 3 + 2];
  82189. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  82190. var otherEdgeIndex = 0;
  82191. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  82192. continue;
  82193. }
  82194. switch (edgeIndex) {
  82195. case 0:
  82196. if (this._checkVerticesInsteadOfIndices) {
  82197. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82198. }
  82199. else {
  82200. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  82201. }
  82202. break;
  82203. case 1:
  82204. if (this._checkVerticesInsteadOfIndices) {
  82205. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82206. }
  82207. else {
  82208. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  82209. }
  82210. break;
  82211. case 2:
  82212. if (this._checkVerticesInsteadOfIndices) {
  82213. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82214. }
  82215. else {
  82216. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  82217. }
  82218. break;
  82219. }
  82220. if (otherEdgeIndex === -1) {
  82221. continue;
  82222. }
  82223. faceAdjacencies.edges[edgeIndex] = otherIndex;
  82224. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  82225. faceAdjacencies.edgesConnectedCount++;
  82226. otherFaceAdjacencies.edgesConnectedCount++;
  82227. if (faceAdjacencies.edgesConnectedCount === 3) {
  82228. break;
  82229. }
  82230. }
  82231. }
  82232. }
  82233. // Create lines
  82234. for (index = 0; index < adjacencies.length; index++) {
  82235. // 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
  82236. var current = adjacencies[index];
  82237. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  82238. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  82239. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  82240. }
  82241. // Merge into a single mesh
  82242. var engine = this._source.getScene().getEngine();
  82243. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  82244. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  82245. this._ib = engine.createIndexBuffer(this._linesIndices);
  82246. this._indicesCount = this._linesIndices.length;
  82247. };
  82248. EdgesRenderer.prototype.render = function () {
  82249. var scene = this._source.getScene();
  82250. if (!this._lineShader.isReady() || !scene.activeCamera) {
  82251. return;
  82252. }
  82253. var engine = scene.getEngine();
  82254. this._lineShader._preBind();
  82255. // VBOs
  82256. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  82257. scene.resetCachedMaterial();
  82258. this._lineShader.setColor4("color", this._source.edgesColor);
  82259. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  82260. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  82261. }
  82262. else {
  82263. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  82264. }
  82265. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  82266. this._lineShader.bind(this._source.getWorldMatrix());
  82267. // Draw order
  82268. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  82269. this._lineShader.unbind();
  82270. engine.setDepthWrite(true);
  82271. };
  82272. return EdgesRenderer;
  82273. }());
  82274. BABYLON.EdgesRenderer = EdgesRenderer;
  82275. })(BABYLON || (BABYLON = {}));
  82276. //# sourceMappingURL=babylon.edgesRenderer.js.map
  82277. var __assign = (this && this.__assign) || Object.assign || function(t) {
  82278. for (var s, i = 1, n = arguments.length; i < n; i++) {
  82279. s = arguments[i];
  82280. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  82281. t[p] = s[p];
  82282. }
  82283. return t;
  82284. };
  82285. var BABYLON;
  82286. (function (BABYLON) {
  82287. /**
  82288. * The effect layer Helps adding post process effect blended with the main pass.
  82289. *
  82290. * This can be for instance use to generate glow or higlight effects on the scene.
  82291. *
  82292. * The effect layer class can not be used directly and is intented to inherited from to be
  82293. * customized per effects.
  82294. */
  82295. var EffectLayer = /** @class */ (function () {
  82296. /**
  82297. * Instantiates a new effect Layer and references it in the scene.
  82298. * @param name The name of the layer
  82299. * @param scene The scene to use the layer in
  82300. */
  82301. function EffectLayer(
  82302. /** The Friendly of the effect in the scene */
  82303. name, scene) {
  82304. this.name = name;
  82305. this._vertexBuffers = {};
  82306. this._maxSize = 0;
  82307. this._mainTextureDesiredSize = { width: 0, height: 0 };
  82308. this._shouldRender = true;
  82309. this._postProcesses = [];
  82310. this._textures = [];
  82311. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  82312. /**
  82313. * The clear color of the texture used to generate the glow map.
  82314. */
  82315. this.neutralColor = new BABYLON.Color4();
  82316. /**
  82317. * Specifies wether the highlight layer is enabled or not.
  82318. */
  82319. this.isEnabled = true;
  82320. /**
  82321. * An event triggered when the effect layer has been disposed.
  82322. */
  82323. this.onDisposeObservable = new BABYLON.Observable();
  82324. /**
  82325. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  82326. */
  82327. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  82328. /**
  82329. * An event triggered when the generated texture is being merged in the scene.
  82330. */
  82331. this.onBeforeComposeObservable = new BABYLON.Observable();
  82332. /**
  82333. * An event triggered when the generated texture has been merged in the scene.
  82334. */
  82335. this.onAfterComposeObservable = new BABYLON.Observable();
  82336. /**
  82337. * An event triggered when the efffect layer changes its size.
  82338. */
  82339. this.onSizeChangedObservable = new BABYLON.Observable();
  82340. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82341. this._engine = scene.getEngine();
  82342. this._maxSize = this._engine.getCaps().maxTextureSize;
  82343. this._scene.effectLayers.push(this);
  82344. // Generate Buffers
  82345. this._generateIndexBuffer();
  82346. this._genrateVertexBuffer();
  82347. }
  82348. Object.defineProperty(EffectLayer.prototype, "camera", {
  82349. /**
  82350. * Gets the camera attached to the layer.
  82351. */
  82352. get: function () {
  82353. return this._effectLayerOptions.camera;
  82354. },
  82355. enumerable: true,
  82356. configurable: true
  82357. });
  82358. /**
  82359. * Initializes the effect layer with the required options.
  82360. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  82361. */
  82362. EffectLayer.prototype._init = function (options) {
  82363. // Adapt options
  82364. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82365. this._setMainTextureSize();
  82366. this._createMainTexture();
  82367. this._createTextureAndPostProcesses();
  82368. this._mergeEffect = this._createMergeEffect();
  82369. };
  82370. /**
  82371. * Generates the index buffer of the full screen quad blending to the main canvas.
  82372. */
  82373. EffectLayer.prototype._generateIndexBuffer = function () {
  82374. // Indices
  82375. var indices = [];
  82376. indices.push(0);
  82377. indices.push(1);
  82378. indices.push(2);
  82379. indices.push(0);
  82380. indices.push(2);
  82381. indices.push(3);
  82382. this._indexBuffer = this._engine.createIndexBuffer(indices);
  82383. };
  82384. /**
  82385. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  82386. */
  82387. EffectLayer.prototype._genrateVertexBuffer = function () {
  82388. // VBO
  82389. var vertices = [];
  82390. vertices.push(1, 1);
  82391. vertices.push(-1, 1);
  82392. vertices.push(-1, -1);
  82393. vertices.push(1, -1);
  82394. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82395. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  82396. };
  82397. /**
  82398. * Sets the main texture desired size which is the closest power of two
  82399. * of the engine canvas size.
  82400. */
  82401. EffectLayer.prototype._setMainTextureSize = function () {
  82402. if (this._effectLayerOptions.mainTextureFixedSize) {
  82403. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  82404. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  82405. }
  82406. else {
  82407. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  82408. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  82409. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  82410. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  82411. }
  82412. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  82413. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  82414. };
  82415. /**
  82416. * Creates the main texture for the effect layer.
  82417. */
  82418. EffectLayer.prototype._createMainTexture = function () {
  82419. var _this = this;
  82420. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  82421. width: this._mainTextureDesiredSize.width,
  82422. height: this._mainTextureDesiredSize.height
  82423. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82424. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  82425. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82426. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82427. this._mainTexture.anisotropicFilteringLevel = 1;
  82428. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82429. this._mainTexture.renderParticles = false;
  82430. this._mainTexture.renderList = null;
  82431. this._mainTexture.ignoreCameraViewport = true;
  82432. // Custom render function
  82433. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82434. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  82435. var index;
  82436. var engine = _this._scene.getEngine();
  82437. if (depthOnlySubMeshes.length) {
  82438. engine.setColorWrite(false);
  82439. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82440. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  82441. }
  82442. engine.setColorWrite(true);
  82443. }
  82444. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82445. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  82446. }
  82447. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82448. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  82449. }
  82450. for (index = 0; index < transparentSubMeshes.length; index++) {
  82451. _this._renderSubMesh(transparentSubMeshes.data[index]);
  82452. }
  82453. };
  82454. this._mainTexture.onClearObservable.add(function (engine) {
  82455. engine.clear(_this.neutralColor, true, true, true);
  82456. });
  82457. };
  82458. /**
  82459. * Checks for the readiness of the element composing the layer.
  82460. * @param subMesh the mesh to check for
  82461. * @param useInstances specify wether or not to use instances to render the mesh
  82462. * @param emissiveTexture the associated emissive texture used to generate the glow
  82463. * @return true if ready otherwise, false
  82464. */
  82465. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  82466. var material = subMesh.getMaterial();
  82467. if (!material) {
  82468. return false;
  82469. }
  82470. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  82471. return false;
  82472. }
  82473. var defines = [];
  82474. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82475. var mesh = subMesh.getMesh();
  82476. var uv1 = false;
  82477. var uv2 = false;
  82478. // Alpha test
  82479. if (material && material.needAlphaTesting()) {
  82480. var alphaTexture = material.getAlphaTestTexture();
  82481. if (alphaTexture) {
  82482. defines.push("#define ALPHATEST");
  82483. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82484. alphaTexture.coordinatesIndex === 1) {
  82485. defines.push("#define DIFFUSEUV2");
  82486. uv2 = true;
  82487. }
  82488. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82489. defines.push("#define DIFFUSEUV1");
  82490. uv1 = true;
  82491. }
  82492. }
  82493. }
  82494. // Emissive
  82495. if (emissiveTexture) {
  82496. defines.push("#define EMISSIVE");
  82497. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82498. emissiveTexture.coordinatesIndex === 1) {
  82499. defines.push("#define EMISSIVEUV2");
  82500. uv2 = true;
  82501. }
  82502. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82503. defines.push("#define EMISSIVEUV1");
  82504. uv1 = true;
  82505. }
  82506. }
  82507. if (uv1) {
  82508. attribs.push(BABYLON.VertexBuffer.UVKind);
  82509. defines.push("#define UV1");
  82510. }
  82511. if (uv2) {
  82512. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82513. defines.push("#define UV2");
  82514. }
  82515. // Bones
  82516. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82517. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82518. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82519. if (mesh.numBoneInfluencers > 4) {
  82520. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82521. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82522. }
  82523. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82524. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  82525. }
  82526. else {
  82527. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82528. }
  82529. // Instances
  82530. if (useInstances) {
  82531. defines.push("#define INSTANCES");
  82532. attribs.push("world0");
  82533. attribs.push("world1");
  82534. attribs.push("world2");
  82535. attribs.push("world3");
  82536. }
  82537. // Get correct effect
  82538. var join = defines.join("\n");
  82539. if (this._cachedDefines !== join) {
  82540. this._cachedDefines = join;
  82541. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  82542. }
  82543. return this._effectLayerMapGenerationEffect.isReady();
  82544. };
  82545. /**
  82546. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  82547. */
  82548. EffectLayer.prototype.render = function () {
  82549. var currentEffect = this._mergeEffect;
  82550. // Check
  82551. if (!currentEffect.isReady())
  82552. return;
  82553. for (var i = 0; i < this._postProcesses.length; i++) {
  82554. if (!this._postProcesses[i].isReady()) {
  82555. return;
  82556. }
  82557. }
  82558. var engine = this._scene.getEngine();
  82559. this.onBeforeComposeObservable.notifyObservers(this);
  82560. // Render
  82561. engine.enableEffect(currentEffect);
  82562. engine.setState(false);
  82563. // VBOs
  82564. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  82565. // Cache
  82566. var previousAlphaMode = engine.getAlphaMode();
  82567. // Go Blend.
  82568. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  82569. // Blends the map on the main canvas.
  82570. this._internalRender(currentEffect);
  82571. // Restore Alpha
  82572. engine.setAlphaMode(previousAlphaMode);
  82573. this.onAfterComposeObservable.notifyObservers(this);
  82574. // Handle size changes.
  82575. var size = this._mainTexture.getSize();
  82576. this._setMainTextureSize();
  82577. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  82578. // Recreate RTT and post processes on size change.
  82579. this.onSizeChangedObservable.notifyObservers(this);
  82580. this._disposeTextureAndPostProcesses();
  82581. this._createMainTexture();
  82582. this._createTextureAndPostProcesses();
  82583. }
  82584. };
  82585. /**
  82586. * Determine if a given mesh will be used in the current effect.
  82587. * @param mesh mesh to test
  82588. * @returns true if the mesh will be used
  82589. */
  82590. EffectLayer.prototype.hasMesh = function (mesh) {
  82591. return true;
  82592. };
  82593. /**
  82594. * Returns true if the layer contains information to display, otherwise false.
  82595. * @returns true if the glow layer should be rendered
  82596. */
  82597. EffectLayer.prototype.shouldRender = function () {
  82598. return this.isEnabled && this._shouldRender;
  82599. };
  82600. /**
  82601. * Returns true if the mesh should render, otherwise false.
  82602. * @param mesh The mesh to render
  82603. * @returns true if it should render otherwise false
  82604. */
  82605. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  82606. return true;
  82607. };
  82608. /**
  82609. * Returns true if the mesh should render, otherwise false.
  82610. * @param mesh The mesh to render
  82611. * @returns true if it should render otherwise false
  82612. */
  82613. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  82614. return true;
  82615. };
  82616. /**
  82617. * Renders the submesh passed in parameter to the generation map.
  82618. */
  82619. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  82620. var _this = this;
  82621. if (!this.shouldRender()) {
  82622. return;
  82623. }
  82624. var material = subMesh.getMaterial();
  82625. var mesh = subMesh.getRenderingMesh();
  82626. var scene = this._scene;
  82627. var engine = scene.getEngine();
  82628. if (!material) {
  82629. return;
  82630. }
  82631. // Do not block in blend mode.
  82632. if (material.needAlphaBlendingForMesh(mesh)) {
  82633. return;
  82634. }
  82635. // Culling
  82636. engine.setState(material.backFaceCulling);
  82637. // Managing instances
  82638. var batch = mesh._getInstancesRenderList(subMesh._id);
  82639. if (batch.mustReturn) {
  82640. return;
  82641. }
  82642. // Early Exit per mesh
  82643. if (!this._shouldRenderMesh(mesh)) {
  82644. return;
  82645. }
  82646. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  82647. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  82648. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  82649. engine.enableEffect(this._effectLayerMapGenerationEffect);
  82650. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  82651. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  82652. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  82653. // Alpha test
  82654. if (material && material.needAlphaTesting()) {
  82655. var alphaTexture = material.getAlphaTestTexture();
  82656. if (alphaTexture) {
  82657. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  82658. var textureMatrix = alphaTexture.getTextureMatrix();
  82659. if (textureMatrix) {
  82660. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  82661. }
  82662. }
  82663. }
  82664. // Glow emissive only
  82665. if (this._emissiveTextureAndColor.texture) {
  82666. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  82667. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  82668. }
  82669. // Bones
  82670. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82671. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82672. }
  82673. // Draw
  82674. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  82675. }
  82676. else {
  82677. // Need to reset refresh rate of the shadowMap
  82678. this._mainTexture.resetRefreshCounter();
  82679. }
  82680. };
  82681. /**
  82682. * Rebuild the required buffers.
  82683. * @ignore Internal use only.
  82684. */
  82685. EffectLayer.prototype._rebuild = function () {
  82686. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82687. if (vb) {
  82688. vb._rebuild();
  82689. }
  82690. this._generateIndexBuffer();
  82691. };
  82692. /**
  82693. * Dispose only the render target textures and post process.
  82694. */
  82695. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  82696. this._mainTexture.dispose();
  82697. for (var i = 0; i < this._postProcesses.length; i++) {
  82698. if (this._postProcesses[i]) {
  82699. this._postProcesses[i].dispose();
  82700. }
  82701. }
  82702. this._postProcesses = [];
  82703. for (var i = 0; i < this._textures.length; i++) {
  82704. if (this._textures[i]) {
  82705. this._textures[i].dispose();
  82706. }
  82707. }
  82708. this._textures = [];
  82709. };
  82710. /**
  82711. * Dispose the highlight layer and free resources.
  82712. */
  82713. EffectLayer.prototype.dispose = function () {
  82714. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82715. if (vertexBuffer) {
  82716. vertexBuffer.dispose();
  82717. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82718. }
  82719. if (this._indexBuffer) {
  82720. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82721. this._indexBuffer = null;
  82722. }
  82723. // Clean textures and post processes
  82724. this._disposeTextureAndPostProcesses();
  82725. // Remove from scene
  82726. var index = this._scene.effectLayers.indexOf(this, 0);
  82727. if (index > -1) {
  82728. this._scene.effectLayers.splice(index, 1);
  82729. }
  82730. // Callback
  82731. this.onDisposeObservable.notifyObservers(this);
  82732. this.onDisposeObservable.clear();
  82733. this.onBeforeRenderMainTextureObservable.clear();
  82734. this.onBeforeComposeObservable.clear();
  82735. this.onAfterComposeObservable.clear();
  82736. this.onSizeChangedObservable.clear();
  82737. };
  82738. return EffectLayer;
  82739. }());
  82740. BABYLON.EffectLayer = EffectLayer;
  82741. })(BABYLON || (BABYLON = {}));
  82742. //# sourceMappingURL=babylon.effectLayer.js.map
  82743. var BABYLON;
  82744. (function (BABYLON) {
  82745. /**
  82746. * Special Glow Blur post process only blurring the alpha channel
  82747. * It enforces keeping the most luminous color in the color channel.
  82748. */
  82749. var GlowBlurPostProcess = /** @class */ (function (_super) {
  82750. __extends(GlowBlurPostProcess, _super);
  82751. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  82752. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82753. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  82754. _this.direction = direction;
  82755. _this.kernel = kernel;
  82756. _this.onApplyObservable.add(function (effect) {
  82757. effect.setFloat2("screenSize", _this.width, _this.height);
  82758. effect.setVector2("direction", _this.direction);
  82759. effect.setFloat("blurWidth", _this.kernel);
  82760. });
  82761. return _this;
  82762. }
  82763. return GlowBlurPostProcess;
  82764. }(BABYLON.PostProcess));
  82765. /**
  82766. * The highlight layer Helps adding a glow effect around a mesh.
  82767. *
  82768. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  82769. * glowy meshes to your scene.
  82770. *
  82771. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  82772. */
  82773. var HighlightLayer = /** @class */ (function (_super) {
  82774. __extends(HighlightLayer, _super);
  82775. /**
  82776. * Instantiates a new highlight Layer and references it to the scene..
  82777. * @param name The name of the layer
  82778. * @param scene The scene to use the layer in
  82779. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  82780. */
  82781. function HighlightLayer(name, scene, options) {
  82782. var _this = _super.call(this, name, scene) || this;
  82783. _this.name = name;
  82784. /**
  82785. * Specifies whether or not the inner glow is ACTIVE in the layer.
  82786. */
  82787. _this.innerGlow = true;
  82788. /**
  82789. * Specifies whether or not the outer glow is ACTIVE in the layer.
  82790. */
  82791. _this.outerGlow = true;
  82792. /**
  82793. * An event triggered when the highlight layer is being blurred.
  82794. */
  82795. _this.onBeforeBlurObservable = new BABYLON.Observable();
  82796. /**
  82797. * An event triggered when the highlight layer has been blurred.
  82798. */
  82799. _this.onAfterBlurObservable = new BABYLON.Observable();
  82800. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  82801. _this._meshes = {};
  82802. _this._excludedMeshes = {};
  82803. _this.neutralColor = HighlightLayer.NeutralColor;
  82804. // Warn on stencil
  82805. if (!_this._engine.isStencilEnable) {
  82806. 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 }");
  82807. }
  82808. // Adapt options
  82809. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82810. // Initialize the layer
  82811. _this._init({
  82812. alphaBlendingMode: _this._options.alphaBlendingMode,
  82813. camera: _this._options.camera,
  82814. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  82815. mainTextureRatio: _this._options.mainTextureRatio
  82816. });
  82817. // Do not render as long as no meshes have been added
  82818. _this._shouldRender = false;
  82819. return _this;
  82820. }
  82821. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  82822. /**
  82823. * Gets the horizontal size of the blur.
  82824. */
  82825. get: function () {
  82826. return this._horizontalBlurPostprocess.kernel;
  82827. },
  82828. /**
  82829. * Specifies the horizontal size of the blur.
  82830. */
  82831. set: function (value) {
  82832. this._horizontalBlurPostprocess.kernel = value;
  82833. },
  82834. enumerable: true,
  82835. configurable: true
  82836. });
  82837. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  82838. /**
  82839. * Gets the vertical size of the blur.
  82840. */
  82841. get: function () {
  82842. return this._verticalBlurPostprocess.kernel;
  82843. },
  82844. /**
  82845. * Specifies the vertical size of the blur.
  82846. */
  82847. set: function (value) {
  82848. this._verticalBlurPostprocess.kernel = value;
  82849. },
  82850. enumerable: true,
  82851. configurable: true
  82852. });
  82853. /**
  82854. * Get the effect name of the layer.
  82855. * @return The effect name
  82856. */
  82857. HighlightLayer.prototype.getEffectName = function () {
  82858. return HighlightLayer.EffectName;
  82859. };
  82860. /**
  82861. * Create the merge effect. This is the shader use to blit the information back
  82862. * to the main canvas at the end of the scene rendering.
  82863. */
  82864. HighlightLayer.prototype._createMergeEffect = function () {
  82865. // Effect
  82866. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  82867. };
  82868. /**
  82869. * Creates the render target textures and post processes used in the highlight layer.
  82870. */
  82871. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  82872. var _this = this;
  82873. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  82874. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  82875. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  82876. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  82877. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  82878. width: blurTextureWidth,
  82879. height: blurTextureHeight
  82880. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82881. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82882. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82883. this._blurTexture.anisotropicFilteringLevel = 16;
  82884. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82885. this._blurTexture.renderParticles = false;
  82886. this._blurTexture.ignoreCameraViewport = true;
  82887. this._textures = [this._blurTexture];
  82888. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  82889. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82890. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  82891. effect.setTexture("textureSampler", _this._mainTexture);
  82892. });
  82893. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82894. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  82895. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  82896. });
  82897. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82898. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  82899. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  82900. });
  82901. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  82902. }
  82903. else {
  82904. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  82905. width: blurTextureWidth,
  82906. height: blurTextureHeight
  82907. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82908. this._horizontalBlurPostprocess.width = blurTextureWidth;
  82909. this._horizontalBlurPostprocess.height = blurTextureHeight;
  82910. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  82911. effect.setTexture("textureSampler", _this._mainTexture);
  82912. });
  82913. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  82914. width: blurTextureWidth,
  82915. height: blurTextureHeight
  82916. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82917. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  82918. }
  82919. this._mainTexture.onAfterUnbindObservable.add(function () {
  82920. _this.onBeforeBlurObservable.notifyObservers(_this);
  82921. var internalTexture = _this._blurTexture.getInternalTexture();
  82922. if (internalTexture) {
  82923. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  82924. }
  82925. _this.onAfterBlurObservable.notifyObservers(_this);
  82926. });
  82927. // Prevent autoClear.
  82928. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  82929. };
  82930. /**
  82931. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  82932. */
  82933. HighlightLayer.prototype.needStencil = function () {
  82934. return true;
  82935. };
  82936. /**
  82937. * Checks for the readiness of the element composing the layer.
  82938. * @param subMesh the mesh to check for
  82939. * @param useInstances specify wether or not to use instances to render the mesh
  82940. * @param emissiveTexture the associated emissive texture used to generate the glow
  82941. * @return true if ready otherwise, false
  82942. */
  82943. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  82944. var material = subMesh.getMaterial();
  82945. var mesh = subMesh.getRenderingMesh();
  82946. if (!material || !mesh || !this._meshes) {
  82947. return false;
  82948. }
  82949. var emissiveTexture = null;
  82950. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  82951. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  82952. emissiveTexture = material.emissiveTexture;
  82953. }
  82954. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  82955. };
  82956. /**
  82957. * Implementation specific of rendering the generating effect on the main canvas.
  82958. * @param effect The effect used to render through
  82959. */
  82960. HighlightLayer.prototype._internalRender = function (effect) {
  82961. // Texture
  82962. effect.setTexture("textureSampler", this._blurTexture);
  82963. // Cache
  82964. var engine = this._engine;
  82965. var previousStencilBuffer = engine.getStencilBuffer();
  82966. var previousStencilFunction = engine.getStencilFunction();
  82967. var previousStencilMask = engine.getStencilMask();
  82968. var previousStencilOperationPass = engine.getStencilOperationPass();
  82969. var previousStencilOperationFail = engine.getStencilOperationFail();
  82970. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  82971. var previousStencilReference = engine.getStencilFunctionReference();
  82972. // Stencil operations
  82973. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  82974. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  82975. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  82976. // Draw order
  82977. engine.setStencilMask(0x00);
  82978. engine.setStencilBuffer(true);
  82979. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  82980. // 2 passes inner outer
  82981. if (this.outerGlow) {
  82982. effect.setFloat("offset", 0);
  82983. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  82984. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82985. }
  82986. if (this.innerGlow) {
  82987. effect.setFloat("offset", 1);
  82988. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  82989. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82990. }
  82991. // Restore Cache
  82992. engine.setStencilFunction(previousStencilFunction);
  82993. engine.setStencilMask(previousStencilMask);
  82994. engine.setStencilBuffer(previousStencilBuffer);
  82995. engine.setStencilOperationPass(previousStencilOperationPass);
  82996. engine.setStencilOperationFail(previousStencilOperationFail);
  82997. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  82998. engine.setStencilFunctionReference(previousStencilReference);
  82999. };
  83000. /**
  83001. * Returns true if the layer contains information to display, otherwise false.
  83002. */
  83003. HighlightLayer.prototype.shouldRender = function () {
  83004. if (_super.prototype.shouldRender.call(this)) {
  83005. return this._meshes ? true : false;
  83006. }
  83007. return false;
  83008. };
  83009. /**
  83010. * Returns true if the mesh should render, otherwise false.
  83011. * @param mesh The mesh to render
  83012. * @returns true if it should render otherwise false
  83013. */
  83014. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  83015. // Excluded Mesh
  83016. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  83017. return false;
  83018. }
  83019. ;
  83020. return true;
  83021. };
  83022. /**
  83023. * Sets the required values for both the emissive texture and and the main color.
  83024. */
  83025. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83026. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  83027. if (highlightLayerMesh) {
  83028. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  83029. }
  83030. else {
  83031. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83032. }
  83033. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  83034. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83035. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  83036. }
  83037. else {
  83038. this._emissiveTextureAndColor.texture = null;
  83039. }
  83040. };
  83041. /**
  83042. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  83043. * @param mesh The mesh to exclude from the highlight layer
  83044. */
  83045. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  83046. if (!this._excludedMeshes) {
  83047. return;
  83048. }
  83049. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  83050. if (!meshExcluded) {
  83051. this._excludedMeshes[mesh.uniqueId] = {
  83052. mesh: mesh,
  83053. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  83054. mesh.getEngine().setStencilBuffer(false);
  83055. }),
  83056. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  83057. mesh.getEngine().setStencilBuffer(true);
  83058. }),
  83059. };
  83060. }
  83061. };
  83062. /**
  83063. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  83064. * @param mesh The mesh to highlight
  83065. */
  83066. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  83067. if (!this._excludedMeshes) {
  83068. return;
  83069. }
  83070. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  83071. if (meshExcluded) {
  83072. if (meshExcluded.beforeRender) {
  83073. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  83074. }
  83075. if (meshExcluded.afterRender) {
  83076. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  83077. }
  83078. }
  83079. this._excludedMeshes[mesh.uniqueId] = null;
  83080. };
  83081. /**
  83082. * Determine if a given mesh will be highlighted by the current HighlightLayer
  83083. * @param mesh mesh to test
  83084. * @returns true if the mesh will be highlighted by the current HighlightLayer
  83085. */
  83086. HighlightLayer.prototype.hasMesh = function (mesh) {
  83087. if (!this._meshes) {
  83088. return false;
  83089. }
  83090. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  83091. };
  83092. /**
  83093. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  83094. * @param mesh The mesh to highlight
  83095. * @param color The color of the highlight
  83096. * @param glowEmissiveOnly Extract the glow from the emissive texture
  83097. */
  83098. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  83099. var _this = this;
  83100. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  83101. if (!this._meshes) {
  83102. return;
  83103. }
  83104. var meshHighlight = this._meshes[mesh.uniqueId];
  83105. if (meshHighlight) {
  83106. meshHighlight.color = color;
  83107. }
  83108. else {
  83109. this._meshes[mesh.uniqueId] = {
  83110. mesh: mesh,
  83111. color: color,
  83112. // Lambda required for capture due to Observable this context
  83113. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  83114. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  83115. _this._defaultStencilReference(mesh);
  83116. }
  83117. else {
  83118. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  83119. }
  83120. }),
  83121. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  83122. glowEmissiveOnly: glowEmissiveOnly
  83123. };
  83124. }
  83125. this._shouldRender = true;
  83126. };
  83127. /**
  83128. * Remove a mesh from the highlight layer in order to make it stop glowing.
  83129. * @param mesh The mesh to highlight
  83130. */
  83131. HighlightLayer.prototype.removeMesh = function (mesh) {
  83132. if (!this._meshes) {
  83133. return;
  83134. }
  83135. var meshHighlight = this._meshes[mesh.uniqueId];
  83136. if (meshHighlight) {
  83137. if (meshHighlight.observerHighlight) {
  83138. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83139. }
  83140. if (meshHighlight.observerDefault) {
  83141. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83142. }
  83143. delete this._meshes[mesh.uniqueId];
  83144. }
  83145. this._shouldRender = false;
  83146. for (var meshHighlightToCheck in this._meshes) {
  83147. if (this._meshes[meshHighlightToCheck]) {
  83148. this._shouldRender = true;
  83149. break;
  83150. }
  83151. }
  83152. };
  83153. /**
  83154. * Force the stencil to the normal expected value for none glowing parts
  83155. */
  83156. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  83157. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  83158. };
  83159. /**
  83160. * Free any resources and references associated to a mesh.
  83161. * Internal use
  83162. * @param mesh The mesh to free.
  83163. */
  83164. HighlightLayer.prototype._disposeMesh = function (mesh) {
  83165. this.removeMesh(mesh);
  83166. this.removeExcludedMesh(mesh);
  83167. };
  83168. /**
  83169. * Dispose the highlight layer and free resources.
  83170. */
  83171. HighlightLayer.prototype.dispose = function () {
  83172. if (this._meshes) {
  83173. // Clean mesh references
  83174. for (var id in this._meshes) {
  83175. var meshHighlight = this._meshes[id];
  83176. if (meshHighlight && meshHighlight.mesh) {
  83177. if (meshHighlight.observerHighlight) {
  83178. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83179. }
  83180. if (meshHighlight.observerDefault) {
  83181. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83182. }
  83183. }
  83184. }
  83185. this._meshes = null;
  83186. }
  83187. if (this._excludedMeshes) {
  83188. for (var id in this._excludedMeshes) {
  83189. var meshHighlight = this._excludedMeshes[id];
  83190. if (meshHighlight) {
  83191. if (meshHighlight.beforeRender) {
  83192. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  83193. }
  83194. if (meshHighlight.afterRender) {
  83195. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  83196. }
  83197. }
  83198. }
  83199. this._excludedMeshes = null;
  83200. }
  83201. _super.prototype.dispose.call(this);
  83202. };
  83203. /**
  83204. * Effect Name of the highlight layer.
  83205. */
  83206. HighlightLayer.EffectName = "HighlightLayer";
  83207. /**
  83208. * The neutral color used during the preparation of the glow effect.
  83209. * This is black by default as the blend operation is a blend operation.
  83210. */
  83211. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  83212. /**
  83213. * Stencil value used for glowing meshes.
  83214. */
  83215. HighlightLayer.GlowingMeshStencilReference = 0x02;
  83216. /**
  83217. * Stencil value used for the other meshes in the scene.
  83218. */
  83219. HighlightLayer.NormalMeshStencilReference = 0x01;
  83220. return HighlightLayer;
  83221. }(BABYLON.EffectLayer));
  83222. BABYLON.HighlightLayer = HighlightLayer;
  83223. })(BABYLON || (BABYLON = {}));
  83224. //# sourceMappingURL=babylon.highlightLayer.js.map
  83225. var BABYLON;
  83226. (function (BABYLON) {
  83227. /**
  83228. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  83229. *
  83230. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  83231. * glowy meshes to your scene.
  83232. *
  83233. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  83234. */
  83235. var GlowLayer = /** @class */ (function (_super) {
  83236. __extends(GlowLayer, _super);
  83237. /**
  83238. * Instantiates a new glow Layer and references it to the scene.
  83239. * @param name The name of the layer
  83240. * @param scene The scene to use the layer in
  83241. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  83242. */
  83243. function GlowLayer(name, scene, options) {
  83244. var _this = _super.call(this, name, scene) || this;
  83245. _this.name = name;
  83246. _this._intensity = 1.0;
  83247. _this._includedOnlyMeshes = [];
  83248. _this._excludedMeshes = [];
  83249. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  83250. // Adapt options
  83251. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  83252. // Initialize the layer
  83253. _this._init({
  83254. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  83255. camera: _this._options.camera,
  83256. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  83257. mainTextureRatio: _this._options.mainTextureRatio
  83258. });
  83259. return _this;
  83260. }
  83261. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  83262. /**
  83263. * Gets the kernel size of the blur.
  83264. */
  83265. get: function () {
  83266. return this._horizontalBlurPostprocess1.kernel;
  83267. },
  83268. /**
  83269. * Sets the kernel size of the blur.
  83270. */
  83271. set: function (value) {
  83272. this._horizontalBlurPostprocess1.kernel = value;
  83273. this._verticalBlurPostprocess1.kernel = value;
  83274. this._horizontalBlurPostprocess2.kernel = value;
  83275. this._verticalBlurPostprocess2.kernel = value;
  83276. },
  83277. enumerable: true,
  83278. configurable: true
  83279. });
  83280. Object.defineProperty(GlowLayer.prototype, "intensity", {
  83281. /**
  83282. * Gets the glow intensity.
  83283. */
  83284. get: function () {
  83285. return this._intensity;
  83286. },
  83287. /**
  83288. * Sets the glow intensity.
  83289. */
  83290. set: function (value) {
  83291. this._intensity = value;
  83292. },
  83293. enumerable: true,
  83294. configurable: true
  83295. });
  83296. /**
  83297. * Get the effect name of the layer.
  83298. * @return The effect name
  83299. */
  83300. GlowLayer.prototype.getEffectName = function () {
  83301. return GlowLayer.EffectName;
  83302. };
  83303. /**
  83304. * Create the merge effect. This is the shader use to blit the information back
  83305. * to the main canvas at the end of the scene rendering.
  83306. */
  83307. GlowLayer.prototype._createMergeEffect = function () {
  83308. // Effect
  83309. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  83310. };
  83311. /**
  83312. * Creates the render target textures and post processes used in the glow layer.
  83313. */
  83314. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  83315. var _this = this;
  83316. var blurTextureWidth = this._mainTextureDesiredSize.width;
  83317. var blurTextureHeight = this._mainTextureDesiredSize.height;
  83318. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  83319. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  83320. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  83321. width: blurTextureWidth,
  83322. height: blurTextureHeight
  83323. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83324. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83325. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83326. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83327. this._blurTexture1.renderParticles = false;
  83328. this._blurTexture1.ignoreCameraViewport = true;
  83329. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  83330. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  83331. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  83332. width: blurTextureWidth2,
  83333. height: blurTextureHeight2
  83334. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83335. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83336. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83337. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83338. this._blurTexture2.renderParticles = false;
  83339. this._blurTexture2.ignoreCameraViewport = true;
  83340. this._textures = [this._blurTexture1, this._blurTexture2];
  83341. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83342. width: blurTextureWidth,
  83343. height: blurTextureHeight
  83344. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83345. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  83346. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  83347. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  83348. effect.setTexture("textureSampler", _this._mainTexture);
  83349. });
  83350. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83351. width: blurTextureWidth,
  83352. height: blurTextureHeight
  83353. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83354. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83355. width: blurTextureWidth2,
  83356. height: blurTextureHeight2
  83357. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83358. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  83359. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  83360. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  83361. effect.setTexture("textureSampler", _this._blurTexture1);
  83362. });
  83363. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83364. width: blurTextureWidth2,
  83365. height: blurTextureHeight2
  83366. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83367. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83368. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  83369. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83370. this._mainTexture.samples = this._options.mainTextureSamples;
  83371. this._mainTexture.onAfterUnbindObservable.add(function () {
  83372. var internalTexture = _this._blurTexture1.getInternalTexture();
  83373. if (internalTexture) {
  83374. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  83375. internalTexture = _this._blurTexture2.getInternalTexture();
  83376. if (internalTexture) {
  83377. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  83378. }
  83379. }
  83380. });
  83381. // Prevent autoClear.
  83382. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  83383. };
  83384. /**
  83385. * Checks for the readiness of the element composing the layer.
  83386. * @param subMesh the mesh to check for
  83387. * @param useInstances specify wether or not to use instances to render the mesh
  83388. * @param emissiveTexture the associated emissive texture used to generate the glow
  83389. * @return true if ready otherwise, false
  83390. */
  83391. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  83392. var material = subMesh.getMaterial();
  83393. var mesh = subMesh.getRenderingMesh();
  83394. if (!material || !mesh) {
  83395. return false;
  83396. }
  83397. var emissiveTexture = material.emissiveTexture;
  83398. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  83399. };
  83400. /**
  83401. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  83402. */
  83403. GlowLayer.prototype.needStencil = function () {
  83404. return false;
  83405. };
  83406. /**
  83407. * Implementation specific of rendering the generating effect on the main canvas.
  83408. * @param effect The effect used to render through
  83409. */
  83410. GlowLayer.prototype._internalRender = function (effect) {
  83411. // Texture
  83412. effect.setTexture("textureSampler", this._blurTexture1);
  83413. effect.setTexture("textureSampler2", this._blurTexture2);
  83414. effect.setFloat("offset", this._intensity);
  83415. // Cache
  83416. var engine = this._engine;
  83417. var previousStencilBuffer = engine.getStencilBuffer();
  83418. // Draw order
  83419. engine.setStencilBuffer(false);
  83420. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83421. // Draw order
  83422. engine.setStencilBuffer(previousStencilBuffer);
  83423. };
  83424. /**
  83425. * Sets the required values for both the emissive texture and and the main color.
  83426. */
  83427. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83428. var textureLevel = 1.0;
  83429. if (this.customEmissiveTextureSelector) {
  83430. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  83431. }
  83432. else {
  83433. if (material) {
  83434. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83435. if (this._emissiveTextureAndColor.texture) {
  83436. textureLevel = this._emissiveTextureAndColor.texture.level;
  83437. }
  83438. }
  83439. else {
  83440. this._emissiveTextureAndColor.texture = null;
  83441. }
  83442. }
  83443. if (this.customEmissiveColorSelector) {
  83444. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  83445. }
  83446. else {
  83447. if (material.emissiveColor) {
  83448. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  83449. }
  83450. else {
  83451. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83452. }
  83453. }
  83454. };
  83455. /**
  83456. * Returns true if the mesh should render, otherwise false.
  83457. * @param mesh The mesh to render
  83458. * @returns true if it should render otherwise false
  83459. */
  83460. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  83461. return this.hasMesh(mesh);
  83462. };
  83463. /**
  83464. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  83465. * @param mesh The mesh to exclude from the glow layer
  83466. */
  83467. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  83468. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  83469. this._excludedMeshes.push(mesh.uniqueId);
  83470. }
  83471. };
  83472. /**
  83473. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  83474. * @param mesh The mesh to remove
  83475. */
  83476. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  83477. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  83478. if (index !== -1) {
  83479. this._excludedMeshes.splice(index, 1);
  83480. }
  83481. };
  83482. /**
  83483. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  83484. * @param mesh The mesh to include in the glow layer
  83485. */
  83486. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  83487. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  83488. this._includedOnlyMeshes.push(mesh.uniqueId);
  83489. }
  83490. };
  83491. /**
  83492. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  83493. * @param mesh The mesh to remove
  83494. */
  83495. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  83496. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  83497. if (index !== -1) {
  83498. this._includedOnlyMeshes.splice(index, 1);
  83499. }
  83500. };
  83501. /**
  83502. * Determine if a given mesh will be used in the glow layer
  83503. * @param mesh The mesh to test
  83504. * @returns true if the mesh will be highlighted by the current glow layer
  83505. */
  83506. GlowLayer.prototype.hasMesh = function (mesh) {
  83507. // Included Mesh
  83508. if (this._includedOnlyMeshes.length) {
  83509. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  83510. }
  83511. ;
  83512. // Excluded Mesh
  83513. if (this._excludedMeshes.length) {
  83514. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  83515. }
  83516. ;
  83517. return true;
  83518. };
  83519. /**
  83520. * Free any resources and references associated to a mesh.
  83521. * Internal use
  83522. * @param mesh The mesh to free.
  83523. */
  83524. GlowLayer.prototype._disposeMesh = function (mesh) {
  83525. this.removeIncludedOnlyMesh(mesh);
  83526. this.removeExcludedMesh(mesh);
  83527. };
  83528. /**
  83529. * Effect Name of the layer.
  83530. */
  83531. GlowLayer.EffectName = "GlowLayer";
  83532. /**
  83533. * The default blur kernel size used for the glow.
  83534. */
  83535. GlowLayer.DefaultBlurKernelSize = 32;
  83536. /**
  83537. * The default texture size ratio used for the glow.
  83538. */
  83539. GlowLayer.DefaultTextureRatio = 0.5;
  83540. return GlowLayer;
  83541. }(BABYLON.EffectLayer));
  83542. BABYLON.GlowLayer = GlowLayer;
  83543. })(BABYLON || (BABYLON = {}));
  83544. //# sourceMappingURL=babylon.glowLayer.js.map
  83545. var BABYLON;
  83546. (function (BABYLON) {
  83547. /**
  83548. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  83549. */
  83550. var AssetTaskState;
  83551. (function (AssetTaskState) {
  83552. /**
  83553. * Initialization
  83554. */
  83555. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  83556. /**
  83557. * Running
  83558. */
  83559. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  83560. /**
  83561. * Done
  83562. */
  83563. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  83564. /**
  83565. * Error
  83566. */
  83567. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  83568. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  83569. /**
  83570. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  83571. */
  83572. var AbstractAssetTask = /** @class */ (function () {
  83573. /**
  83574. * Creates a new {BABYLON.AssetsManager}
  83575. * @param name defines the name of the task
  83576. */
  83577. function AbstractAssetTask(
  83578. /**
  83579. * Task name
  83580. */ name) {
  83581. this.name = name;
  83582. this._isCompleted = false;
  83583. this._taskState = AssetTaskState.INIT;
  83584. }
  83585. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  83586. /**
  83587. * Get if the task is completed
  83588. */
  83589. get: function () {
  83590. return this._isCompleted;
  83591. },
  83592. enumerable: true,
  83593. configurable: true
  83594. });
  83595. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  83596. /**
  83597. * Gets the current state of the task
  83598. */
  83599. get: function () {
  83600. return this._taskState;
  83601. },
  83602. enumerable: true,
  83603. configurable: true
  83604. });
  83605. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  83606. /**
  83607. * Gets the current error object (if task is in error)
  83608. */
  83609. get: function () {
  83610. return this._errorObject;
  83611. },
  83612. enumerable: true,
  83613. configurable: true
  83614. });
  83615. /**
  83616. * Internal only
  83617. * @ignore
  83618. */
  83619. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  83620. if (this._errorObject) {
  83621. return;
  83622. }
  83623. this._errorObject = {
  83624. message: message,
  83625. exception: exception
  83626. };
  83627. };
  83628. /**
  83629. * Execute the current task
  83630. * @param scene defines the scene where you want your assets to be loaded
  83631. * @param onSuccess is a callback called when the task is successfully executed
  83632. * @param onError is a callback called if an error occurs
  83633. */
  83634. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  83635. var _this = this;
  83636. this._taskState = AssetTaskState.RUNNING;
  83637. this.runTask(scene, function () {
  83638. _this.onDoneCallback(onSuccess, onError);
  83639. }, function (msg, exception) {
  83640. _this.onErrorCallback(onError, msg, exception);
  83641. });
  83642. };
  83643. /**
  83644. * Execute the current task
  83645. * @param scene defines the scene where you want your assets to be loaded
  83646. * @param onSuccess is a callback called when the task is successfully executed
  83647. * @param onError is a callback called if an error occurs
  83648. */
  83649. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83650. throw new Error("runTask is not implemented");
  83651. };
  83652. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  83653. this._taskState = AssetTaskState.ERROR;
  83654. this._errorObject = {
  83655. message: message,
  83656. exception: exception
  83657. };
  83658. if (this.onError) {
  83659. this.onError(this, message, exception);
  83660. }
  83661. onError();
  83662. };
  83663. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  83664. try {
  83665. this._taskState = AssetTaskState.DONE;
  83666. this._isCompleted = true;
  83667. if (this.onSuccess) {
  83668. this.onSuccess(this);
  83669. }
  83670. onSuccess();
  83671. }
  83672. catch (e) {
  83673. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  83674. }
  83675. };
  83676. return AbstractAssetTask;
  83677. }());
  83678. BABYLON.AbstractAssetTask = AbstractAssetTask;
  83679. /**
  83680. * Class used to share progress information about assets loading
  83681. */
  83682. var AssetsProgressEvent = /** @class */ (function () {
  83683. /**
  83684. * Creates a {BABYLON.AssetsProgressEvent}
  83685. * @param remainingCount defines the number of remaining tasks to process
  83686. * @param totalCount defines the total number of tasks
  83687. * @param task defines the task that was just processed
  83688. */
  83689. function AssetsProgressEvent(remainingCount, totalCount, task) {
  83690. this.remainingCount = remainingCount;
  83691. this.totalCount = totalCount;
  83692. this.task = task;
  83693. }
  83694. return AssetsProgressEvent;
  83695. }());
  83696. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  83697. /**
  83698. * Define a task used by {BABYLON.AssetsManager} to load meshes
  83699. */
  83700. var MeshAssetTask = /** @class */ (function (_super) {
  83701. __extends(MeshAssetTask, _super);
  83702. /**
  83703. * Creates a new {BABYLON.MeshAssetTask}
  83704. * @param name defines the name of the task
  83705. * @param meshesNames defines the list of mesh's names you want to load
  83706. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  83707. * @param sceneFilename defines the filename of the scene to load from
  83708. */
  83709. function MeshAssetTask(
  83710. /**
  83711. * Defines the name of the task
  83712. */
  83713. name,
  83714. /**
  83715. * Defines the list of mesh's names you want to load
  83716. */
  83717. meshesNames,
  83718. /**
  83719. * Defines the root url to use as a base to load your meshes and associated resources
  83720. */
  83721. rootUrl,
  83722. /**
  83723. * Defines the filename of the scene to load from
  83724. */
  83725. sceneFilename) {
  83726. var _this = _super.call(this, name) || this;
  83727. _this.name = name;
  83728. _this.meshesNames = meshesNames;
  83729. _this.rootUrl = rootUrl;
  83730. _this.sceneFilename = sceneFilename;
  83731. return _this;
  83732. }
  83733. /**
  83734. * Execute the current task
  83735. * @param scene defines the scene where you want your assets to be loaded
  83736. * @param onSuccess is a callback called when the task is successfully executed
  83737. * @param onError is a callback called if an error occurs
  83738. */
  83739. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83740. var _this = this;
  83741. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  83742. _this.loadedMeshes = meshes;
  83743. _this.loadedParticleSystems = particleSystems;
  83744. _this.loadedSkeletons = skeletons;
  83745. onSuccess();
  83746. }, null, function (scene, message, exception) {
  83747. onError(message, exception);
  83748. });
  83749. };
  83750. return MeshAssetTask;
  83751. }(AbstractAssetTask));
  83752. BABYLON.MeshAssetTask = MeshAssetTask;
  83753. /**
  83754. * Define a task used by {BABYLON.AssetsManager} to load text content
  83755. */
  83756. var TextFileAssetTask = /** @class */ (function (_super) {
  83757. __extends(TextFileAssetTask, _super);
  83758. /**
  83759. * Creates a new TextFileAssetTask object
  83760. * @param name defines the name of the task
  83761. * @param url defines the location of the file to load
  83762. */
  83763. function TextFileAssetTask(
  83764. /**
  83765. * Defines the name of the task
  83766. */
  83767. name,
  83768. /**
  83769. * Defines the location of the file to load
  83770. */
  83771. url) {
  83772. var _this = _super.call(this, name) || this;
  83773. _this.name = name;
  83774. _this.url = url;
  83775. return _this;
  83776. }
  83777. /**
  83778. * Execute the current task
  83779. * @param scene defines the scene where you want your assets to be loaded
  83780. * @param onSuccess is a callback called when the task is successfully executed
  83781. * @param onError is a callback called if an error occurs
  83782. */
  83783. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83784. var _this = this;
  83785. scene._loadFile(this.url, function (data) {
  83786. _this.text = data;
  83787. onSuccess();
  83788. }, undefined, false, false, function (request, exception) {
  83789. if (request) {
  83790. onError(request.status + " " + request.statusText, exception);
  83791. }
  83792. });
  83793. };
  83794. return TextFileAssetTask;
  83795. }(AbstractAssetTask));
  83796. BABYLON.TextFileAssetTask = TextFileAssetTask;
  83797. /**
  83798. * Define a task used by {BABYLON.AssetsManager} to load binary data
  83799. */
  83800. var BinaryFileAssetTask = /** @class */ (function (_super) {
  83801. __extends(BinaryFileAssetTask, _super);
  83802. /**
  83803. * Creates a new BinaryFileAssetTask object
  83804. * @param name defines the name of the new task
  83805. * @param url defines the location of the file to load
  83806. */
  83807. function BinaryFileAssetTask(
  83808. /**
  83809. * Defines the name of the task
  83810. */
  83811. name,
  83812. /**
  83813. * Defines the location of the file to load
  83814. */
  83815. url) {
  83816. var _this = _super.call(this, name) || this;
  83817. _this.name = name;
  83818. _this.url = url;
  83819. return _this;
  83820. }
  83821. /**
  83822. * Execute the current task
  83823. * @param scene defines the scene where you want your assets to be loaded
  83824. * @param onSuccess is a callback called when the task is successfully executed
  83825. * @param onError is a callback called if an error occurs
  83826. */
  83827. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83828. var _this = this;
  83829. scene._loadFile(this.url, function (data) {
  83830. _this.data = data;
  83831. onSuccess();
  83832. }, undefined, true, true, function (request, exception) {
  83833. if (request) {
  83834. onError(request.status + " " + request.statusText, exception);
  83835. }
  83836. });
  83837. };
  83838. return BinaryFileAssetTask;
  83839. }(AbstractAssetTask));
  83840. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  83841. /**
  83842. * Define a task used by {BABYLON.AssetsManager} to load images
  83843. */
  83844. var ImageAssetTask = /** @class */ (function (_super) {
  83845. __extends(ImageAssetTask, _super);
  83846. /**
  83847. * Creates a new ImageAssetTask
  83848. * @param name defines the name of the task
  83849. * @param url defines the location of the image to load
  83850. */
  83851. function ImageAssetTask(
  83852. /**
  83853. * Defines the name of the task
  83854. */
  83855. name,
  83856. /**
  83857. * Defines the location of the image to load
  83858. */
  83859. url) {
  83860. var _this = _super.call(this, name) || this;
  83861. _this.name = name;
  83862. _this.url = url;
  83863. return _this;
  83864. }
  83865. /**
  83866. * Execute the current task
  83867. * @param scene defines the scene where you want your assets to be loaded
  83868. * @param onSuccess is a callback called when the task is successfully executed
  83869. * @param onError is a callback called if an error occurs
  83870. */
  83871. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83872. var _this = this;
  83873. var img = new Image();
  83874. BABYLON.Tools.SetCorsBehavior(this.url, img);
  83875. img.onload = function () {
  83876. _this.image = img;
  83877. onSuccess();
  83878. };
  83879. img.onerror = function (err) {
  83880. onError("Error loading image", err);
  83881. };
  83882. img.src = this.url;
  83883. };
  83884. return ImageAssetTask;
  83885. }(AbstractAssetTask));
  83886. BABYLON.ImageAssetTask = ImageAssetTask;
  83887. /**
  83888. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  83889. */
  83890. var TextureAssetTask = /** @class */ (function (_super) {
  83891. __extends(TextureAssetTask, _super);
  83892. /**
  83893. * Creates a new TextureAssetTask object
  83894. * @param name defines the name of the task
  83895. * @param url defines the location of the file to load
  83896. * @param noMipmap defines if mipmap should not be generated (default is false)
  83897. * @param invertY defines if texture must be inverted on Y axis (default is false)
  83898. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  83899. */
  83900. function TextureAssetTask(
  83901. /**
  83902. * Defines the name of the task
  83903. */
  83904. name,
  83905. /**
  83906. * Defines the location of the file to load
  83907. */
  83908. url,
  83909. /**
  83910. * Defines if mipmap should not be generated (default is false)
  83911. */
  83912. noMipmap,
  83913. /**
  83914. * Defines if texture must be inverted on Y axis (default is false)
  83915. */
  83916. invertY,
  83917. /**
  83918. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  83919. */
  83920. samplingMode) {
  83921. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  83922. var _this = _super.call(this, name) || this;
  83923. _this.name = name;
  83924. _this.url = url;
  83925. _this.noMipmap = noMipmap;
  83926. _this.invertY = invertY;
  83927. _this.samplingMode = samplingMode;
  83928. return _this;
  83929. }
  83930. /**
  83931. * Execute the current task
  83932. * @param scene defines the scene where you want your assets to be loaded
  83933. * @param onSuccess is a callback called when the task is successfully executed
  83934. * @param onError is a callback called if an error occurs
  83935. */
  83936. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83937. var onload = function () {
  83938. onSuccess();
  83939. };
  83940. var onerror = function (message, exception) {
  83941. onError(message, exception);
  83942. };
  83943. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  83944. };
  83945. return TextureAssetTask;
  83946. }(AbstractAssetTask));
  83947. BABYLON.TextureAssetTask = TextureAssetTask;
  83948. /**
  83949. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  83950. */
  83951. var CubeTextureAssetTask = /** @class */ (function (_super) {
  83952. __extends(CubeTextureAssetTask, _super);
  83953. /**
  83954. * Creates a new CubeTextureAssetTask
  83955. * @param name defines the name of the task
  83956. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  83957. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  83958. * @param noMipmap defines if mipmaps should not be generated (default is false)
  83959. * @param files defines the explicit list of files (undefined by default)
  83960. */
  83961. function CubeTextureAssetTask(
  83962. /**
  83963. * Defines the name of the task
  83964. */
  83965. name,
  83966. /**
  83967. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  83968. */
  83969. url,
  83970. /**
  83971. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  83972. */
  83973. extensions,
  83974. /**
  83975. * Defines if mipmaps should not be generated (default is false)
  83976. */
  83977. noMipmap,
  83978. /**
  83979. * Defines the explicit list of files (undefined by default)
  83980. */
  83981. files) {
  83982. var _this = _super.call(this, name) || this;
  83983. _this.name = name;
  83984. _this.url = url;
  83985. _this.extensions = extensions;
  83986. _this.noMipmap = noMipmap;
  83987. _this.files = files;
  83988. return _this;
  83989. }
  83990. /**
  83991. * Execute the current task
  83992. * @param scene defines the scene where you want your assets to be loaded
  83993. * @param onSuccess is a callback called when the task is successfully executed
  83994. * @param onError is a callback called if an error occurs
  83995. */
  83996. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83997. var onload = function () {
  83998. onSuccess();
  83999. };
  84000. var onerror = function (message, exception) {
  84001. onError(message, exception);
  84002. };
  84003. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  84004. };
  84005. return CubeTextureAssetTask;
  84006. }(AbstractAssetTask));
  84007. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  84008. /**
  84009. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  84010. */
  84011. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  84012. __extends(HDRCubeTextureAssetTask, _super);
  84013. /**
  84014. * Creates a new HDRCubeTextureAssetTask object
  84015. * @param name defines the name of the task
  84016. * @param url defines the location of the file to load
  84017. * @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.
  84018. * @param noMipmap defines if mipmaps should not be generated (default is false)
  84019. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  84020. * @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)
  84021. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  84022. */
  84023. function HDRCubeTextureAssetTask(
  84024. /**
  84025. * Defines the name of the task
  84026. */
  84027. name,
  84028. /**
  84029. * Defines the location of the file to load
  84030. */
  84031. url,
  84032. /**
  84033. * 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.
  84034. */
  84035. size,
  84036. /**
  84037. * Defines if mipmaps should not be generated (default is false)
  84038. */
  84039. noMipmap,
  84040. /**
  84041. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  84042. */
  84043. generateHarmonics,
  84044. /**
  84045. * 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)
  84046. */
  84047. useInGammaSpace,
  84048. /**
  84049. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  84050. */
  84051. usePMREMGenerator) {
  84052. if (noMipmap === void 0) { noMipmap = false; }
  84053. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84054. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  84055. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  84056. var _this = _super.call(this, name) || this;
  84057. _this.name = name;
  84058. _this.url = url;
  84059. _this.size = size;
  84060. _this.noMipmap = noMipmap;
  84061. _this.generateHarmonics = generateHarmonics;
  84062. _this.useInGammaSpace = useInGammaSpace;
  84063. _this.usePMREMGenerator = usePMREMGenerator;
  84064. return _this;
  84065. }
  84066. /**
  84067. * Execute the current task
  84068. * @param scene defines the scene where you want your assets to be loaded
  84069. * @param onSuccess is a callback called when the task is successfully executed
  84070. * @param onError is a callback called if an error occurs
  84071. */
  84072. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  84073. var onload = function () {
  84074. onSuccess();
  84075. };
  84076. var onerror = function (message, exception) {
  84077. onError(message, exception);
  84078. };
  84079. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  84080. };
  84081. return HDRCubeTextureAssetTask;
  84082. }(AbstractAssetTask));
  84083. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  84084. /**
  84085. * This class can be used to easily import assets into a scene
  84086. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  84087. */
  84088. var AssetsManager = /** @class */ (function () {
  84089. /**
  84090. * Creates a new AssetsManager
  84091. * @param scene defines the scene to work on
  84092. */
  84093. function AssetsManager(scene) {
  84094. this._isLoading = false;
  84095. this._tasks = new Array();
  84096. this._waitingTasksCount = 0;
  84097. this._totalTasksCount = 0;
  84098. /**
  84099. * Observable called when all tasks are processed
  84100. */
  84101. this.onTaskSuccessObservable = new BABYLON.Observable();
  84102. /**
  84103. * Observable called when a task had an error
  84104. */
  84105. this.onTaskErrorObservable = new BABYLON.Observable();
  84106. /**
  84107. * Observable called when a task is successful
  84108. */
  84109. this.onTasksDoneObservable = new BABYLON.Observable();
  84110. /**
  84111. * Observable called when a task is done (whatever the result is)
  84112. */
  84113. this.onProgressObservable = new BABYLON.Observable();
  84114. /**
  84115. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  84116. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  84117. */
  84118. this.useDefaultLoadingScreen = true;
  84119. this._scene = scene;
  84120. }
  84121. /**
  84122. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  84123. * @param taskName defines the name of the new task
  84124. * @param meshesNames defines the name of meshes to load
  84125. * @param rootUrl defines the root url to use to locate files
  84126. * @param sceneFilename defines the filename of the scene file
  84127. * @returns a new {BABYLON.MeshAssetTask} object
  84128. */
  84129. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  84130. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  84131. this._tasks.push(task);
  84132. return task;
  84133. };
  84134. /**
  84135. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  84136. * @param taskName defines the name of the new task
  84137. * @param url defines the url of the file to load
  84138. * @returns a new {BABYLON.TextFileAssetTask} object
  84139. */
  84140. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  84141. var task = new TextFileAssetTask(taskName, url);
  84142. this._tasks.push(task);
  84143. return task;
  84144. };
  84145. /**
  84146. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  84147. * @param taskName defines the name of the new task
  84148. * @param url defines the url of the file to load
  84149. * @returns a new {BABYLON.BinaryFileAssetTask} object
  84150. */
  84151. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  84152. var task = new BinaryFileAssetTask(taskName, url);
  84153. this._tasks.push(task);
  84154. return task;
  84155. };
  84156. /**
  84157. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  84158. * @param taskName defines the name of the new task
  84159. * @param url defines the url of the file to load
  84160. * @returns a new {BABYLON.ImageAssetTask} object
  84161. */
  84162. AssetsManager.prototype.addImageTask = function (taskName, url) {
  84163. var task = new ImageAssetTask(taskName, url);
  84164. this._tasks.push(task);
  84165. return task;
  84166. };
  84167. /**
  84168. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  84169. * @param taskName defines the name of the new task
  84170. * @param url defines the url of the file to load
  84171. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84172. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  84173. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  84174. * @returns a new {BABYLON.TextureAssetTask} object
  84175. */
  84176. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  84177. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  84178. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  84179. this._tasks.push(task);
  84180. return task;
  84181. };
  84182. /**
  84183. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  84184. * @param taskName defines the name of the new task
  84185. * @param url defines the url of the file to load
  84186. * @param extensions defines the extension to use to load the cube map (can be null)
  84187. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84188. * @param files defines the list of files to load (can be null)
  84189. * @returns a new {BABYLON.CubeTextureAssetTask} object
  84190. */
  84191. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  84192. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  84193. this._tasks.push(task);
  84194. return task;
  84195. };
  84196. /**
  84197. *
  84198. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  84199. * @param taskName defines the name of the new task
  84200. * @param url defines the url of the file to load
  84201. * @param size defines the size you want for the cubemap (can be null)
  84202. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84203. * @param generateHarmonics defines if you want to automatically generate (true by default)
  84204. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  84205. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  84206. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  84207. */
  84208. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  84209. if (noMipmap === void 0) { noMipmap = false; }
  84210. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84211. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  84212. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  84213. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  84214. this._tasks.push(task);
  84215. return task;
  84216. };
  84217. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  84218. var _this = this;
  84219. this._waitingTasksCount--;
  84220. try {
  84221. if (task.taskState === AssetTaskState.DONE) {
  84222. // Let's remove successfull tasks
  84223. BABYLON.Tools.SetImmediate(function () {
  84224. var index = _this._tasks.indexOf(task);
  84225. if (index > -1) {
  84226. _this._tasks.splice(index, 1);
  84227. }
  84228. });
  84229. }
  84230. if (this.onProgress) {
  84231. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  84232. }
  84233. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  84234. }
  84235. catch (e) {
  84236. BABYLON.Tools.Error("Error running progress callbacks.");
  84237. console.log(e);
  84238. }
  84239. if (this._waitingTasksCount === 0) {
  84240. try {
  84241. if (this.onFinish) {
  84242. this.onFinish(this._tasks);
  84243. }
  84244. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84245. }
  84246. catch (e) {
  84247. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  84248. console.log(e);
  84249. }
  84250. this._isLoading = false;
  84251. this._scene.getEngine().hideLoadingUI();
  84252. }
  84253. };
  84254. AssetsManager.prototype._runTask = function (task) {
  84255. var _this = this;
  84256. var done = function () {
  84257. try {
  84258. if (_this.onTaskSuccess) {
  84259. _this.onTaskSuccess(task);
  84260. }
  84261. _this.onTaskSuccessObservable.notifyObservers(task);
  84262. _this._decreaseWaitingTasksCount(task);
  84263. }
  84264. catch (e) {
  84265. error("Error executing task success callbacks", e);
  84266. }
  84267. };
  84268. var error = function (message, exception) {
  84269. task._setErrorObject(message, exception);
  84270. if (_this.onTaskError) {
  84271. _this.onTaskError(task);
  84272. }
  84273. _this.onTaskErrorObservable.notifyObservers(task);
  84274. _this._decreaseWaitingTasksCount(task);
  84275. };
  84276. task.run(this._scene, done, error);
  84277. };
  84278. /**
  84279. * Reset the {BABYLON.AssetsManager} and remove all tasks
  84280. * @return the current instance of the {BABYLON.AssetsManager}
  84281. */
  84282. AssetsManager.prototype.reset = function () {
  84283. this._isLoading = false;
  84284. this._tasks = new Array();
  84285. return this;
  84286. };
  84287. /**
  84288. * Start the loading process
  84289. * @return the current instance of the {BABYLON.AssetsManager}
  84290. */
  84291. AssetsManager.prototype.load = function () {
  84292. if (this._isLoading) {
  84293. return this;
  84294. }
  84295. this._isLoading = true;
  84296. this._waitingTasksCount = this._tasks.length;
  84297. this._totalTasksCount = this._tasks.length;
  84298. if (this._waitingTasksCount === 0) {
  84299. if (this.onFinish) {
  84300. this.onFinish(this._tasks);
  84301. }
  84302. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84303. return this;
  84304. }
  84305. if (this.useDefaultLoadingScreen) {
  84306. this._scene.getEngine().displayLoadingUI();
  84307. }
  84308. for (var index = 0; index < this._tasks.length; index++) {
  84309. var task = this._tasks[index];
  84310. this._runTask(task);
  84311. }
  84312. return this;
  84313. };
  84314. return AssetsManager;
  84315. }());
  84316. BABYLON.AssetsManager = AssetsManager;
  84317. })(BABYLON || (BABYLON = {}));
  84318. //# sourceMappingURL=babylon.assetsManager.js.map
  84319. var BABYLON;
  84320. (function (BABYLON) {
  84321. var serializedGeometries = [];
  84322. var serializeGeometry = function (geometry, serializationGeometries) {
  84323. if (serializedGeometries[geometry.id]) {
  84324. return;
  84325. }
  84326. if (geometry.doNotSerialize) {
  84327. return;
  84328. }
  84329. if (geometry instanceof BABYLON.BoxGeometry) {
  84330. serializationGeometries.boxes.push(geometry.serialize());
  84331. }
  84332. else if (geometry instanceof BABYLON.SphereGeometry) {
  84333. serializationGeometries.spheres.push(geometry.serialize());
  84334. }
  84335. else if (geometry instanceof BABYLON.CylinderGeometry) {
  84336. serializationGeometries.cylinders.push(geometry.serialize());
  84337. }
  84338. else if (geometry instanceof BABYLON.TorusGeometry) {
  84339. serializationGeometries.toruses.push(geometry.serialize());
  84340. }
  84341. else if (geometry instanceof BABYLON.GroundGeometry) {
  84342. serializationGeometries.grounds.push(geometry.serialize());
  84343. }
  84344. else if (geometry instanceof BABYLON.Plane) {
  84345. serializationGeometries.planes.push(geometry.serialize());
  84346. }
  84347. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  84348. serializationGeometries.torusKnots.push(geometry.serialize());
  84349. }
  84350. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  84351. throw new Error("Unknown primitive type");
  84352. }
  84353. else {
  84354. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  84355. }
  84356. serializedGeometries[geometry.id] = true;
  84357. };
  84358. var serializeMesh = function (mesh, serializationScene) {
  84359. var serializationObject = {};
  84360. // Geometry
  84361. var geometry = mesh._geometry;
  84362. if (geometry) {
  84363. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  84364. // 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
  84365. serializeGeometry(geometry, serializationScene.geometries);
  84366. }
  84367. }
  84368. // Custom
  84369. if (mesh.serialize) {
  84370. mesh.serialize(serializationObject);
  84371. }
  84372. return serializationObject;
  84373. };
  84374. var finalizeSingleMesh = function (mesh, serializationObject) {
  84375. //only works if the mesh is already loaded
  84376. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84377. //serialize material
  84378. if (mesh.material) {
  84379. if (mesh.material instanceof BABYLON.StandardMaterial) {
  84380. serializationObject.materials = serializationObject.materials || [];
  84381. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84382. serializationObject.materials.push(mesh.material.serialize());
  84383. }
  84384. }
  84385. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  84386. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  84387. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84388. serializationObject.multiMaterials.push(mesh.material.serialize());
  84389. }
  84390. }
  84391. }
  84392. //serialize geometry
  84393. var geometry = mesh._geometry;
  84394. if (geometry) {
  84395. if (!serializationObject.geometries) {
  84396. serializationObject.geometries = {};
  84397. serializationObject.geometries.boxes = [];
  84398. serializationObject.geometries.spheres = [];
  84399. serializationObject.geometries.cylinders = [];
  84400. serializationObject.geometries.toruses = [];
  84401. serializationObject.geometries.grounds = [];
  84402. serializationObject.geometries.planes = [];
  84403. serializationObject.geometries.torusKnots = [];
  84404. serializationObject.geometries.vertexData = [];
  84405. }
  84406. serializeGeometry(geometry, serializationObject.geometries);
  84407. }
  84408. // Skeletons
  84409. if (mesh.skeleton) {
  84410. serializationObject.skeletons = serializationObject.skeletons || [];
  84411. serializationObject.skeletons.push(mesh.skeleton.serialize());
  84412. }
  84413. //serialize the actual mesh
  84414. serializationObject.meshes = serializationObject.meshes || [];
  84415. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84416. }
  84417. };
  84418. var SceneSerializer = /** @class */ (function () {
  84419. function SceneSerializer() {
  84420. }
  84421. SceneSerializer.ClearCache = function () {
  84422. serializedGeometries = [];
  84423. };
  84424. SceneSerializer.Serialize = function (scene) {
  84425. var serializationObject = {};
  84426. SceneSerializer.ClearCache();
  84427. // Scene
  84428. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  84429. serializationObject.autoClear = scene.autoClear;
  84430. serializationObject.clearColor = scene.clearColor.asArray();
  84431. serializationObject.ambientColor = scene.ambientColor.asArray();
  84432. serializationObject.gravity = scene.gravity.asArray();
  84433. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  84434. serializationObject.workerCollisions = scene.workerCollisions;
  84435. // Fog
  84436. if (scene.fogMode && scene.fogMode !== 0) {
  84437. serializationObject.fogMode = scene.fogMode;
  84438. serializationObject.fogColor = scene.fogColor.asArray();
  84439. serializationObject.fogStart = scene.fogStart;
  84440. serializationObject.fogEnd = scene.fogEnd;
  84441. serializationObject.fogDensity = scene.fogDensity;
  84442. }
  84443. //Physics
  84444. if (scene.isPhysicsEnabled()) {
  84445. var physicEngine = scene.getPhysicsEngine();
  84446. if (physicEngine) {
  84447. serializationObject.physicsEnabled = true;
  84448. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  84449. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  84450. }
  84451. }
  84452. // Metadata
  84453. if (scene.metadata) {
  84454. serializationObject.metadata = scene.metadata;
  84455. }
  84456. // Morph targets
  84457. serializationObject.morphTargetManagers = [];
  84458. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  84459. var abstractMesh = _a[_i];
  84460. var manager = abstractMesh.morphTargetManager;
  84461. if (manager) {
  84462. serializationObject.morphTargetManagers.push(manager.serialize());
  84463. }
  84464. }
  84465. // Lights
  84466. serializationObject.lights = [];
  84467. var index;
  84468. var light;
  84469. for (index = 0; index < scene.lights.length; index++) {
  84470. light = scene.lights[index];
  84471. if (!light.doNotSerialize) {
  84472. serializationObject.lights.push(light.serialize());
  84473. }
  84474. }
  84475. // Cameras
  84476. serializationObject.cameras = [];
  84477. for (index = 0; index < scene.cameras.length; index++) {
  84478. var camera = scene.cameras[index];
  84479. if (!camera.doNotSerialize) {
  84480. serializationObject.cameras.push(camera.serialize());
  84481. }
  84482. }
  84483. if (scene.activeCamera) {
  84484. serializationObject.activeCameraID = scene.activeCamera.id;
  84485. }
  84486. // Animations
  84487. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  84488. // Materials
  84489. serializationObject.materials = [];
  84490. serializationObject.multiMaterials = [];
  84491. var material;
  84492. for (index = 0; index < scene.materials.length; index++) {
  84493. material = scene.materials[index];
  84494. if (!material.doNotSerialize) {
  84495. serializationObject.materials.push(material.serialize());
  84496. }
  84497. }
  84498. // MultiMaterials
  84499. serializationObject.multiMaterials = [];
  84500. for (index = 0; index < scene.multiMaterials.length; index++) {
  84501. var multiMaterial = scene.multiMaterials[index];
  84502. serializationObject.multiMaterials.push(multiMaterial.serialize());
  84503. }
  84504. // Environment texture
  84505. if (scene.environmentTexture) {
  84506. serializationObject.environmentTexture = scene.environmentTexture.name;
  84507. }
  84508. // Skeletons
  84509. serializationObject.skeletons = [];
  84510. for (index = 0; index < scene.skeletons.length; index++) {
  84511. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  84512. }
  84513. // Transform nodes
  84514. serializationObject.transformNodes = [];
  84515. for (index = 0; index < scene.transformNodes.length; index++) {
  84516. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  84517. }
  84518. // Geometries
  84519. serializationObject.geometries = {};
  84520. serializationObject.geometries.boxes = [];
  84521. serializationObject.geometries.spheres = [];
  84522. serializationObject.geometries.cylinders = [];
  84523. serializationObject.geometries.toruses = [];
  84524. serializationObject.geometries.grounds = [];
  84525. serializationObject.geometries.planes = [];
  84526. serializationObject.geometries.torusKnots = [];
  84527. serializationObject.geometries.vertexData = [];
  84528. serializedGeometries = [];
  84529. var geometries = scene.getGeometries();
  84530. for (index = 0; index < geometries.length; index++) {
  84531. var geometry = geometries[index];
  84532. if (geometry.isReady()) {
  84533. serializeGeometry(geometry, serializationObject.geometries);
  84534. }
  84535. }
  84536. // Meshes
  84537. serializationObject.meshes = [];
  84538. for (index = 0; index < scene.meshes.length; index++) {
  84539. var abstractMesh = scene.meshes[index];
  84540. if (abstractMesh instanceof BABYLON.Mesh) {
  84541. var mesh = abstractMesh;
  84542. if (!mesh.doNotSerialize) {
  84543. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84544. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84545. }
  84546. }
  84547. }
  84548. }
  84549. // Particles Systems
  84550. serializationObject.particleSystems = [];
  84551. for (index = 0; index < scene.particleSystems.length; index++) {
  84552. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  84553. }
  84554. // Lens flares
  84555. serializationObject.lensFlareSystems = [];
  84556. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  84557. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  84558. }
  84559. // Shadows
  84560. serializationObject.shadowGenerators = [];
  84561. for (index = 0; index < scene.lights.length; index++) {
  84562. light = scene.lights[index];
  84563. var shadowGenerator = light.getShadowGenerator();
  84564. if (shadowGenerator) {
  84565. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  84566. }
  84567. }
  84568. // Action Manager
  84569. if (scene.actionManager) {
  84570. serializationObject.actions = scene.actionManager.serialize("scene");
  84571. }
  84572. // Audio
  84573. serializationObject.sounds = [];
  84574. for (index = 0; index < scene.soundTracks.length; index++) {
  84575. var soundtrack = scene.soundTracks[index];
  84576. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  84577. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  84578. }
  84579. }
  84580. return serializationObject;
  84581. };
  84582. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  84583. if (withParents === void 0) { withParents = false; }
  84584. if (withChildren === void 0) { withChildren = false; }
  84585. var serializationObject = {};
  84586. SceneSerializer.ClearCache();
  84587. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  84588. if (withParents || withChildren) {
  84589. //deliberate for loop! not for each, appended should be processed as well.
  84590. for (var i = 0; i < toSerialize.length; ++i) {
  84591. if (withChildren) {
  84592. toSerialize[i].getDescendants().forEach(function (node) {
  84593. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  84594. toSerialize.push(node);
  84595. }
  84596. });
  84597. }
  84598. //make sure the array doesn't contain the object already
  84599. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  84600. toSerialize.push(toSerialize[i].parent);
  84601. }
  84602. }
  84603. }
  84604. toSerialize.forEach(function (mesh) {
  84605. finalizeSingleMesh(mesh, serializationObject);
  84606. });
  84607. return serializationObject;
  84608. };
  84609. return SceneSerializer;
  84610. }());
  84611. BABYLON.SceneSerializer = SceneSerializer;
  84612. })(BABYLON || (BABYLON = {}));
  84613. //# sourceMappingURL=babylon.sceneSerializer.js.map
  84614. var BABYLON;
  84615. (function (BABYLON) {
  84616. var ReflectionProbe = /** @class */ (function () {
  84617. function ReflectionProbe(name, size, scene, generateMipMaps) {
  84618. if (generateMipMaps === void 0) { generateMipMaps = true; }
  84619. var _this = this;
  84620. this.name = name;
  84621. this._viewMatrix = BABYLON.Matrix.Identity();
  84622. this._target = BABYLON.Vector3.Zero();
  84623. this._add = BABYLON.Vector3.Zero();
  84624. this.invertYAxis = false;
  84625. this.position = BABYLON.Vector3.Zero();
  84626. this._scene = scene;
  84627. this._scene.reflectionProbes.push(this);
  84628. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  84629. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  84630. switch (faceIndex) {
  84631. case 0:
  84632. _this._add.copyFromFloats(1, 0, 0);
  84633. break;
  84634. case 1:
  84635. _this._add.copyFromFloats(-1, 0, 0);
  84636. break;
  84637. case 2:
  84638. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  84639. break;
  84640. case 3:
  84641. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  84642. break;
  84643. case 4:
  84644. _this._add.copyFromFloats(0, 0, 1);
  84645. break;
  84646. case 5:
  84647. _this._add.copyFromFloats(0, 0, -1);
  84648. break;
  84649. }
  84650. if (_this._attachedMesh) {
  84651. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  84652. }
  84653. _this.position.addToRef(_this._add, _this._target);
  84654. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  84655. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  84656. scene._forcedViewPosition = _this.position;
  84657. });
  84658. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  84659. scene._forcedViewPosition = null;
  84660. scene.updateTransformMatrix(true);
  84661. });
  84662. if (scene.activeCamera) {
  84663. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  84664. }
  84665. }
  84666. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  84667. get: function () {
  84668. return this._renderTargetTexture.samples;
  84669. },
  84670. set: function (value) {
  84671. this._renderTargetTexture.samples = value;
  84672. },
  84673. enumerable: true,
  84674. configurable: true
  84675. });
  84676. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  84677. get: function () {
  84678. return this._renderTargetTexture.refreshRate;
  84679. },
  84680. set: function (value) {
  84681. this._renderTargetTexture.refreshRate = value;
  84682. },
  84683. enumerable: true,
  84684. configurable: true
  84685. });
  84686. ReflectionProbe.prototype.getScene = function () {
  84687. return this._scene;
  84688. };
  84689. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  84690. get: function () {
  84691. return this._renderTargetTexture;
  84692. },
  84693. enumerable: true,
  84694. configurable: true
  84695. });
  84696. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  84697. get: function () {
  84698. return this._renderTargetTexture.renderList;
  84699. },
  84700. enumerable: true,
  84701. configurable: true
  84702. });
  84703. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  84704. this._attachedMesh = mesh;
  84705. };
  84706. /**
  84707. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  84708. *
  84709. * @param renderingGroupId The rendering group id corresponding to its index
  84710. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  84711. */
  84712. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  84713. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  84714. };
  84715. ReflectionProbe.prototype.dispose = function () {
  84716. var index = this._scene.reflectionProbes.indexOf(this);
  84717. if (index !== -1) {
  84718. // Remove from the scene if found
  84719. this._scene.reflectionProbes.splice(index, 1);
  84720. }
  84721. if (this._renderTargetTexture) {
  84722. this._renderTargetTexture.dispose();
  84723. this._renderTargetTexture = null;
  84724. }
  84725. };
  84726. return ReflectionProbe;
  84727. }());
  84728. BABYLON.ReflectionProbe = ReflectionProbe;
  84729. })(BABYLON || (BABYLON = {}));
  84730. //# sourceMappingURL=babylon.reflectionProbe.js.map
  84731. var BABYLON;
  84732. (function (BABYLON) {
  84733. var Layer = /** @class */ (function () {
  84734. function Layer(name, imgUrl, scene, isBackground, color) {
  84735. this.name = name;
  84736. this.scale = new BABYLON.Vector2(1, 1);
  84737. this.offset = new BABYLON.Vector2(0, 0);
  84738. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  84739. this.layerMask = 0x0FFFFFFF;
  84740. this._vertexBuffers = {};
  84741. // Events
  84742. /**
  84743. * An event triggered when the layer is disposed.
  84744. * @type {BABYLON.Observable}
  84745. */
  84746. this.onDisposeObservable = new BABYLON.Observable();
  84747. /**
  84748. * An event triggered before rendering the scene
  84749. * @type {BABYLON.Observable}
  84750. */
  84751. this.onBeforeRenderObservable = new BABYLON.Observable();
  84752. /**
  84753. * An event triggered after rendering the scene
  84754. * @type {BABYLON.Observable}
  84755. */
  84756. this.onAfterRenderObservable = new BABYLON.Observable();
  84757. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  84758. this.isBackground = isBackground === undefined ? true : isBackground;
  84759. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  84760. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  84761. this._scene.layers.push(this);
  84762. var engine = this._scene.getEngine();
  84763. // VBO
  84764. var vertices = [];
  84765. vertices.push(1, 1);
  84766. vertices.push(-1, 1);
  84767. vertices.push(-1, -1);
  84768. vertices.push(1, -1);
  84769. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84770. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84771. this._createIndexBuffer();
  84772. // Effects
  84773. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  84774. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  84775. }
  84776. Object.defineProperty(Layer.prototype, "onDispose", {
  84777. set: function (callback) {
  84778. if (this._onDisposeObserver) {
  84779. this.onDisposeObservable.remove(this._onDisposeObserver);
  84780. }
  84781. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  84782. },
  84783. enumerable: true,
  84784. configurable: true
  84785. });
  84786. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  84787. set: function (callback) {
  84788. if (this._onBeforeRenderObserver) {
  84789. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  84790. }
  84791. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  84792. },
  84793. enumerable: true,
  84794. configurable: true
  84795. });
  84796. Object.defineProperty(Layer.prototype, "onAfterRender", {
  84797. set: function (callback) {
  84798. if (this._onAfterRenderObserver) {
  84799. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  84800. }
  84801. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  84802. },
  84803. enumerable: true,
  84804. configurable: true
  84805. });
  84806. Layer.prototype._createIndexBuffer = function () {
  84807. var engine = this._scene.getEngine();
  84808. // Indices
  84809. var indices = [];
  84810. indices.push(0);
  84811. indices.push(1);
  84812. indices.push(2);
  84813. indices.push(0);
  84814. indices.push(2);
  84815. indices.push(3);
  84816. this._indexBuffer = engine.createIndexBuffer(indices);
  84817. };
  84818. Layer.prototype._rebuild = function () {
  84819. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84820. if (vb) {
  84821. vb._rebuild();
  84822. }
  84823. this._createIndexBuffer();
  84824. };
  84825. Layer.prototype.render = function () {
  84826. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  84827. // Check
  84828. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  84829. return;
  84830. var engine = this._scene.getEngine();
  84831. this.onBeforeRenderObservable.notifyObservers(this);
  84832. // Render
  84833. engine.enableEffect(currentEffect);
  84834. engine.setState(false);
  84835. // Texture
  84836. currentEffect.setTexture("textureSampler", this.texture);
  84837. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  84838. // Color
  84839. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  84840. // Scale / offset
  84841. currentEffect.setVector2("offset", this.offset);
  84842. currentEffect.setVector2("scale", this.scale);
  84843. // VBOs
  84844. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84845. // Draw order
  84846. if (!this.alphaTest) {
  84847. engine.setAlphaMode(this.alphaBlendingMode);
  84848. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84849. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84850. }
  84851. else {
  84852. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84853. }
  84854. this.onAfterRenderObservable.notifyObservers(this);
  84855. };
  84856. Layer.prototype.dispose = function () {
  84857. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84858. if (vertexBuffer) {
  84859. vertexBuffer.dispose();
  84860. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84861. }
  84862. if (this._indexBuffer) {
  84863. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84864. this._indexBuffer = null;
  84865. }
  84866. if (this.texture) {
  84867. this.texture.dispose();
  84868. this.texture = null;
  84869. }
  84870. // Remove from scene
  84871. var index = this._scene.layers.indexOf(this);
  84872. this._scene.layers.splice(index, 1);
  84873. // Callback
  84874. this.onDisposeObservable.notifyObservers(this);
  84875. this.onDisposeObservable.clear();
  84876. this.onAfterRenderObservable.clear();
  84877. this.onBeforeRenderObservable.clear();
  84878. };
  84879. return Layer;
  84880. }());
  84881. BABYLON.Layer = Layer;
  84882. })(BABYLON || (BABYLON = {}));
  84883. //# sourceMappingURL=babylon.layer.js.map
  84884. var BABYLON;
  84885. (function (BABYLON) {
  84886. var TextureTools = /** @class */ (function () {
  84887. function TextureTools() {
  84888. }
  84889. /**
  84890. * Uses the GPU to create a copy texture rescaled at a given size
  84891. * @param texture Texture to copy from
  84892. * @param width Desired width
  84893. * @param height Desired height
  84894. * @return Generated texture
  84895. */
  84896. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  84897. if (useBilinearMode === void 0) { useBilinearMode = true; }
  84898. var scene = texture.getScene();
  84899. var engine = scene.getEngine();
  84900. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  84901. rtt.wrapU = texture.wrapU;
  84902. rtt.wrapV = texture.wrapV;
  84903. rtt.uOffset = texture.uOffset;
  84904. rtt.vOffset = texture.vOffset;
  84905. rtt.uScale = texture.uScale;
  84906. rtt.vScale = texture.vScale;
  84907. rtt.uAng = texture.uAng;
  84908. rtt.vAng = texture.vAng;
  84909. rtt.wAng = texture.wAng;
  84910. rtt.coordinatesIndex = texture.coordinatesIndex;
  84911. rtt.level = texture.level;
  84912. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  84913. rtt._texture.isReady = false;
  84914. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84915. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84916. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84917. passPostProcess.getEffect().executeWhenCompiled(function () {
  84918. passPostProcess.onApply = function (effect) {
  84919. effect.setTexture("textureSampler", texture);
  84920. };
  84921. var internalTexture = rtt.getInternalTexture();
  84922. if (internalTexture) {
  84923. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  84924. engine.unBindFramebuffer(internalTexture);
  84925. rtt.disposeFramebufferObjects();
  84926. passPostProcess.dispose();
  84927. internalTexture.isReady = true;
  84928. }
  84929. });
  84930. return rtt;
  84931. };
  84932. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  84933. if (!scene._environmentBRDFTexture) {
  84934. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84935. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84936. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84937. scene._environmentBRDFTexture = texture;
  84938. }
  84939. return scene._environmentBRDFTexture;
  84940. };
  84941. 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=";
  84942. return TextureTools;
  84943. }());
  84944. BABYLON.TextureTools = TextureTools;
  84945. })(BABYLON || (BABYLON = {}));
  84946. //# sourceMappingURL=babylon.textureTools.js.map
  84947. var BABYLON;
  84948. (function (BABYLON) {
  84949. var FramingBehavior = /** @class */ (function () {
  84950. function FramingBehavior() {
  84951. this._mode = FramingBehavior.FitFrustumSidesMode;
  84952. this._radiusScale = 1.0;
  84953. this._positionScale = 0.5;
  84954. this._defaultElevation = 0.3;
  84955. this._elevationReturnTime = 1500;
  84956. this._elevationReturnWaitTime = 1000;
  84957. this._zoomStopsAnimation = false;
  84958. this._framingTime = 1500;
  84959. this._isPointerDown = false;
  84960. this._lastInteractionTime = -Infinity;
  84961. // Framing control
  84962. this._animatables = new Array();
  84963. this._betaIsAnimating = false;
  84964. }
  84965. Object.defineProperty(FramingBehavior.prototype, "name", {
  84966. get: function () {
  84967. return "Framing";
  84968. },
  84969. enumerable: true,
  84970. configurable: true
  84971. });
  84972. Object.defineProperty(FramingBehavior.prototype, "mode", {
  84973. /**
  84974. * Gets current mode used by the behavior.
  84975. */
  84976. get: function () {
  84977. return this._mode;
  84978. },
  84979. /**
  84980. * Sets the current mode used by the behavior
  84981. */
  84982. set: function (mode) {
  84983. this._mode = mode;
  84984. },
  84985. enumerable: true,
  84986. configurable: true
  84987. });
  84988. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  84989. /**
  84990. * Gets the scale applied to the radius
  84991. */
  84992. get: function () {
  84993. return this._radiusScale;
  84994. },
  84995. /**
  84996. * Sets the scale applied to the radius (1 by default)
  84997. */
  84998. set: function (radius) {
  84999. this._radiusScale = radius;
  85000. },
  85001. enumerable: true,
  85002. configurable: true
  85003. });
  85004. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  85005. /**
  85006. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  85007. */
  85008. get: function () {
  85009. return this._positionScale;
  85010. },
  85011. /**
  85012. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  85013. */
  85014. set: function (scale) {
  85015. this._positionScale = scale;
  85016. },
  85017. enumerable: true,
  85018. configurable: true
  85019. });
  85020. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  85021. /**
  85022. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  85023. * behaviour is triggered, in radians.
  85024. */
  85025. get: function () {
  85026. return this._defaultElevation;
  85027. },
  85028. /**
  85029. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  85030. * behaviour is triggered, in radians.
  85031. */
  85032. set: function (elevation) {
  85033. this._defaultElevation = elevation;
  85034. },
  85035. enumerable: true,
  85036. configurable: true
  85037. });
  85038. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  85039. /**
  85040. * Gets the time (in milliseconds) taken to return to the default beta position.
  85041. * Negative value indicates camera should not return to default.
  85042. */
  85043. get: function () {
  85044. return this._elevationReturnTime;
  85045. },
  85046. /**
  85047. * Sets the time (in milliseconds) taken to return to the default beta position.
  85048. * Negative value indicates camera should not return to default.
  85049. */
  85050. set: function (speed) {
  85051. this._elevationReturnTime = speed;
  85052. },
  85053. enumerable: true,
  85054. configurable: true
  85055. });
  85056. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  85057. /**
  85058. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  85059. */
  85060. get: function () {
  85061. return this._elevationReturnWaitTime;
  85062. },
  85063. /**
  85064. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  85065. */
  85066. set: function (time) {
  85067. this._elevationReturnWaitTime = time;
  85068. },
  85069. enumerable: true,
  85070. configurable: true
  85071. });
  85072. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  85073. /**
  85074. * Gets the flag that indicates if user zooming should stop animation.
  85075. */
  85076. get: function () {
  85077. return this._zoomStopsAnimation;
  85078. },
  85079. /**
  85080. * Sets the flag that indicates if user zooming should stop animation.
  85081. */
  85082. set: function (flag) {
  85083. this._zoomStopsAnimation = flag;
  85084. },
  85085. enumerable: true,
  85086. configurable: true
  85087. });
  85088. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  85089. /**
  85090. * Gets the transition time when framing the mesh, in milliseconds
  85091. */
  85092. get: function () {
  85093. return this._framingTime;
  85094. },
  85095. /**
  85096. * Sets the transition time when framing the mesh, in milliseconds
  85097. */
  85098. set: function (time) {
  85099. this._framingTime = time;
  85100. },
  85101. enumerable: true,
  85102. configurable: true
  85103. });
  85104. FramingBehavior.prototype.init = function () {
  85105. // Do notihng
  85106. };
  85107. FramingBehavior.prototype.attach = function (camera) {
  85108. var _this = this;
  85109. this._attachedCamera = camera;
  85110. var scene = this._attachedCamera.getScene();
  85111. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  85112. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85113. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85114. _this._isPointerDown = true;
  85115. return;
  85116. }
  85117. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85118. _this._isPointerDown = false;
  85119. }
  85120. });
  85121. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85122. if (mesh) {
  85123. _this.zoomOnMesh(mesh);
  85124. }
  85125. });
  85126. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85127. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85128. _this._applyUserInteraction();
  85129. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  85130. // back to the default position after a given timeout
  85131. _this._maintainCameraAboveGround();
  85132. });
  85133. };
  85134. FramingBehavior.prototype.detach = function () {
  85135. if (!this._attachedCamera) {
  85136. return;
  85137. }
  85138. var scene = this._attachedCamera.getScene();
  85139. if (this._onPrePointerObservableObserver) {
  85140. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85141. }
  85142. if (this._onAfterCheckInputsObserver) {
  85143. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85144. }
  85145. if (this._onMeshTargetChangedObserver) {
  85146. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85147. }
  85148. this._attachedCamera = null;
  85149. };
  85150. /**
  85151. * Targets the given mesh and updates zoom level accordingly.
  85152. * @param mesh The mesh to target.
  85153. * @param radius Optional. If a cached radius position already exists, overrides default.
  85154. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85155. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85156. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85157. */
  85158. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85159. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85160. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85161. mesh.computeWorldMatrix(true);
  85162. var boundingBox = mesh.getBoundingInfo().boundingBox;
  85163. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  85164. };
  85165. /**
  85166. * Targets the given mesh with its children and updates zoom level accordingly.
  85167. * @param mesh The mesh to target.
  85168. * @param radius Optional. If a cached radius position already exists, overrides default.
  85169. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85170. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85171. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85172. */
  85173. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85174. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85175. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85176. mesh.computeWorldMatrix(true);
  85177. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  85178. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  85179. };
  85180. /**
  85181. * Targets the given meshes with their children and updates zoom level accordingly.
  85182. * @param meshes The mesh to target.
  85183. * @param radius Optional. If a cached radius position already exists, overrides default.
  85184. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85185. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85186. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85187. */
  85188. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  85189. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85190. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85191. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  85192. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  85193. for (var i = 0; i < meshes.length; i++) {
  85194. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  85195. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  85196. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  85197. }
  85198. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  85199. };
  85200. /**
  85201. * Targets the given mesh and updates zoom level accordingly.
  85202. * @param mesh The mesh to target.
  85203. * @param radius Optional. If a cached radius position already exists, overrides default.
  85204. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85205. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85206. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85207. */
  85208. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  85209. var _this = this;
  85210. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85211. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85212. var zoomTarget;
  85213. if (!this._attachedCamera) {
  85214. return;
  85215. }
  85216. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  85217. var bottom = minimumWorld.y;
  85218. var top = maximumWorld.y;
  85219. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  85220. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  85221. if (focusOnOriginXZ) {
  85222. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  85223. }
  85224. else {
  85225. var centerWorld = minimumWorld.add(radiusWorld);
  85226. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  85227. }
  85228. if (!this._vectorTransition) {
  85229. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  85230. }
  85231. this._betaIsAnimating = true;
  85232. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  85233. if (animatable) {
  85234. this._animatables.push(animatable);
  85235. }
  85236. // sets the radius and lower radius bounds
  85237. // Small delta ensures camera is not always at lower zoom limit.
  85238. var radius = 0;
  85239. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  85240. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85241. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  85242. radius = position;
  85243. }
  85244. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85245. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85246. if (this._attachedCamera.lowerRadiusLimit === null) {
  85247. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  85248. }
  85249. }
  85250. // Set sensibilities
  85251. var extend = maximumWorld.subtract(minimumWorld).length();
  85252. this._attachedCamera.panningSensibility = 5000 / extend;
  85253. this._attachedCamera.wheelPrecision = 100 / radius;
  85254. // transition to new radius
  85255. if (!this._radiusTransition) {
  85256. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85257. }
  85258. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  85259. if (onAnimationEnd) {
  85260. onAnimationEnd();
  85261. }
  85262. if (_this._attachedCamera) {
  85263. _this._attachedCamera.storeState();
  85264. }
  85265. });
  85266. if (animatable) {
  85267. this._animatables.push(animatable);
  85268. }
  85269. };
  85270. /**
  85271. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  85272. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  85273. * frustum width.
  85274. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  85275. * to fully enclose the mesh in the viewing frustum.
  85276. */
  85277. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  85278. var size = maximumWorld.subtract(minimumWorld);
  85279. var boxVectorGlobalDiagonal = size.length();
  85280. var frustumSlope = this._getFrustumSlope();
  85281. // Formula for setting distance
  85282. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  85283. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  85284. // Horizon distance
  85285. var radius = radiusWithoutFraming * this._radiusScale;
  85286. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  85287. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  85288. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  85289. var camera = this._attachedCamera;
  85290. if (!camera) {
  85291. return 0;
  85292. }
  85293. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85294. // Don't exceed the requested limit
  85295. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  85296. }
  85297. // Don't exceed the upper radius limit
  85298. if (camera.upperRadiusLimit) {
  85299. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  85300. }
  85301. return distance;
  85302. };
  85303. /**
  85304. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  85305. * is automatically returned to its default position (expected to be above ground plane).
  85306. */
  85307. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  85308. var _this = this;
  85309. if (this._elevationReturnTime < 0) {
  85310. return;
  85311. }
  85312. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  85313. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  85314. var limitBeta = Math.PI * 0.5;
  85315. // Bring the camera back up if below the ground plane
  85316. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  85317. this._betaIsAnimating = true;
  85318. //Transition to new position
  85319. this.stopAllAnimations();
  85320. if (!this._betaTransition) {
  85321. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85322. }
  85323. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  85324. _this._clearAnimationLocks();
  85325. _this.stopAllAnimations();
  85326. });
  85327. if (animatabe) {
  85328. this._animatables.push(animatabe);
  85329. }
  85330. }
  85331. };
  85332. /**
  85333. * Returns the frustum slope based on the canvas ratio and camera FOV
  85334. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  85335. */
  85336. FramingBehavior.prototype._getFrustumSlope = function () {
  85337. // Calculate the viewport ratio
  85338. // Aspect Ratio is Height/Width.
  85339. var camera = this._attachedCamera;
  85340. if (!camera) {
  85341. return BABYLON.Vector2.Zero();
  85342. }
  85343. var engine = camera.getScene().getEngine();
  85344. var aspectRatio = engine.getAspectRatio(camera);
  85345. // Camera FOV is the vertical field of view (top-bottom) in radians.
  85346. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  85347. var frustumSlopeY = Math.tan(camera.fov / 2);
  85348. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  85349. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  85350. // along the forward vector.
  85351. var frustumSlopeX = frustumSlopeY * aspectRatio;
  85352. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  85353. };
  85354. /**
  85355. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  85356. */
  85357. FramingBehavior.prototype._clearAnimationLocks = function () {
  85358. this._betaIsAnimating = false;
  85359. };
  85360. /**
  85361. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85362. */
  85363. FramingBehavior.prototype._applyUserInteraction = function () {
  85364. if (this.isUserIsMoving) {
  85365. this._lastInteractionTime = BABYLON.Tools.Now;
  85366. this.stopAllAnimations();
  85367. this._clearAnimationLocks();
  85368. }
  85369. };
  85370. /**
  85371. * Stops and removes all animations that have been applied to the camera
  85372. */
  85373. FramingBehavior.prototype.stopAllAnimations = function () {
  85374. if (this._attachedCamera) {
  85375. this._attachedCamera.animations = [];
  85376. }
  85377. while (this._animatables.length) {
  85378. if (this._animatables[0]) {
  85379. this._animatables[0].onAnimationEnd = null;
  85380. this._animatables[0].stop();
  85381. }
  85382. this._animatables.shift();
  85383. }
  85384. };
  85385. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  85386. /**
  85387. * Gets a value indicating if the user is moving the camera
  85388. */
  85389. get: function () {
  85390. if (!this._attachedCamera) {
  85391. return false;
  85392. }
  85393. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85394. this._attachedCamera.inertialBetaOffset !== 0 ||
  85395. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85396. this._attachedCamera.inertialPanningX !== 0 ||
  85397. this._attachedCamera.inertialPanningY !== 0 ||
  85398. this._isPointerDown;
  85399. },
  85400. enumerable: true,
  85401. configurable: true
  85402. });
  85403. /**
  85404. * The easing function used by animations
  85405. */
  85406. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  85407. /**
  85408. * The easing mode used by animations
  85409. */
  85410. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  85411. // Statics
  85412. /**
  85413. * The camera can move all the way towards the mesh.
  85414. */
  85415. FramingBehavior.IgnoreBoundsSizeMode = 0;
  85416. /**
  85417. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  85418. */
  85419. FramingBehavior.FitFrustumSidesMode = 1;
  85420. return FramingBehavior;
  85421. }());
  85422. BABYLON.FramingBehavior = FramingBehavior;
  85423. })(BABYLON || (BABYLON = {}));
  85424. //# sourceMappingURL=babylon.framingBehavior.js.map
  85425. var BABYLON;
  85426. (function (BABYLON) {
  85427. /**
  85428. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  85429. */
  85430. var BouncingBehavior = /** @class */ (function () {
  85431. function BouncingBehavior() {
  85432. /**
  85433. * The duration of the animation, in milliseconds
  85434. */
  85435. this.transitionDuration = 450;
  85436. /**
  85437. * Length of the distance animated by the transition when lower radius is reached
  85438. */
  85439. this.lowerRadiusTransitionRange = 2;
  85440. /**
  85441. * Length of the distance animated by the transition when upper radius is reached
  85442. */
  85443. this.upperRadiusTransitionRange = -2;
  85444. this._autoTransitionRange = false;
  85445. // Animations
  85446. this._radiusIsAnimating = false;
  85447. this._radiusBounceTransition = null;
  85448. this._animatables = new Array();
  85449. }
  85450. Object.defineProperty(BouncingBehavior.prototype, "name", {
  85451. get: function () {
  85452. return "Bouncing";
  85453. },
  85454. enumerable: true,
  85455. configurable: true
  85456. });
  85457. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  85458. /**
  85459. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85460. */
  85461. get: function () {
  85462. return this._autoTransitionRange;
  85463. },
  85464. /**
  85465. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85466. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  85467. */
  85468. set: function (value) {
  85469. var _this = this;
  85470. if (this._autoTransitionRange === value) {
  85471. return;
  85472. }
  85473. this._autoTransitionRange = value;
  85474. var camera = this._attachedCamera;
  85475. if (!camera) {
  85476. return;
  85477. }
  85478. if (value) {
  85479. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85480. if (!mesh) {
  85481. return;
  85482. }
  85483. mesh.computeWorldMatrix(true);
  85484. var diagonal = mesh.getBoundingInfo().diagonalLength;
  85485. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  85486. _this.upperRadiusTransitionRange = diagonal * 0.05;
  85487. });
  85488. }
  85489. else if (this._onMeshTargetChangedObserver) {
  85490. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85491. }
  85492. },
  85493. enumerable: true,
  85494. configurable: true
  85495. });
  85496. BouncingBehavior.prototype.init = function () {
  85497. // Do notihng
  85498. };
  85499. BouncingBehavior.prototype.attach = function (camera) {
  85500. var _this = this;
  85501. this._attachedCamera = camera;
  85502. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85503. if (!_this._attachedCamera) {
  85504. return;
  85505. }
  85506. // Add the bounce animation to the lower radius limit
  85507. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  85508. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  85509. }
  85510. // Add the bounce animation to the upper radius limit
  85511. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  85512. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  85513. }
  85514. });
  85515. };
  85516. BouncingBehavior.prototype.detach = function () {
  85517. if (!this._attachedCamera) {
  85518. return;
  85519. }
  85520. if (this._onAfterCheckInputsObserver) {
  85521. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85522. }
  85523. if (this._onMeshTargetChangedObserver) {
  85524. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85525. }
  85526. this._attachedCamera = null;
  85527. };
  85528. /**
  85529. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  85530. * @param radiusLimit The limit to check against.
  85531. * @return Bool to indicate if at limit.
  85532. */
  85533. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  85534. if (!this._attachedCamera) {
  85535. return false;
  85536. }
  85537. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  85538. return true;
  85539. }
  85540. return false;
  85541. };
  85542. /**
  85543. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  85544. * @param radiusDelta The delta by which to animate to. Can be negative.
  85545. */
  85546. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  85547. var _this = this;
  85548. if (!this._attachedCamera) {
  85549. return;
  85550. }
  85551. if (!this._radiusBounceTransition) {
  85552. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  85553. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  85554. }
  85555. // Prevent zoom until bounce has completed
  85556. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  85557. this._attachedCamera.wheelPrecision = Infinity;
  85558. this._attachedCamera.inertialRadiusOffset = 0;
  85559. // Animate to the radius limit
  85560. this.stopAllAnimations();
  85561. this._radiusIsAnimating = true;
  85562. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  85563. if (animatable) {
  85564. this._animatables.push(animatable);
  85565. }
  85566. };
  85567. /**
  85568. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  85569. */
  85570. BouncingBehavior.prototype._clearAnimationLocks = function () {
  85571. this._radiusIsAnimating = false;
  85572. if (this._attachedCamera) {
  85573. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  85574. }
  85575. };
  85576. /**
  85577. * Stops and removes all animations that have been applied to the camera
  85578. */
  85579. BouncingBehavior.prototype.stopAllAnimations = function () {
  85580. if (this._attachedCamera) {
  85581. this._attachedCamera.animations = [];
  85582. }
  85583. while (this._animatables.length) {
  85584. this._animatables[0].onAnimationEnd = null;
  85585. this._animatables[0].stop();
  85586. this._animatables.shift();
  85587. }
  85588. };
  85589. /**
  85590. * The easing function used by animations
  85591. */
  85592. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  85593. /**
  85594. * The easing mode used by animations
  85595. */
  85596. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  85597. return BouncingBehavior;
  85598. }());
  85599. BABYLON.BouncingBehavior = BouncingBehavior;
  85600. })(BABYLON || (BABYLON = {}));
  85601. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  85602. var BABYLON;
  85603. (function (BABYLON) {
  85604. var AutoRotationBehavior = /** @class */ (function () {
  85605. function AutoRotationBehavior() {
  85606. this._zoomStopsAnimation = false;
  85607. this._idleRotationSpeed = 0.05;
  85608. this._idleRotationWaitTime = 2000;
  85609. this._idleRotationSpinupTime = 2000;
  85610. this._isPointerDown = false;
  85611. this._lastFrameTime = null;
  85612. this._lastInteractionTime = -Infinity;
  85613. this._cameraRotationSpeed = 0;
  85614. this._lastFrameRadius = 0;
  85615. }
  85616. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  85617. get: function () {
  85618. return "AutoRotation";
  85619. },
  85620. enumerable: true,
  85621. configurable: true
  85622. });
  85623. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  85624. /**
  85625. * Gets the flag that indicates if user zooming should stop animation.
  85626. */
  85627. get: function () {
  85628. return this._zoomStopsAnimation;
  85629. },
  85630. /**
  85631. * Sets the flag that indicates if user zooming should stop animation.
  85632. */
  85633. set: function (flag) {
  85634. this._zoomStopsAnimation = flag;
  85635. },
  85636. enumerable: true,
  85637. configurable: true
  85638. });
  85639. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  85640. /**
  85641. * Gets the default speed at which the camera rotates around the model.
  85642. */
  85643. get: function () {
  85644. return this._idleRotationSpeed;
  85645. },
  85646. /**
  85647. * Sets the default speed at which the camera rotates around the model.
  85648. */
  85649. set: function (speed) {
  85650. this._idleRotationSpeed = speed;
  85651. },
  85652. enumerable: true,
  85653. configurable: true
  85654. });
  85655. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  85656. /**
  85657. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  85658. */
  85659. get: function () {
  85660. return this._idleRotationWaitTime;
  85661. },
  85662. /**
  85663. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  85664. */
  85665. set: function (time) {
  85666. this._idleRotationWaitTime = time;
  85667. },
  85668. enumerable: true,
  85669. configurable: true
  85670. });
  85671. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  85672. /**
  85673. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85674. */
  85675. get: function () {
  85676. return this._idleRotationSpinupTime;
  85677. },
  85678. /**
  85679. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85680. */
  85681. set: function (time) {
  85682. this._idleRotationSpinupTime = time;
  85683. },
  85684. enumerable: true,
  85685. configurable: true
  85686. });
  85687. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  85688. /**
  85689. * Gets a value indicating if the camera is currently rotating because of this behavior
  85690. */
  85691. get: function () {
  85692. return Math.abs(this._cameraRotationSpeed) > 0;
  85693. },
  85694. enumerable: true,
  85695. configurable: true
  85696. });
  85697. AutoRotationBehavior.prototype.init = function () {
  85698. // Do notihng
  85699. };
  85700. AutoRotationBehavior.prototype.attach = function (camera) {
  85701. var _this = this;
  85702. this._attachedCamera = camera;
  85703. var scene = this._attachedCamera.getScene();
  85704. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85705. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85706. _this._isPointerDown = true;
  85707. return;
  85708. }
  85709. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85710. _this._isPointerDown = false;
  85711. }
  85712. });
  85713. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85714. var now = BABYLON.Tools.Now;
  85715. var dt = 0;
  85716. if (_this._lastFrameTime != null) {
  85717. dt = now - _this._lastFrameTime;
  85718. }
  85719. _this._lastFrameTime = now;
  85720. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85721. _this._applyUserInteraction();
  85722. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  85723. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  85724. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  85725. // Step camera rotation by rotation speed
  85726. if (_this._attachedCamera) {
  85727. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  85728. }
  85729. });
  85730. };
  85731. AutoRotationBehavior.prototype.detach = function () {
  85732. if (!this._attachedCamera) {
  85733. return;
  85734. }
  85735. var scene = this._attachedCamera.getScene();
  85736. if (this._onPrePointerObservableObserver) {
  85737. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85738. }
  85739. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85740. this._attachedCamera = null;
  85741. };
  85742. /**
  85743. * Returns true if user is scrolling.
  85744. * @return true if user is scrolling.
  85745. */
  85746. AutoRotationBehavior.prototype._userIsZooming = function () {
  85747. if (!this._attachedCamera) {
  85748. return false;
  85749. }
  85750. return this._attachedCamera.inertialRadiusOffset !== 0;
  85751. };
  85752. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  85753. if (!this._attachedCamera) {
  85754. return false;
  85755. }
  85756. var zoomHasHitLimit = false;
  85757. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  85758. zoomHasHitLimit = true;
  85759. }
  85760. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  85761. this._lastFrameRadius = this._attachedCamera.radius;
  85762. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  85763. };
  85764. /**
  85765. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85766. */
  85767. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  85768. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  85769. this._lastInteractionTime = BABYLON.Tools.Now;
  85770. }
  85771. };
  85772. // Tools
  85773. AutoRotationBehavior.prototype._userIsMoving = function () {
  85774. if (!this._attachedCamera) {
  85775. return false;
  85776. }
  85777. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85778. this._attachedCamera.inertialBetaOffset !== 0 ||
  85779. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85780. this._attachedCamera.inertialPanningX !== 0 ||
  85781. this._attachedCamera.inertialPanningY !== 0 ||
  85782. this._isPointerDown;
  85783. };
  85784. return AutoRotationBehavior;
  85785. }());
  85786. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  85787. })(BABYLON || (BABYLON = {}));
  85788. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  85789. var BABYLON;
  85790. (function (BABYLON) {
  85791. /**
  85792. * This class can be used to get instrumentation data from a Babylon engine
  85793. */
  85794. var EngineInstrumentation = /** @class */ (function () {
  85795. function EngineInstrumentation(engine) {
  85796. this.engine = engine;
  85797. this._captureGPUFrameTime = false;
  85798. this._gpuFrameTime = new BABYLON.PerfCounter();
  85799. this._captureShaderCompilationTime = false;
  85800. this._shaderCompilationTime = new BABYLON.PerfCounter();
  85801. // Observers
  85802. this._onBeginFrameObserver = null;
  85803. this._onEndFrameObserver = null;
  85804. this._onBeforeShaderCompilationObserver = null;
  85805. this._onAfterShaderCompilationObserver = null;
  85806. }
  85807. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  85808. // Properties
  85809. /**
  85810. * Gets the perf counter used for GPU frame time
  85811. */
  85812. get: function () {
  85813. return this._gpuFrameTime;
  85814. },
  85815. enumerable: true,
  85816. configurable: true
  85817. });
  85818. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  85819. /**
  85820. * Gets the GPU frame time capture status
  85821. */
  85822. get: function () {
  85823. return this._captureGPUFrameTime;
  85824. },
  85825. /**
  85826. * Enable or disable the GPU frame time capture
  85827. */
  85828. set: function (value) {
  85829. var _this = this;
  85830. if (value === this._captureGPUFrameTime) {
  85831. return;
  85832. }
  85833. this._captureGPUFrameTime = value;
  85834. if (value) {
  85835. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  85836. if (!_this._gpuFrameTimeToken) {
  85837. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  85838. }
  85839. });
  85840. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  85841. if (!_this._gpuFrameTimeToken) {
  85842. return;
  85843. }
  85844. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  85845. if (time > -1) {
  85846. _this._gpuFrameTimeToken = null;
  85847. _this._gpuFrameTime.fetchNewFrame();
  85848. _this._gpuFrameTime.addCount(time, true);
  85849. }
  85850. });
  85851. }
  85852. else {
  85853. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  85854. this._onBeginFrameObserver = null;
  85855. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  85856. this._onEndFrameObserver = null;
  85857. }
  85858. },
  85859. enumerable: true,
  85860. configurable: true
  85861. });
  85862. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  85863. /**
  85864. * Gets the perf counter used for shader compilation time
  85865. */
  85866. get: function () {
  85867. return this._shaderCompilationTime;
  85868. },
  85869. enumerable: true,
  85870. configurable: true
  85871. });
  85872. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  85873. /**
  85874. * Gets the shader compilation time capture status
  85875. */
  85876. get: function () {
  85877. return this._captureShaderCompilationTime;
  85878. },
  85879. /**
  85880. * Enable or disable the shader compilation time capture
  85881. */
  85882. set: function (value) {
  85883. var _this = this;
  85884. if (value === this._captureShaderCompilationTime) {
  85885. return;
  85886. }
  85887. this._captureShaderCompilationTime = value;
  85888. if (value) {
  85889. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  85890. _this._shaderCompilationTime.fetchNewFrame();
  85891. _this._shaderCompilationTime.beginMonitoring();
  85892. });
  85893. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  85894. _this._shaderCompilationTime.endMonitoring();
  85895. });
  85896. }
  85897. else {
  85898. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  85899. this._onBeforeShaderCompilationObserver = null;
  85900. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  85901. this._onAfterShaderCompilationObserver = null;
  85902. }
  85903. },
  85904. enumerable: true,
  85905. configurable: true
  85906. });
  85907. EngineInstrumentation.prototype.dispose = function () {
  85908. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  85909. this._onBeginFrameObserver = null;
  85910. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  85911. this._onEndFrameObserver = null;
  85912. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  85913. this._onBeforeShaderCompilationObserver = null;
  85914. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  85915. this._onAfterShaderCompilationObserver = null;
  85916. this.engine = null;
  85917. };
  85918. return EngineInstrumentation;
  85919. }());
  85920. BABYLON.EngineInstrumentation = EngineInstrumentation;
  85921. })(BABYLON || (BABYLON = {}));
  85922. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  85923. var BABYLON;
  85924. (function (BABYLON) {
  85925. /**
  85926. * This class can be used to get instrumentation data from a Babylon engine
  85927. */
  85928. var SceneInstrumentation = /** @class */ (function () {
  85929. function SceneInstrumentation(scene) {
  85930. var _this = this;
  85931. this.scene = scene;
  85932. this._captureActiveMeshesEvaluationTime = false;
  85933. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  85934. this._captureRenderTargetsRenderTime = false;
  85935. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  85936. this._captureFrameTime = false;
  85937. this._frameTime = new BABYLON.PerfCounter();
  85938. this._captureRenderTime = false;
  85939. this._renderTime = new BABYLON.PerfCounter();
  85940. this._captureInterFrameTime = false;
  85941. this._interFrameTime = new BABYLON.PerfCounter();
  85942. this._captureParticlesRenderTime = false;
  85943. this._particlesRenderTime = new BABYLON.PerfCounter();
  85944. this._captureSpritesRenderTime = false;
  85945. this._spritesRenderTime = new BABYLON.PerfCounter();
  85946. this._capturePhysicsTime = false;
  85947. this._physicsTime = new BABYLON.PerfCounter();
  85948. this._captureAnimationsTime = false;
  85949. this._animationsTime = new BABYLON.PerfCounter();
  85950. // Observers
  85951. this._onBeforeActiveMeshesEvaluationObserver = null;
  85952. this._onAfterActiveMeshesEvaluationObserver = null;
  85953. this._onBeforeRenderTargetsRenderObserver = null;
  85954. this._onAfterRenderTargetsRenderObserver = null;
  85955. this._onAfterRenderObserver = null;
  85956. this._onBeforeDrawPhaseObserver = null;
  85957. this._onAfterDrawPhaseObserver = null;
  85958. this._onBeforeAnimationsObserver = null;
  85959. this._onBeforeParticlesRenderingObserver = null;
  85960. this._onAfterParticlesRenderingObserver = null;
  85961. this._onBeforeSpritesRenderingObserver = null;
  85962. this._onAfterSpritesRenderingObserver = null;
  85963. this._onBeforePhysicsObserver = null;
  85964. this._onAfterPhysicsObserver = null;
  85965. this._onAfterAnimationsObserver = null;
  85966. // Before render
  85967. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  85968. if (_this._captureActiveMeshesEvaluationTime) {
  85969. _this._activeMeshesEvaluationTime.fetchNewFrame();
  85970. }
  85971. if (_this._captureRenderTargetsRenderTime) {
  85972. _this._renderTargetsRenderTime.fetchNewFrame();
  85973. }
  85974. if (_this._captureFrameTime) {
  85975. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  85976. _this._frameTime.beginMonitoring();
  85977. }
  85978. if (_this._captureInterFrameTime) {
  85979. _this._interFrameTime.endMonitoring();
  85980. }
  85981. if (_this._captureParticlesRenderTime) {
  85982. _this._particlesRenderTime.fetchNewFrame();
  85983. }
  85984. if (_this._captureSpritesRenderTime) {
  85985. _this._spritesRenderTime.fetchNewFrame();
  85986. }
  85987. if (_this._captureAnimationsTime) {
  85988. _this._animationsTime.beginMonitoring();
  85989. }
  85990. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  85991. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  85992. });
  85993. // After render
  85994. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  85995. if (_this._captureFrameTime) {
  85996. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  85997. _this._frameTime.endMonitoring();
  85998. }
  85999. if (_this._captureRenderTime) {
  86000. _this._renderTime.endMonitoring(false);
  86001. }
  86002. if (_this._captureInterFrameTime) {
  86003. _this._interFrameTime.beginMonitoring();
  86004. }
  86005. });
  86006. }
  86007. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  86008. // Properties
  86009. /**
  86010. * Gets the perf counter used for active meshes evaluation time
  86011. */
  86012. get: function () {
  86013. return this._activeMeshesEvaluationTime;
  86014. },
  86015. enumerable: true,
  86016. configurable: true
  86017. });
  86018. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  86019. /**
  86020. * Gets the active meshes evaluation time capture status
  86021. */
  86022. get: function () {
  86023. return this._captureActiveMeshesEvaluationTime;
  86024. },
  86025. /**
  86026. * Enable or disable the active meshes evaluation time capture
  86027. */
  86028. set: function (value) {
  86029. var _this = this;
  86030. if (value === this._captureActiveMeshesEvaluationTime) {
  86031. return;
  86032. }
  86033. this._captureActiveMeshesEvaluationTime = value;
  86034. if (value) {
  86035. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  86036. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  86037. _this._activeMeshesEvaluationTime.beginMonitoring();
  86038. });
  86039. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  86040. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  86041. _this._activeMeshesEvaluationTime.endMonitoring();
  86042. });
  86043. }
  86044. else {
  86045. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  86046. this._onBeforeActiveMeshesEvaluationObserver = null;
  86047. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  86048. this._onAfterActiveMeshesEvaluationObserver = null;
  86049. }
  86050. },
  86051. enumerable: true,
  86052. configurable: true
  86053. });
  86054. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  86055. /**
  86056. * Gets the perf counter used for render targets render time
  86057. */
  86058. get: function () {
  86059. return this._renderTargetsRenderTime;
  86060. },
  86061. enumerable: true,
  86062. configurable: true
  86063. });
  86064. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  86065. /**
  86066. * Gets the render targets render time capture status
  86067. */
  86068. get: function () {
  86069. return this._captureRenderTargetsRenderTime;
  86070. },
  86071. /**
  86072. * Enable or disable the render targets render time capture
  86073. */
  86074. set: function (value) {
  86075. var _this = this;
  86076. if (value === this._captureRenderTargetsRenderTime) {
  86077. return;
  86078. }
  86079. this._captureRenderTargetsRenderTime = value;
  86080. if (value) {
  86081. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  86082. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  86083. _this._renderTargetsRenderTime.beginMonitoring();
  86084. });
  86085. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  86086. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  86087. _this._renderTargetsRenderTime.endMonitoring(false);
  86088. });
  86089. }
  86090. else {
  86091. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86092. this._onBeforeRenderTargetsRenderObserver = null;
  86093. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86094. this._onAfterRenderTargetsRenderObserver = null;
  86095. }
  86096. },
  86097. enumerable: true,
  86098. configurable: true
  86099. });
  86100. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  86101. /**
  86102. * Gets the perf counter used for particles render time
  86103. */
  86104. get: function () {
  86105. return this._particlesRenderTime;
  86106. },
  86107. enumerable: true,
  86108. configurable: true
  86109. });
  86110. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  86111. /**
  86112. * Gets the particles render time capture status
  86113. */
  86114. get: function () {
  86115. return this._captureParticlesRenderTime;
  86116. },
  86117. /**
  86118. * Enable or disable the particles render time capture
  86119. */
  86120. set: function (value) {
  86121. var _this = this;
  86122. if (value === this._captureParticlesRenderTime) {
  86123. return;
  86124. }
  86125. this._captureParticlesRenderTime = value;
  86126. if (value) {
  86127. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  86128. BABYLON.Tools.StartPerformanceCounter("Particles");
  86129. _this._particlesRenderTime.beginMonitoring();
  86130. });
  86131. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  86132. BABYLON.Tools.EndPerformanceCounter("Particles");
  86133. _this._particlesRenderTime.endMonitoring(false);
  86134. });
  86135. }
  86136. else {
  86137. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86138. this._onBeforeParticlesRenderingObserver = null;
  86139. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86140. this._onAfterParticlesRenderingObserver = null;
  86141. }
  86142. },
  86143. enumerable: true,
  86144. configurable: true
  86145. });
  86146. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  86147. /**
  86148. * Gets the perf counter used for sprites render time
  86149. */
  86150. get: function () {
  86151. return this._spritesRenderTime;
  86152. },
  86153. enumerable: true,
  86154. configurable: true
  86155. });
  86156. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  86157. /**
  86158. * Gets the sprites render time capture status
  86159. */
  86160. get: function () {
  86161. return this._captureSpritesRenderTime;
  86162. },
  86163. /**
  86164. * Enable or disable the sprites render time capture
  86165. */
  86166. set: function (value) {
  86167. var _this = this;
  86168. if (value === this._captureSpritesRenderTime) {
  86169. return;
  86170. }
  86171. this._captureSpritesRenderTime = value;
  86172. if (value) {
  86173. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  86174. BABYLON.Tools.StartPerformanceCounter("Sprites");
  86175. _this._spritesRenderTime.beginMonitoring();
  86176. });
  86177. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  86178. BABYLON.Tools.EndPerformanceCounter("Sprites");
  86179. _this._spritesRenderTime.endMonitoring(false);
  86180. });
  86181. }
  86182. else {
  86183. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86184. this._onBeforeSpritesRenderingObserver = null;
  86185. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86186. this._onAfterSpritesRenderingObserver = null;
  86187. }
  86188. },
  86189. enumerable: true,
  86190. configurable: true
  86191. });
  86192. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  86193. /**
  86194. * Gets the perf counter used for physics time
  86195. */
  86196. get: function () {
  86197. return this._physicsTime;
  86198. },
  86199. enumerable: true,
  86200. configurable: true
  86201. });
  86202. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  86203. /**
  86204. * Gets the physics time capture status
  86205. */
  86206. get: function () {
  86207. return this._capturePhysicsTime;
  86208. },
  86209. /**
  86210. * Enable or disable the physics time capture
  86211. */
  86212. set: function (value) {
  86213. var _this = this;
  86214. if (value === this._capturePhysicsTime) {
  86215. return;
  86216. }
  86217. this._capturePhysicsTime = value;
  86218. if (value) {
  86219. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  86220. BABYLON.Tools.StartPerformanceCounter("Physics");
  86221. _this._physicsTime.beginMonitoring();
  86222. });
  86223. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  86224. BABYLON.Tools.EndPerformanceCounter("Physics");
  86225. _this._physicsTime.endMonitoring();
  86226. });
  86227. }
  86228. else {
  86229. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86230. this._onBeforePhysicsObserver = null;
  86231. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86232. this._onAfterPhysicsObserver = null;
  86233. }
  86234. },
  86235. enumerable: true,
  86236. configurable: true
  86237. });
  86238. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  86239. /**
  86240. * Gets the perf counter used for animations time
  86241. */
  86242. get: function () {
  86243. return this._animationsTime;
  86244. },
  86245. enumerable: true,
  86246. configurable: true
  86247. });
  86248. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  86249. /**
  86250. * Gets the animations time capture status
  86251. */
  86252. get: function () {
  86253. return this._captureAnimationsTime;
  86254. },
  86255. /**
  86256. * Enable or disable the animations time capture
  86257. */
  86258. set: function (value) {
  86259. var _this = this;
  86260. if (value === this._captureAnimationsTime) {
  86261. return;
  86262. }
  86263. this._captureAnimationsTime = value;
  86264. if (value) {
  86265. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  86266. _this._animationsTime.endMonitoring();
  86267. });
  86268. }
  86269. else {
  86270. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86271. this._onAfterAnimationsObserver = null;
  86272. }
  86273. },
  86274. enumerable: true,
  86275. configurable: true
  86276. });
  86277. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  86278. /**
  86279. * Gets the perf counter used for frame time capture
  86280. */
  86281. get: function () {
  86282. return this._frameTime;
  86283. },
  86284. enumerable: true,
  86285. configurable: true
  86286. });
  86287. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  86288. /**
  86289. * Gets the frame time capture status
  86290. */
  86291. get: function () {
  86292. return this._captureFrameTime;
  86293. },
  86294. /**
  86295. * Enable or disable the frame time capture
  86296. */
  86297. set: function (value) {
  86298. this._captureFrameTime = value;
  86299. },
  86300. enumerable: true,
  86301. configurable: true
  86302. });
  86303. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  86304. /**
  86305. * Gets the perf counter used for inter-frames time capture
  86306. */
  86307. get: function () {
  86308. return this._interFrameTime;
  86309. },
  86310. enumerable: true,
  86311. configurable: true
  86312. });
  86313. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  86314. /**
  86315. * Gets the inter-frames time capture status
  86316. */
  86317. get: function () {
  86318. return this._captureInterFrameTime;
  86319. },
  86320. /**
  86321. * Enable or disable the inter-frames time capture
  86322. */
  86323. set: function (value) {
  86324. this._captureInterFrameTime = value;
  86325. },
  86326. enumerable: true,
  86327. configurable: true
  86328. });
  86329. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  86330. /**
  86331. * Gets the perf counter used for render time capture
  86332. */
  86333. get: function () {
  86334. return this._renderTime;
  86335. },
  86336. enumerable: true,
  86337. configurable: true
  86338. });
  86339. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  86340. /**
  86341. * Gets the render time capture status
  86342. */
  86343. get: function () {
  86344. return this._captureRenderTime;
  86345. },
  86346. /**
  86347. * Enable or disable the render time capture
  86348. */
  86349. set: function (value) {
  86350. var _this = this;
  86351. if (value === this._captureRenderTime) {
  86352. return;
  86353. }
  86354. this._captureRenderTime = value;
  86355. if (value) {
  86356. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  86357. _this._renderTime.beginMonitoring();
  86358. BABYLON.Tools.StartPerformanceCounter("Main render");
  86359. });
  86360. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  86361. _this._renderTime.endMonitoring(false);
  86362. BABYLON.Tools.EndPerformanceCounter("Main render");
  86363. });
  86364. }
  86365. else {
  86366. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86367. this._onBeforeDrawPhaseObserver = null;
  86368. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86369. this._onAfterDrawPhaseObserver = null;
  86370. }
  86371. },
  86372. enumerable: true,
  86373. configurable: true
  86374. });
  86375. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  86376. /**
  86377. * Gets the perf counter used for draw calls
  86378. */
  86379. get: function () {
  86380. return this.scene.getEngine()._drawCalls;
  86381. },
  86382. enumerable: true,
  86383. configurable: true
  86384. });
  86385. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  86386. /**
  86387. * Gets the perf counter used for texture collisions
  86388. */
  86389. get: function () {
  86390. return this.scene.getEngine()._textureCollisions;
  86391. },
  86392. enumerable: true,
  86393. configurable: true
  86394. });
  86395. SceneInstrumentation.prototype.dispose = function () {
  86396. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86397. this._onAfterRenderObserver = null;
  86398. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  86399. this._onBeforeActiveMeshesEvaluationObserver = null;
  86400. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  86401. this._onAfterActiveMeshesEvaluationObserver = null;
  86402. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86403. this._onBeforeRenderTargetsRenderObserver = null;
  86404. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86405. this._onAfterRenderTargetsRenderObserver = null;
  86406. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  86407. this._onBeforeAnimationsObserver = null;
  86408. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86409. this._onBeforeParticlesRenderingObserver = null;
  86410. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86411. this._onAfterParticlesRenderingObserver = null;
  86412. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86413. this._onBeforeSpritesRenderingObserver = null;
  86414. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86415. this._onAfterSpritesRenderingObserver = null;
  86416. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86417. this._onBeforeDrawPhaseObserver = null;
  86418. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86419. this._onAfterDrawPhaseObserver = null;
  86420. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86421. this._onBeforePhysicsObserver = null;
  86422. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86423. this._onAfterPhysicsObserver = null;
  86424. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86425. this._onAfterAnimationsObserver = null;
  86426. this.scene = null;
  86427. };
  86428. return SceneInstrumentation;
  86429. }());
  86430. BABYLON.SceneInstrumentation = SceneInstrumentation;
  86431. })(BABYLON || (BABYLON = {}));
  86432. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  86433. var BABYLON;
  86434. (function (BABYLON) {
  86435. var _TimeToken = /** @class */ (function () {
  86436. function _TimeToken() {
  86437. this._timeElapsedQueryEnded = false;
  86438. }
  86439. return _TimeToken;
  86440. }());
  86441. BABYLON._TimeToken = _TimeToken;
  86442. })(BABYLON || (BABYLON = {}));
  86443. //# sourceMappingURL=babylon.timeToken.js.map
  86444. var BABYLON;
  86445. (function (BABYLON) {
  86446. /**
  86447. * Background material defines definition.
  86448. * @ignore Mainly internal Use
  86449. */
  86450. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  86451. __extends(BackgroundMaterialDefines, _super);
  86452. /**
  86453. * Constructor of the defines.
  86454. */
  86455. function BackgroundMaterialDefines() {
  86456. var _this = _super.call(this) || this;
  86457. /**
  86458. * True if the diffuse texture is in use.
  86459. */
  86460. _this.DIFFUSE = false;
  86461. /**
  86462. * The direct UV channel to use.
  86463. */
  86464. _this.DIFFUSEDIRECTUV = 0;
  86465. /**
  86466. * True if the diffuse texture is in gamma space.
  86467. */
  86468. _this.GAMMADIFFUSE = false;
  86469. /**
  86470. * True if the diffuse texture has opacity in the alpha channel.
  86471. */
  86472. _this.DIFFUSEHASALPHA = false;
  86473. /**
  86474. * True if you want the material to fade to transparent at grazing angle.
  86475. */
  86476. _this.OPACITYFRESNEL = false;
  86477. /**
  86478. * True if an extra blur needs to be added in the reflection.
  86479. */
  86480. _this.REFLECTIONBLUR = false;
  86481. /**
  86482. * True if you want the material to fade to reflection at grazing angle.
  86483. */
  86484. _this.REFLECTIONFRESNEL = false;
  86485. /**
  86486. * True if you want the material to falloff as far as you move away from the scene center.
  86487. */
  86488. _this.REFLECTIONFALLOFF = false;
  86489. /**
  86490. * False if the current Webgl implementation does not support the texture lod extension.
  86491. */
  86492. _this.TEXTURELODSUPPORT = false;
  86493. /**
  86494. * True to ensure the data are premultiplied.
  86495. */
  86496. _this.PREMULTIPLYALPHA = false;
  86497. /**
  86498. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  86499. */
  86500. _this.USERGBCOLOR = false;
  86501. /**
  86502. * True to add noise in order to reduce the banding effect.
  86503. */
  86504. _this.NOISE = false;
  86505. // Image Processing Configuration.
  86506. _this.IMAGEPROCESSING = false;
  86507. _this.VIGNETTE = false;
  86508. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  86509. _this.VIGNETTEBLENDMODEOPAQUE = false;
  86510. _this.TONEMAPPING = false;
  86511. _this.CONTRAST = false;
  86512. _this.COLORCURVES = false;
  86513. _this.COLORGRADING = false;
  86514. _this.COLORGRADING3D = false;
  86515. _this.SAMPLER3DGREENDEPTH = false;
  86516. _this.SAMPLER3DBGRMAP = false;
  86517. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  86518. _this.EXPOSURE = false;
  86519. // Reflection.
  86520. _this.REFLECTION = false;
  86521. _this.REFLECTIONMAP_3D = false;
  86522. _this.REFLECTIONMAP_SPHERICAL = false;
  86523. _this.REFLECTIONMAP_PLANAR = false;
  86524. _this.REFLECTIONMAP_CUBIC = false;
  86525. _this.REFLECTIONMAP_PROJECTION = false;
  86526. _this.REFLECTIONMAP_SKYBOX = false;
  86527. _this.REFLECTIONMAP_EXPLICIT = false;
  86528. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  86529. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  86530. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  86531. _this.INVERTCUBICMAP = false;
  86532. _this.REFLECTIONMAP_OPPOSITEZ = false;
  86533. _this.LODINREFLECTIONALPHA = false;
  86534. _this.GAMMAREFLECTION = false;
  86535. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  86536. // Default BJS.
  86537. _this.MAINUV1 = false;
  86538. _this.MAINUV2 = false;
  86539. _this.UV1 = false;
  86540. _this.UV2 = false;
  86541. _this.CLIPPLANE = false;
  86542. _this.POINTSIZE = false;
  86543. _this.FOG = false;
  86544. _this.NORMAL = false;
  86545. _this.NUM_BONE_INFLUENCERS = 0;
  86546. _this.BonesPerMesh = 0;
  86547. _this.INSTANCES = false;
  86548. _this.SHADOWFLOAT = false;
  86549. _this.rebuild();
  86550. return _this;
  86551. }
  86552. return BackgroundMaterialDefines;
  86553. }(BABYLON.MaterialDefines));
  86554. /**
  86555. * Background material used to create an efficient environement around your scene.
  86556. */
  86557. var BackgroundMaterial = /** @class */ (function (_super) {
  86558. __extends(BackgroundMaterial, _super);
  86559. /**
  86560. * Instantiates a Background Material in the given scene
  86561. * @param name The friendly name of the material
  86562. * @param scene The scene to add the material to
  86563. */
  86564. function BackgroundMaterial(name, scene) {
  86565. var _this = _super.call(this, name, scene) || this;
  86566. /**
  86567. * Key light Color (multiply against the R channel of the environement texture)
  86568. */
  86569. _this.primaryColor = BABYLON.Color3.White();
  86570. /**
  86571. * Key light Level (allowing HDR output of the background)
  86572. */
  86573. _this.primaryLevel = 1;
  86574. /**
  86575. * Secondary light Color (multiply against the G channel of the environement texture)
  86576. */
  86577. _this.secondaryColor = BABYLON.Color3.Gray();
  86578. /**
  86579. * Secondary light Level (allowing HDR output of the background)
  86580. */
  86581. _this.secondaryLevel = 1;
  86582. /**
  86583. * Tertiary light Color (multiply against the B channel of the environement texture)
  86584. */
  86585. _this.tertiaryColor = BABYLON.Color3.Black();
  86586. /**
  86587. * Tertiary light Level (allowing HDR output of the background)
  86588. */
  86589. _this.tertiaryLevel = 1;
  86590. /**
  86591. * Reflection Texture used in the material.
  86592. * Should be author in a specific way for the best result (refer to the documentation).
  86593. */
  86594. _this.reflectionTexture = null;
  86595. /**
  86596. * Reflection Texture level of blur.
  86597. *
  86598. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  86599. * texture twice.
  86600. */
  86601. _this.reflectionBlur = 0;
  86602. /**
  86603. * Diffuse Texture used in the material.
  86604. * Should be author in a specific way for the best result (refer to the documentation).
  86605. */
  86606. _this.diffuseTexture = null;
  86607. _this._shadowLights = null;
  86608. /**
  86609. * Specify the list of lights casting shadow on the material.
  86610. * All scene shadow lights will be included if null.
  86611. */
  86612. _this.shadowLights = null;
  86613. /**
  86614. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  86615. * soft lighting on the background.
  86616. */
  86617. _this.shadowBlurScale = 1;
  86618. /**
  86619. * Helps adjusting the shadow to a softer level if required.
  86620. * 0 means black shadows and 1 means no shadows.
  86621. */
  86622. _this.shadowLevel = 0;
  86623. /**
  86624. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  86625. * It is usually zero but might be interesting to modify according to your setup.
  86626. */
  86627. _this.sceneCenter = BABYLON.Vector3.Zero();
  86628. /**
  86629. * This helps specifying that the material is falling off to the sky box at grazing angle.
  86630. * This helps ensuring a nice transition when the camera goes under the ground.
  86631. */
  86632. _this.opacityFresnel = true;
  86633. /**
  86634. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  86635. * This helps adding a mirror texture on the ground.
  86636. */
  86637. _this.reflectionFresnel = false;
  86638. /**
  86639. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  86640. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  86641. */
  86642. _this.reflectionFalloffDistance = 0.0;
  86643. /**
  86644. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  86645. */
  86646. _this.reflectionAmount = 1.0;
  86647. /**
  86648. * This specifies the weight of the reflection at grazing angle.
  86649. */
  86650. _this.reflectionReflectance0 = 0.05;
  86651. /**
  86652. * This specifies the weight of the reflection at a perpendicular point of view.
  86653. */
  86654. _this.reflectionReflectance90 = 0.5;
  86655. /**
  86656. * Helps to directly use the maps channels instead of their level.
  86657. */
  86658. _this.useRGBColor = true;
  86659. /**
  86660. * This helps reducing the banding effect that could occur on the background.
  86661. */
  86662. _this.enableNoise = false;
  86663. _this._fovMultiplier = 1.0;
  86664. /**
  86665. * Enable the FOV adjustment feature controlled by fovMultiplier.
  86666. * @type {boolean}
  86667. */
  86668. _this.useEquirectangularFOV = false;
  86669. _this._maxSimultaneousLights = 4;
  86670. /**
  86671. * Number of Simultaneous lights allowed on the material.
  86672. */
  86673. _this.maxSimultaneousLights = 4;
  86674. /**
  86675. * Keep track of the image processing observer to allow dispose and replace.
  86676. */
  86677. _this._imageProcessingObserver = null;
  86678. // Temp values kept as cache in the material.
  86679. _this._renderTargets = new BABYLON.SmartArray(16);
  86680. _this._reflectionControls = BABYLON.Vector4.Zero();
  86681. // Setup the default processing configuration to the scene.
  86682. _this._attachImageProcessingConfiguration(null);
  86683. _this.getRenderTargetTextures = function () {
  86684. _this._renderTargets.reset();
  86685. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  86686. _this._renderTargets.push(_this._diffuseTexture);
  86687. }
  86688. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  86689. _this._renderTargets.push(_this._reflectionTexture);
  86690. }
  86691. return _this._renderTargets;
  86692. };
  86693. return _this;
  86694. }
  86695. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  86696. /**
  86697. * Sets the reflection reflectance fresnel values according to the default standard
  86698. * empirically know to work well :-)
  86699. */
  86700. set: function (value) {
  86701. var reflectionWeight = value;
  86702. if (reflectionWeight < 0.5) {
  86703. reflectionWeight = reflectionWeight * 2.0;
  86704. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  86705. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  86706. }
  86707. else {
  86708. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  86709. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  86710. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  86711. }
  86712. },
  86713. enumerable: true,
  86714. configurable: true
  86715. });
  86716. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  86717. /**
  86718. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  86719. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  86720. * Recommended to be keep at 1.0 except for special cases.
  86721. */
  86722. get: function () {
  86723. return this._fovMultiplier;
  86724. },
  86725. set: function (value) {
  86726. if (isNaN(value)) {
  86727. value = 1.0;
  86728. }
  86729. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  86730. },
  86731. enumerable: true,
  86732. configurable: true
  86733. });
  86734. /**
  86735. * Attaches a new image processing configuration to the PBR Material.
  86736. * @param configuration (if null the scene configuration will be use)
  86737. */
  86738. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  86739. var _this = this;
  86740. if (configuration === this._imageProcessingConfiguration) {
  86741. return;
  86742. }
  86743. // Detaches observer.
  86744. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86745. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86746. }
  86747. // Pick the scene configuration if needed.
  86748. if (!configuration) {
  86749. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  86750. }
  86751. else {
  86752. this._imageProcessingConfiguration = configuration;
  86753. }
  86754. // Attaches observer.
  86755. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  86756. _this._markAllSubMeshesAsImageProcessingDirty();
  86757. });
  86758. };
  86759. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  86760. /**
  86761. * Gets the image processing configuration used either in this material.
  86762. */
  86763. get: function () {
  86764. return this._imageProcessingConfiguration;
  86765. },
  86766. /**
  86767. * Sets the Default image processing configuration used either in the this material.
  86768. *
  86769. * If sets to null, the scene one is in use.
  86770. */
  86771. set: function (value) {
  86772. this._attachImageProcessingConfiguration(value);
  86773. // Ensure the effect will be rebuilt.
  86774. this._markAllSubMeshesAsTexturesDirty();
  86775. },
  86776. enumerable: true,
  86777. configurable: true
  86778. });
  86779. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  86780. /**
  86781. * Gets wether the color curves effect is enabled.
  86782. */
  86783. get: function () {
  86784. return this.imageProcessingConfiguration.colorCurvesEnabled;
  86785. },
  86786. /**
  86787. * Sets wether the color curves effect is enabled.
  86788. */
  86789. set: function (value) {
  86790. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  86791. },
  86792. enumerable: true,
  86793. configurable: true
  86794. });
  86795. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  86796. /**
  86797. * Gets wether the color grading effect is enabled.
  86798. */
  86799. get: function () {
  86800. return this.imageProcessingConfiguration.colorGradingEnabled;
  86801. },
  86802. /**
  86803. * Gets wether the color grading effect is enabled.
  86804. */
  86805. set: function (value) {
  86806. this.imageProcessingConfiguration.colorGradingEnabled = value;
  86807. },
  86808. enumerable: true,
  86809. configurable: true
  86810. });
  86811. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  86812. /**
  86813. * Gets wether tonemapping is enabled or not.
  86814. */
  86815. get: function () {
  86816. return this._imageProcessingConfiguration.toneMappingEnabled;
  86817. },
  86818. /**
  86819. * Sets wether tonemapping is enabled or not
  86820. */
  86821. set: function (value) {
  86822. this._imageProcessingConfiguration.toneMappingEnabled = value;
  86823. },
  86824. enumerable: true,
  86825. configurable: true
  86826. });
  86827. ;
  86828. ;
  86829. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  86830. /**
  86831. * The camera exposure used on this material.
  86832. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  86833. * This corresponds to a photographic exposure.
  86834. */
  86835. get: function () {
  86836. return this._imageProcessingConfiguration.exposure;
  86837. },
  86838. /**
  86839. * The camera exposure used on this material.
  86840. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  86841. * This corresponds to a photographic exposure.
  86842. */
  86843. set: function (value) {
  86844. this._imageProcessingConfiguration.exposure = value;
  86845. },
  86846. enumerable: true,
  86847. configurable: true
  86848. });
  86849. ;
  86850. ;
  86851. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  86852. /**
  86853. * Gets The camera contrast used on this material.
  86854. */
  86855. get: function () {
  86856. return this._imageProcessingConfiguration.contrast;
  86857. },
  86858. /**
  86859. * Sets The camera contrast used on this material.
  86860. */
  86861. set: function (value) {
  86862. this._imageProcessingConfiguration.contrast = value;
  86863. },
  86864. enumerable: true,
  86865. configurable: true
  86866. });
  86867. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  86868. /**
  86869. * Gets the Color Grading 2D Lookup Texture.
  86870. */
  86871. get: function () {
  86872. return this._imageProcessingConfiguration.colorGradingTexture;
  86873. },
  86874. /**
  86875. * Sets the Color Grading 2D Lookup Texture.
  86876. */
  86877. set: function (value) {
  86878. this.imageProcessingConfiguration.colorGradingTexture = value;
  86879. },
  86880. enumerable: true,
  86881. configurable: true
  86882. });
  86883. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  86884. /**
  86885. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  86886. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  86887. * 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;
  86888. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  86889. */
  86890. get: function () {
  86891. return this.imageProcessingConfiguration.colorCurves;
  86892. },
  86893. /**
  86894. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  86895. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  86896. * 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;
  86897. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  86898. */
  86899. set: function (value) {
  86900. this.imageProcessingConfiguration.colorCurves = value;
  86901. },
  86902. enumerable: true,
  86903. configurable: true
  86904. });
  86905. /**
  86906. * The entire material has been created in order to prevent overdraw.
  86907. * @returns false
  86908. */
  86909. BackgroundMaterial.prototype.needAlphaTesting = function () {
  86910. return true;
  86911. };
  86912. /**
  86913. * The entire material has been created in order to prevent overdraw.
  86914. * @returns true if blending is enable
  86915. */
  86916. BackgroundMaterial.prototype.needAlphaBlending = function () {
  86917. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  86918. };
  86919. /**
  86920. * Checks wether the material is ready to be rendered for a given mesh.
  86921. * @param mesh The mesh to render
  86922. * @param subMesh The submesh to check against
  86923. * @param useInstances Specify wether or not the material is used with instances
  86924. * @returns true if all the dependencies are ready (Textures, Effects...)
  86925. */
  86926. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  86927. var _this = this;
  86928. if (useInstances === void 0) { useInstances = false; }
  86929. if (subMesh.effect && this.isFrozen) {
  86930. if (this._wasPreviouslyReady) {
  86931. return true;
  86932. }
  86933. }
  86934. if (!subMesh._materialDefines) {
  86935. subMesh._materialDefines = new BackgroundMaterialDefines();
  86936. }
  86937. var scene = this.getScene();
  86938. var defines = subMesh._materialDefines;
  86939. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  86940. if (defines._renderId === scene.getRenderId()) {
  86941. return true;
  86942. }
  86943. }
  86944. var engine = scene.getEngine();
  86945. // Lights
  86946. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  86947. defines._needNormals = true;
  86948. // Textures
  86949. if (defines._areTexturesDirty) {
  86950. defines._needUVs = false;
  86951. if (scene.texturesEnabled) {
  86952. if (scene.getEngine().getCaps().textureLOD) {
  86953. defines.TEXTURELODSUPPORT = true;
  86954. }
  86955. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  86956. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  86957. return false;
  86958. }
  86959. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  86960. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  86961. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  86962. defines.OPACITYFRESNEL = this._opacityFresnel;
  86963. }
  86964. else {
  86965. defines.DIFFUSE = false;
  86966. defines.DIFFUSEHASALPHA = false;
  86967. defines.GAMMADIFFUSE = false;
  86968. defines.OPACITYFRESNEL = false;
  86969. }
  86970. var reflectionTexture = this._reflectionTexture;
  86971. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  86972. if (!reflectionTexture.isReadyOrNotBlocking()) {
  86973. return false;
  86974. }
  86975. defines.REFLECTION = true;
  86976. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  86977. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  86978. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  86979. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  86980. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  86981. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  86982. defines.INVERTCUBICMAP = true;
  86983. }
  86984. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  86985. switch (reflectionTexture.coordinatesMode) {
  86986. case BABYLON.Texture.CUBIC_MODE:
  86987. case BABYLON.Texture.INVCUBIC_MODE:
  86988. defines.REFLECTIONMAP_CUBIC = true;
  86989. break;
  86990. case BABYLON.Texture.EXPLICIT_MODE:
  86991. defines.REFLECTIONMAP_EXPLICIT = true;
  86992. break;
  86993. case BABYLON.Texture.PLANAR_MODE:
  86994. defines.REFLECTIONMAP_PLANAR = true;
  86995. break;
  86996. case BABYLON.Texture.PROJECTION_MODE:
  86997. defines.REFLECTIONMAP_PROJECTION = true;
  86998. break;
  86999. case BABYLON.Texture.SKYBOX_MODE:
  87000. defines.REFLECTIONMAP_SKYBOX = true;
  87001. break;
  87002. case BABYLON.Texture.SPHERICAL_MODE:
  87003. defines.REFLECTIONMAP_SPHERICAL = true;
  87004. break;
  87005. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  87006. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  87007. break;
  87008. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  87009. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  87010. break;
  87011. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  87012. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  87013. break;
  87014. }
  87015. if (this.reflectionFresnel) {
  87016. defines.REFLECTIONFRESNEL = true;
  87017. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  87018. this._reflectionControls.x = this.reflectionAmount;
  87019. this._reflectionControls.y = this.reflectionReflectance0;
  87020. this._reflectionControls.z = this.reflectionReflectance90;
  87021. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  87022. }
  87023. else {
  87024. defines.REFLECTIONFRESNEL = false;
  87025. defines.REFLECTIONFALLOFF = false;
  87026. }
  87027. }
  87028. else {
  87029. defines.REFLECTION = false;
  87030. defines.REFLECTIONFALLOFF = false;
  87031. defines.REFLECTIONBLUR = false;
  87032. defines.REFLECTIONMAP_3D = false;
  87033. defines.REFLECTIONMAP_SPHERICAL = false;
  87034. defines.REFLECTIONMAP_PLANAR = false;
  87035. defines.REFLECTIONMAP_CUBIC = false;
  87036. defines.REFLECTIONMAP_PROJECTION = false;
  87037. defines.REFLECTIONMAP_SKYBOX = false;
  87038. defines.REFLECTIONMAP_EXPLICIT = false;
  87039. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  87040. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  87041. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  87042. defines.INVERTCUBICMAP = false;
  87043. defines.REFLECTIONMAP_OPPOSITEZ = false;
  87044. defines.LODINREFLECTIONALPHA = false;
  87045. defines.GAMMAREFLECTION = false;
  87046. }
  87047. }
  87048. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  87049. defines.USERGBCOLOR = this._useRGBColor;
  87050. defines.NOISE = this._enableNoise;
  87051. }
  87052. if (defines._areImageProcessingDirty) {
  87053. if (!this._imageProcessingConfiguration.isReady()) {
  87054. return false;
  87055. }
  87056. this._imageProcessingConfiguration.prepareDefines(defines);
  87057. }
  87058. // Misc.
  87059. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  87060. // Values that need to be evaluated on every frame
  87061. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  87062. // Attribs
  87063. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  87064. if (mesh) {
  87065. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  87066. mesh.createNormals(true);
  87067. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  87068. }
  87069. }
  87070. }
  87071. // Get correct effect
  87072. if (defines.isDirty) {
  87073. defines.markAsProcessed();
  87074. scene.resetCachedMaterial();
  87075. // Fallbacks
  87076. var fallbacks = new BABYLON.EffectFallbacks();
  87077. if (defines.FOG) {
  87078. fallbacks.addFallback(0, "FOG");
  87079. }
  87080. if (defines.POINTSIZE) {
  87081. fallbacks.addFallback(1, "POINTSIZE");
  87082. }
  87083. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  87084. if (defines.NUM_BONE_INFLUENCERS > 0) {
  87085. fallbacks.addCPUSkinningFallback(0, mesh);
  87086. }
  87087. //Attributes
  87088. var attribs = [BABYLON.VertexBuffer.PositionKind];
  87089. if (defines.NORMAL) {
  87090. attribs.push(BABYLON.VertexBuffer.NormalKind);
  87091. }
  87092. if (defines.UV1) {
  87093. attribs.push(BABYLON.VertexBuffer.UVKind);
  87094. }
  87095. if (defines.UV2) {
  87096. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  87097. }
  87098. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  87099. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  87100. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  87101. "vFogInfos", "vFogColor", "pointSize",
  87102. "vClipPlane", "mBones",
  87103. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  87104. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  87105. "shadowLevel", "alpha",
  87106. "vBackgroundCenter", "vReflectionControl",
  87107. "vDiffuseInfos", "diffuseMatrix",
  87108. ];
  87109. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  87110. var uniformBuffers = ["Material", "Scene"];
  87111. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  87112. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  87113. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  87114. uniformsNames: uniforms,
  87115. uniformBuffersNames: uniformBuffers,
  87116. samplers: samplers,
  87117. defines: defines,
  87118. maxSimultaneousLights: this._maxSimultaneousLights
  87119. });
  87120. var onCompiled = function (effect) {
  87121. if (_this.onCompiled) {
  87122. _this.onCompiled(effect);
  87123. }
  87124. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  87125. };
  87126. var join = defines.toString();
  87127. subMesh.setEffect(scene.getEngine().createEffect("background", {
  87128. attributes: attribs,
  87129. uniformsNames: uniforms,
  87130. uniformBuffersNames: uniformBuffers,
  87131. samplers: samplers,
  87132. defines: join,
  87133. fallbacks: fallbacks,
  87134. onCompiled: onCompiled,
  87135. onError: this.onError,
  87136. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  87137. }, engine), defines);
  87138. this.buildUniformLayout();
  87139. }
  87140. if (!subMesh.effect || !subMesh.effect.isReady()) {
  87141. return false;
  87142. }
  87143. defines._renderId = scene.getRenderId();
  87144. this._wasPreviouslyReady = true;
  87145. return true;
  87146. };
  87147. /**
  87148. * Build the uniform buffer used in the material.
  87149. */
  87150. BackgroundMaterial.prototype.buildUniformLayout = function () {
  87151. // Order is important !
  87152. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  87153. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  87154. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  87155. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  87156. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  87157. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  87158. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  87159. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  87160. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  87161. this._uniformBuffer.addUniform("pointSize", 1);
  87162. this._uniformBuffer.addUniform("shadowLevel", 1);
  87163. this._uniformBuffer.addUniform("alpha", 1);
  87164. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  87165. this._uniformBuffer.addUniform("vReflectionControl", 4);
  87166. this._uniformBuffer.create();
  87167. };
  87168. /**
  87169. * Unbind the material.
  87170. */
  87171. BackgroundMaterial.prototype.unbind = function () {
  87172. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  87173. this._uniformBuffer.setTexture("diffuseSampler", null);
  87174. }
  87175. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  87176. this._uniformBuffer.setTexture("reflectionSampler", null);
  87177. }
  87178. _super.prototype.unbind.call(this);
  87179. };
  87180. /**
  87181. * Bind only the world matrix to the material.
  87182. * @param world The world matrix to bind.
  87183. */
  87184. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  87185. this._activeEffect.setMatrix("world", world);
  87186. };
  87187. /**
  87188. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  87189. * @param world The world matrix to bind.
  87190. * @param subMesh The submesh to bind for.
  87191. */
  87192. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  87193. var scene = this.getScene();
  87194. var defines = subMesh._materialDefines;
  87195. if (!defines) {
  87196. return;
  87197. }
  87198. var effect = subMesh.effect;
  87199. if (!effect) {
  87200. return;
  87201. }
  87202. this._activeEffect = effect;
  87203. // Matrices
  87204. this.bindOnlyWorldMatrix(world);
  87205. // Bones
  87206. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  87207. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  87208. if (mustRebind) {
  87209. this._uniformBuffer.bindToEffect(effect, "Material");
  87210. this.bindViewProjection(effect);
  87211. var reflectionTexture = this._reflectionTexture;
  87212. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  87213. // Texture uniforms
  87214. if (scene.texturesEnabled) {
  87215. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87216. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  87217. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  87218. }
  87219. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87220. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  87221. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  87222. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  87223. }
  87224. }
  87225. if (this.shadowLevel > 0) {
  87226. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  87227. }
  87228. this._uniformBuffer.updateFloat("alpha", this.alpha);
  87229. // Point size
  87230. if (this.pointsCloud) {
  87231. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  87232. }
  87233. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  87234. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  87235. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  87236. }
  87237. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  87238. // Textures
  87239. if (scene.texturesEnabled) {
  87240. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87241. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  87242. }
  87243. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87244. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  87245. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87246. }
  87247. else if (!defines.REFLECTIONBLUR) {
  87248. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87249. }
  87250. else {
  87251. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  87252. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  87253. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  87254. }
  87255. if (defines.REFLECTIONFRESNEL) {
  87256. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  87257. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  87258. }
  87259. }
  87260. }
  87261. // Clip plane
  87262. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  87263. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  87264. }
  87265. if (mustRebind || !this.isFrozen) {
  87266. if (scene.lightsEnabled) {
  87267. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  87268. }
  87269. // View
  87270. this.bindView(effect);
  87271. // Fog
  87272. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  87273. // image processing
  87274. this._imageProcessingConfiguration.bind(this._activeEffect);
  87275. }
  87276. this._uniformBuffer.update();
  87277. this._afterBind(mesh);
  87278. };
  87279. /**
  87280. * Dispose the material.
  87281. * @param forceDisposeEffect Force disposal of the associated effect.
  87282. * @param forceDisposeTextures Force disposal of the associated textures.
  87283. */
  87284. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  87285. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  87286. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  87287. if (forceDisposeTextures) {
  87288. if (this.diffuseTexture) {
  87289. this.diffuseTexture.dispose();
  87290. }
  87291. if (this.reflectionTexture) {
  87292. this.reflectionTexture.dispose();
  87293. }
  87294. }
  87295. this._renderTargets.dispose();
  87296. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87297. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87298. }
  87299. _super.prototype.dispose.call(this, forceDisposeEffect);
  87300. };
  87301. /**
  87302. * Clones the material.
  87303. * @param name The cloned name.
  87304. * @returns The cloned material.
  87305. */
  87306. BackgroundMaterial.prototype.clone = function (name) {
  87307. var _this = this;
  87308. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  87309. };
  87310. /**
  87311. * Serializes the current material to its JSON representation.
  87312. * @returns The JSON representation.
  87313. */
  87314. BackgroundMaterial.prototype.serialize = function () {
  87315. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87316. serializationObject.customType = "BABYLON.BackgroundMaterial";
  87317. return serializationObject;
  87318. };
  87319. /**
  87320. * Gets the class name of the material
  87321. * @returns "BackgroundMaterial"
  87322. */
  87323. BackgroundMaterial.prototype.getClassName = function () {
  87324. return "BackgroundMaterial";
  87325. };
  87326. /**
  87327. * Parse a JSON input to create back a background material.
  87328. * @param source The JSON data to parse
  87329. * @param scene The scene to create the parsed material in
  87330. * @param rootUrl The root url of the assets the material depends upon
  87331. * @returns the instantiated BackgroundMaterial.
  87332. */
  87333. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  87334. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  87335. };
  87336. /**
  87337. * Standard reflectance value at parallel view angle.
  87338. */
  87339. BackgroundMaterial.StandardReflectance0 = 0.05;
  87340. /**
  87341. * Standard reflectance value at grazing angle.
  87342. */
  87343. BackgroundMaterial.StandardReflectance90 = 0.5;
  87344. __decorate([
  87345. BABYLON.serializeAsColor3()
  87346. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  87347. __decorate([
  87348. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87349. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  87350. __decorate([
  87351. BABYLON.serialize()
  87352. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  87353. __decorate([
  87354. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87355. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  87356. __decorate([
  87357. BABYLON.serializeAsColor3()
  87358. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  87359. __decorate([
  87360. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87361. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  87362. __decorate([
  87363. BABYLON.serialize()
  87364. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  87365. __decorate([
  87366. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87367. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  87368. __decorate([
  87369. BABYLON.serializeAsColor3()
  87370. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  87371. __decorate([
  87372. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87373. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  87374. __decorate([
  87375. BABYLON.serialize()
  87376. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  87377. __decorate([
  87378. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87379. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  87380. __decorate([
  87381. BABYLON.serializeAsTexture()
  87382. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  87383. __decorate([
  87384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87385. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  87386. __decorate([
  87387. BABYLON.serialize()
  87388. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  87389. __decorate([
  87390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87391. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  87392. __decorate([
  87393. BABYLON.serializeAsTexture()
  87394. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  87395. __decorate([
  87396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87397. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  87398. __decorate([
  87399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87400. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  87401. __decorate([
  87402. BABYLON.serialize()
  87403. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  87404. __decorate([
  87405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87406. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  87407. __decorate([
  87408. BABYLON.serialize()
  87409. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  87410. __decorate([
  87411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87412. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  87413. __decorate([
  87414. BABYLON.serializeAsVector3()
  87415. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  87416. __decorate([
  87417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87418. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  87419. __decorate([
  87420. BABYLON.serialize()
  87421. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  87422. __decorate([
  87423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87424. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  87425. __decorate([
  87426. BABYLON.serialize()
  87427. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  87428. __decorate([
  87429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87430. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  87431. __decorate([
  87432. BABYLON.serialize()
  87433. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  87434. __decorate([
  87435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87436. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  87437. __decorate([
  87438. BABYLON.serialize()
  87439. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  87440. __decorate([
  87441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87442. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  87443. __decorate([
  87444. BABYLON.serialize()
  87445. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  87446. __decorate([
  87447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87448. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  87449. __decorate([
  87450. BABYLON.serialize()
  87451. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  87452. __decorate([
  87453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87454. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  87455. __decorate([
  87456. BABYLON.serialize()
  87457. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  87458. __decorate([
  87459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87460. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  87461. __decorate([
  87462. BABYLON.serialize()
  87463. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  87464. __decorate([
  87465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87466. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  87467. __decorate([
  87468. BABYLON.serialize()
  87469. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  87470. __decorate([
  87471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87472. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  87473. __decorate([
  87474. BABYLON.serializeAsImageProcessingConfiguration()
  87475. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  87476. return BackgroundMaterial;
  87477. }(BABYLON.PushMaterial));
  87478. BABYLON.BackgroundMaterial = BackgroundMaterial;
  87479. })(BABYLON || (BABYLON = {}));
  87480. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  87481. var __assign = (this && this.__assign) || Object.assign || function(t) {
  87482. for (var s, i = 1, n = arguments.length; i < n; i++) {
  87483. s = arguments[i];
  87484. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  87485. t[p] = s[p];
  87486. }
  87487. return t;
  87488. };
  87489. var BABYLON;
  87490. (function (BABYLON) {
  87491. /**
  87492. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  87493. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  87494. * It also helps with the default setup of your imageProcessing configuration.
  87495. */
  87496. var EnvironmentHelper = /** @class */ (function () {
  87497. /**
  87498. * constructor
  87499. * @param options
  87500. * @param scene The scene to add the material to
  87501. */
  87502. function EnvironmentHelper(options, scene) {
  87503. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  87504. this._scene = scene;
  87505. this._setupBackground();
  87506. this._setupImageProcessing();
  87507. }
  87508. /**
  87509. * Creates the default options for the helper.
  87510. */
  87511. EnvironmentHelper._getDefaultOptions = function () {
  87512. return {
  87513. createGround: true,
  87514. groundSize: 15,
  87515. groundTexture: this._groundTextureCDNUrl,
  87516. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87517. groundOpacity: 0.9,
  87518. enableGroundShadow: true,
  87519. groundShadowLevel: 0.5,
  87520. enableGroundMirror: false,
  87521. groundMirrorSizeRatio: 0.3,
  87522. groundMirrorBlurKernel: 64,
  87523. groundMirrorAmount: 1,
  87524. groundMirrorFresnelWeight: 1,
  87525. groundMirrorFallOffDistance: 0,
  87526. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  87527. groundYBias: 0.00001,
  87528. createSkybox: true,
  87529. skyboxSize: 20,
  87530. skyboxTexture: this._skyboxTextureCDNUrl,
  87531. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87532. backgroundYRotation: 0,
  87533. sizeAuto: true,
  87534. rootPosition: BABYLON.Vector3.Zero(),
  87535. setupImageProcessing: true,
  87536. environmentTexture: this._environmentTextureCDNUrl,
  87537. cameraExposure: 0.8,
  87538. cameraContrast: 1.2,
  87539. toneMappingEnabled: true,
  87540. };
  87541. };
  87542. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  87543. /**
  87544. * Gets the root mesh created by the helper.
  87545. */
  87546. get: function () {
  87547. return this._rootMesh;
  87548. },
  87549. enumerable: true,
  87550. configurable: true
  87551. });
  87552. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  87553. /**
  87554. * Gets the skybox created by the helper.
  87555. */
  87556. get: function () {
  87557. return this._skybox;
  87558. },
  87559. enumerable: true,
  87560. configurable: true
  87561. });
  87562. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  87563. /**
  87564. * Gets the skybox texture created by the helper.
  87565. */
  87566. get: function () {
  87567. return this._skyboxTexture;
  87568. },
  87569. enumerable: true,
  87570. configurable: true
  87571. });
  87572. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  87573. /**
  87574. * Gets the skybox material created by the helper.
  87575. */
  87576. get: function () {
  87577. return this._skyboxMaterial;
  87578. },
  87579. enumerable: true,
  87580. configurable: true
  87581. });
  87582. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  87583. /**
  87584. * Gets the ground mesh created by the helper.
  87585. */
  87586. get: function () {
  87587. return this._ground;
  87588. },
  87589. enumerable: true,
  87590. configurable: true
  87591. });
  87592. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  87593. /**
  87594. * Gets the ground texture created by the helper.
  87595. */
  87596. get: function () {
  87597. return this._groundTexture;
  87598. },
  87599. enumerable: true,
  87600. configurable: true
  87601. });
  87602. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  87603. /**
  87604. * Gets the ground mirror created by the helper.
  87605. */
  87606. get: function () {
  87607. return this._groundMirror;
  87608. },
  87609. enumerable: true,
  87610. configurable: true
  87611. });
  87612. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  87613. /**
  87614. * Gets the ground mirror render list to helps pushing the meshes
  87615. * you wish in the ground reflection.
  87616. */
  87617. get: function () {
  87618. if (this._groundMirror) {
  87619. return this._groundMirror.renderList;
  87620. }
  87621. return null;
  87622. },
  87623. enumerable: true,
  87624. configurable: true
  87625. });
  87626. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  87627. /**
  87628. * Gets the ground material created by the helper.
  87629. */
  87630. get: function () {
  87631. return this._groundMaterial;
  87632. },
  87633. enumerable: true,
  87634. configurable: true
  87635. });
  87636. /**
  87637. * Updates the background according to the new options
  87638. * @param options
  87639. */
  87640. EnvironmentHelper.prototype.updateOptions = function (options) {
  87641. var newOptions = __assign({}, this._options, options);
  87642. if (this._ground && !newOptions.createGround) {
  87643. this._ground.dispose();
  87644. this._ground = null;
  87645. }
  87646. if (this._groundMaterial && !newOptions.createGround) {
  87647. this._groundMaterial.dispose();
  87648. this._groundMaterial = null;
  87649. }
  87650. if (this._groundTexture) {
  87651. if (this._options.groundTexture != newOptions.groundTexture) {
  87652. this._groundTexture.dispose();
  87653. this._groundTexture = null;
  87654. }
  87655. }
  87656. if (this._skybox && !newOptions.createSkybox) {
  87657. this._skybox.dispose();
  87658. this._skybox = null;
  87659. }
  87660. if (this._skyboxMaterial && !newOptions.createSkybox) {
  87661. this._skyboxMaterial.dispose();
  87662. this._skyboxMaterial = null;
  87663. }
  87664. if (this._skyboxTexture) {
  87665. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  87666. this._skyboxTexture.dispose();
  87667. this._skyboxTexture = null;
  87668. }
  87669. }
  87670. if (this._groundMirror && !newOptions.enableGroundMirror) {
  87671. this._groundMirror.dispose();
  87672. this._groundMirror = null;
  87673. }
  87674. if (this._scene.environmentTexture) {
  87675. if (this._options.environmentTexture != newOptions.environmentTexture) {
  87676. this._scene.environmentTexture.dispose();
  87677. }
  87678. }
  87679. this._options = newOptions;
  87680. this._setupBackground();
  87681. this._setupImageProcessing();
  87682. };
  87683. /**
  87684. * Sets the primary color of all the available elements.
  87685. * @param color
  87686. */
  87687. EnvironmentHelper.prototype.setMainColor = function (color) {
  87688. if (this.groundMaterial) {
  87689. this.groundMaterial.primaryColor = color;
  87690. }
  87691. if (this.skyboxMaterial) {
  87692. this.skyboxMaterial.primaryColor = color;
  87693. }
  87694. if (this.groundMirror) {
  87695. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  87696. }
  87697. };
  87698. /**
  87699. * Setup the image processing according to the specified options.
  87700. */
  87701. EnvironmentHelper.prototype._setupImageProcessing = function () {
  87702. if (this._options.setupImageProcessing) {
  87703. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  87704. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  87705. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  87706. this._setupEnvironmentTexture();
  87707. }
  87708. };
  87709. /**
  87710. * Setup the environment texture according to the specified options.
  87711. */
  87712. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  87713. if (this._scene.environmentTexture) {
  87714. return;
  87715. }
  87716. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  87717. this._scene.environmentTexture = this._options.environmentTexture;
  87718. return;
  87719. }
  87720. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  87721. this._scene.environmentTexture = environmentTexture;
  87722. };
  87723. /**
  87724. * Setup the background according to the specified options.
  87725. */
  87726. EnvironmentHelper.prototype._setupBackground = function () {
  87727. if (!this._rootMesh) {
  87728. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  87729. }
  87730. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  87731. var sceneSize = this._getSceneSize();
  87732. if (this._options.createGround) {
  87733. this._setupGround(sceneSize);
  87734. this._setupGroundMaterial();
  87735. this._setupGroundDiffuseTexture();
  87736. if (this._options.enableGroundMirror) {
  87737. this._setupGroundMirrorTexture(sceneSize);
  87738. }
  87739. this._setupMirrorInGroundMaterial();
  87740. }
  87741. if (this._options.createSkybox) {
  87742. this._setupSkybox(sceneSize);
  87743. this._setupSkyboxMaterial();
  87744. this._setupSkyboxReflectionTexture();
  87745. }
  87746. this._rootMesh.position.x = sceneSize.rootPosition.x;
  87747. this._rootMesh.position.z = sceneSize.rootPosition.z;
  87748. this._rootMesh.position.y = sceneSize.rootPosition.y;
  87749. };
  87750. /**
  87751. * Get the scene sizes according to the setup.
  87752. */
  87753. EnvironmentHelper.prototype._getSceneSize = function () {
  87754. var groundSize = this._options.groundSize;
  87755. var skyboxSize = this._options.skyboxSize;
  87756. var rootPosition = this._options.rootPosition;
  87757. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  87758. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  87759. }
  87760. var sceneExtends = this._scene.getWorldExtends();
  87761. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  87762. if (this._options.sizeAuto) {
  87763. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  87764. this._scene.activeCamera.upperRadiusLimit) {
  87765. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  87766. skyboxSize = groundSize;
  87767. }
  87768. var sceneDiagonalLenght = sceneDiagonal.length();
  87769. if (sceneDiagonalLenght > groundSize) {
  87770. groundSize = sceneDiagonalLenght * 2;
  87771. skyboxSize = groundSize;
  87772. }
  87773. // 10 % bigger.
  87774. groundSize *= 1.1;
  87775. skyboxSize *= 1.5;
  87776. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  87777. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  87778. }
  87779. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  87780. };
  87781. /**
  87782. * Setup the ground according to the specified options.
  87783. */
  87784. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  87785. var _this = this;
  87786. if (!this._ground) {
  87787. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  87788. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  87789. this._ground.parent = this._rootMesh;
  87790. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  87791. }
  87792. this._ground.receiveShadows = this._options.enableGroundShadow;
  87793. };
  87794. /**
  87795. * Setup the ground material according to the specified options.
  87796. */
  87797. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  87798. if (!this._groundMaterial) {
  87799. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  87800. }
  87801. this._groundMaterial.alpha = this._options.groundOpacity;
  87802. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  87803. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  87804. this._groundMaterial.primaryLevel = 1;
  87805. this._groundMaterial.primaryColor = this._options.groundColor;
  87806. this._groundMaterial.secondaryLevel = 0;
  87807. this._groundMaterial.tertiaryLevel = 0;
  87808. this._groundMaterial.useRGBColor = false;
  87809. this._groundMaterial.enableNoise = true;
  87810. if (this._ground) {
  87811. this._ground.material = this._groundMaterial;
  87812. }
  87813. };
  87814. /**
  87815. * Setup the ground diffuse texture according to the specified options.
  87816. */
  87817. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  87818. if (!this._groundMaterial) {
  87819. return;
  87820. }
  87821. if (this._groundTexture) {
  87822. return;
  87823. }
  87824. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  87825. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  87826. return;
  87827. }
  87828. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  87829. diffuseTexture.gammaSpace = false;
  87830. diffuseTexture.hasAlpha = true;
  87831. this._groundMaterial.diffuseTexture = diffuseTexture;
  87832. };
  87833. /**
  87834. * Setup the ground mirror texture according to the specified options.
  87835. */
  87836. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  87837. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87838. if (!this._groundMirror) {
  87839. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  87840. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  87841. this._groundMirror.anisotropicFilteringLevel = 1;
  87842. this._groundMirror.wrapU = wrapping;
  87843. this._groundMirror.wrapV = wrapping;
  87844. this._groundMirror.gammaSpace = false;
  87845. if (this._groundMirror.renderList) {
  87846. for (var i = 0; i < this._scene.meshes.length; i++) {
  87847. var mesh = this._scene.meshes[i];
  87848. if (mesh !== this._ground &&
  87849. mesh !== this._skybox &&
  87850. mesh !== this._rootMesh) {
  87851. this._groundMirror.renderList.push(mesh);
  87852. }
  87853. }
  87854. }
  87855. }
  87856. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  87857. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  87858. };
  87859. /**
  87860. * Setup the ground to receive the mirror texture.
  87861. */
  87862. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  87863. if (this._groundMaterial) {
  87864. this._groundMaterial.reflectionTexture = this._groundMirror;
  87865. this._groundMaterial.reflectionFresnel = true;
  87866. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  87867. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  87868. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  87869. }
  87870. };
  87871. /**
  87872. * Setup the skybox according to the specified options.
  87873. */
  87874. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  87875. var _this = this;
  87876. if (!this._skybox) {
  87877. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  87878. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  87879. }
  87880. this._skybox.parent = this._rootMesh;
  87881. };
  87882. /**
  87883. * Setup the skybox material according to the specified options.
  87884. */
  87885. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  87886. if (!this._skybox) {
  87887. return;
  87888. }
  87889. if (!this._skyboxMaterial) {
  87890. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  87891. }
  87892. this._skyboxMaterial.useRGBColor = false;
  87893. this._skyboxMaterial.primaryLevel = 1;
  87894. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  87895. this._skyboxMaterial.secondaryLevel = 0;
  87896. this._skyboxMaterial.tertiaryLevel = 0;
  87897. this._skyboxMaterial.enableNoise = true;
  87898. this._skybox.material = this._skyboxMaterial;
  87899. };
  87900. /**
  87901. * Setup the skybox reflection texture according to the specified options.
  87902. */
  87903. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  87904. if (!this._skyboxMaterial) {
  87905. return;
  87906. }
  87907. if (this._skyboxTexture) {
  87908. return;
  87909. }
  87910. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  87911. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  87912. return;
  87913. }
  87914. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  87915. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  87916. this._skyboxTexture.gammaSpace = false;
  87917. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  87918. };
  87919. /**
  87920. * Dispose all the elements created by the Helper.
  87921. */
  87922. EnvironmentHelper.prototype.dispose = function () {
  87923. if (this._groundMaterial) {
  87924. this._groundMaterial.dispose(true, true);
  87925. }
  87926. if (this._skyboxMaterial) {
  87927. this._skyboxMaterial.dispose(true, true);
  87928. }
  87929. this._rootMesh.dispose(false);
  87930. };
  87931. /**
  87932. * Default ground texture URL.
  87933. */
  87934. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  87935. /**
  87936. * Default skybox texture URL.
  87937. */
  87938. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  87939. /**
  87940. * Default environment texture URL.
  87941. */
  87942. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  87943. return EnvironmentHelper;
  87944. }());
  87945. BABYLON.EnvironmentHelper = EnvironmentHelper;
  87946. })(BABYLON || (BABYLON = {}));
  87947. //# sourceMappingURL=babylon.environmentHelper.js.map
  87948. 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,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  87949. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition );\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#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  87950. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  87951. var BABYLON;
  87952. (function (BABYLON) {
  87953. var GridMaterialDefines = /** @class */ (function (_super) {
  87954. __extends(GridMaterialDefines, _super);
  87955. function GridMaterialDefines() {
  87956. var _this = _super.call(this) || this;
  87957. _this.TRANSPARENT = false;
  87958. _this.FOG = false;
  87959. _this.PREMULTIPLYALPHA = false;
  87960. _this.rebuild();
  87961. return _this;
  87962. }
  87963. return GridMaterialDefines;
  87964. }(BABYLON.MaterialDefines));
  87965. /**
  87966. * The grid materials allows you to wrap any shape with a grid.
  87967. * Colors are customizable.
  87968. */
  87969. var GridMaterial = /** @class */ (function (_super) {
  87970. __extends(GridMaterial, _super);
  87971. /**
  87972. * constructor
  87973. * @param name The name given to the material in order to identify it afterwards.
  87974. * @param scene The scene the material is used in.
  87975. */
  87976. function GridMaterial(name, scene) {
  87977. var _this = _super.call(this, name, scene) || this;
  87978. /**
  87979. * Main color of the grid (e.g. between lines)
  87980. */
  87981. _this.mainColor = BABYLON.Color3.Black();
  87982. /**
  87983. * Color of the grid lines.
  87984. */
  87985. _this.lineColor = BABYLON.Color3.Teal();
  87986. /**
  87987. * The scale of the grid compared to unit.
  87988. */
  87989. _this.gridRatio = 1.0;
  87990. /**
  87991. * Allows setting an offset for the grid lines.
  87992. */
  87993. _this.gridOffset = BABYLON.Vector3.Zero();
  87994. /**
  87995. * The frequency of thicker lines.
  87996. */
  87997. _this.majorUnitFrequency = 10;
  87998. /**
  87999. * The visibility of minor units in the grid.
  88000. */
  88001. _this.minorUnitVisibility = 0.33;
  88002. /**
  88003. * The grid opacity outside of the lines.
  88004. */
  88005. _this.opacity = 1.0;
  88006. /**
  88007. * Determine RBG output is premultiplied by alpha value.
  88008. */
  88009. _this.preMultiplyAlpha = false;
  88010. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  88011. return _this;
  88012. }
  88013. /**
  88014. * Returns wehter or not the grid requires alpha blending.
  88015. */
  88016. GridMaterial.prototype.needAlphaBlending = function () {
  88017. return this.opacity < 1.0;
  88018. };
  88019. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  88020. return this.needAlphaBlending();
  88021. };
  88022. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  88023. if (this.isFrozen) {
  88024. if (this._wasPreviouslyReady && subMesh.effect) {
  88025. return true;
  88026. }
  88027. }
  88028. if (!subMesh._materialDefines) {
  88029. subMesh._materialDefines = new GridMaterialDefines();
  88030. }
  88031. var defines = subMesh._materialDefines;
  88032. var scene = this.getScene();
  88033. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  88034. if (this._renderId === scene.getRenderId()) {
  88035. return true;
  88036. }
  88037. }
  88038. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  88039. defines.TRANSPARENT = !defines.TRANSPARENT;
  88040. defines.markAsUnprocessed();
  88041. }
  88042. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  88043. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  88044. defines.markAsUnprocessed();
  88045. }
  88046. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  88047. // Get correct effect
  88048. if (defines.isDirty) {
  88049. defines.markAsProcessed();
  88050. scene.resetCachedMaterial();
  88051. // Attributes
  88052. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  88053. // Defines
  88054. var join = defines.toString();
  88055. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  88056. }
  88057. if (!subMesh.effect || !subMesh.effect.isReady()) {
  88058. return false;
  88059. }
  88060. this._renderId = scene.getRenderId();
  88061. this._wasPreviouslyReady = true;
  88062. return true;
  88063. };
  88064. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  88065. var scene = this.getScene();
  88066. var defines = subMesh._materialDefines;
  88067. if (!defines) {
  88068. return;
  88069. }
  88070. var effect = subMesh.effect;
  88071. if (!effect) {
  88072. return;
  88073. }
  88074. this._activeEffect = effect;
  88075. // Matrices
  88076. this.bindOnlyWorldMatrix(world);
  88077. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  88078. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  88079. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  88080. // Uniforms
  88081. if (this._mustRebind(scene, effect)) {
  88082. this._activeEffect.setColor3("mainColor", this.mainColor);
  88083. this._activeEffect.setColor3("lineColor", this.lineColor);
  88084. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  88085. this._gridControl.x = this.gridRatio;
  88086. this._gridControl.y = Math.round(this.majorUnitFrequency);
  88087. this._gridControl.z = this.minorUnitVisibility;
  88088. this._gridControl.w = this.opacity;
  88089. this._activeEffect.setVector4("gridControl", this._gridControl);
  88090. }
  88091. // Fog
  88092. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  88093. this._afterBind(mesh, this._activeEffect);
  88094. };
  88095. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  88096. _super.prototype.dispose.call(this, forceDisposeEffect);
  88097. };
  88098. GridMaterial.prototype.clone = function (name) {
  88099. var _this = this;
  88100. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  88101. };
  88102. GridMaterial.prototype.serialize = function () {
  88103. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88104. serializationObject.customType = "BABYLON.GridMaterial";
  88105. return serializationObject;
  88106. };
  88107. GridMaterial.prototype.getClassName = function () {
  88108. return "GridMaterial";
  88109. };
  88110. GridMaterial.Parse = function (source, scene, rootUrl) {
  88111. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  88112. };
  88113. __decorate([
  88114. BABYLON.serializeAsColor3()
  88115. ], GridMaterial.prototype, "mainColor", void 0);
  88116. __decorate([
  88117. BABYLON.serializeAsColor3()
  88118. ], GridMaterial.prototype, "lineColor", void 0);
  88119. __decorate([
  88120. BABYLON.serialize()
  88121. ], GridMaterial.prototype, "gridRatio", void 0);
  88122. __decorate([
  88123. BABYLON.serializeAsColor3()
  88124. ], GridMaterial.prototype, "gridOffset", void 0);
  88125. __decorate([
  88126. BABYLON.serialize()
  88127. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  88128. __decorate([
  88129. BABYLON.serialize()
  88130. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  88131. __decorate([
  88132. BABYLON.serialize()
  88133. ], GridMaterial.prototype, "opacity", void 0);
  88134. __decorate([
  88135. BABYLON.serialize()
  88136. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  88137. return GridMaterial;
  88138. }(BABYLON.PushMaterial));
  88139. BABYLON.GridMaterial = GridMaterial;
  88140. })(BABYLON || (BABYLON = {}));
  88141. //# sourceMappingURL=babylon.gridmaterial.js.map
  88142. 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}";
  88143. 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}";
  88144. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  88145. var BABYLON;
  88146. (function (BABYLON) {
  88147. var GLTFLoaderCoordinateSystemMode;
  88148. (function (GLTFLoaderCoordinateSystemMode) {
  88149. /**
  88150. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  88151. */
  88152. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  88153. /**
  88154. * Sets the useRightHandedSystem flag on the scene.
  88155. */
  88156. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  88157. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  88158. var GLTFLoaderAnimationStartMode;
  88159. (function (GLTFLoaderAnimationStartMode) {
  88160. /**
  88161. * No animation will start.
  88162. */
  88163. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  88164. /**
  88165. * The first animation will start.
  88166. */
  88167. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  88168. /**
  88169. * All animations will start.
  88170. */
  88171. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  88172. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  88173. var GLTFLoaderState;
  88174. (function (GLTFLoaderState) {
  88175. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  88176. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  88177. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  88178. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  88179. var GLTFFileLoader = /** @class */ (function () {
  88180. function GLTFFileLoader() {
  88181. // #region Common options
  88182. /**
  88183. * Raised when the asset has been parsed.
  88184. * The data.json property stores the glTF JSON.
  88185. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  88186. */
  88187. this.onParsedObservable = new BABYLON.Observable();
  88188. // #endregion
  88189. // #region V2 options
  88190. /**
  88191. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  88192. */
  88193. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  88194. /**
  88195. * The animation start mode (NONE, FIRST, ALL).
  88196. */
  88197. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  88198. /**
  88199. * Set to true to compile materials before raising the success callback.
  88200. */
  88201. this.compileMaterials = false;
  88202. /**
  88203. * Set to true to also compile materials with clip planes.
  88204. */
  88205. this.useClipPlane = false;
  88206. /**
  88207. * Set to true to compile shadow generators before raising the success callback.
  88208. */
  88209. this.compileShadowGenerators = false;
  88210. /**
  88211. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  88212. */
  88213. this.onMeshLoadedObservable = new BABYLON.Observable();
  88214. /**
  88215. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  88216. */
  88217. this.onTextureLoadedObservable = new BABYLON.Observable();
  88218. /**
  88219. * Raised when the loader creates a material after parsing the glTF properties of the material.
  88220. */
  88221. this.onMaterialLoadedObservable = new BABYLON.Observable();
  88222. /**
  88223. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  88224. * For assets with LODs, raised when all of the LODs are complete.
  88225. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  88226. */
  88227. this.onCompleteObservable = new BABYLON.Observable();
  88228. /**
  88229. * Raised when the loader is disposed.
  88230. */
  88231. this.onDisposeObservable = new BABYLON.Observable();
  88232. /**
  88233. * Raised after a loader extension is created.
  88234. * Set additional options for a loader extension in this event.
  88235. */
  88236. this.onExtensionLoadedObservable = new BABYLON.Observable();
  88237. // #endregion
  88238. this._loader = null;
  88239. this.name = "gltf";
  88240. this.extensions = {
  88241. ".gltf": { isBinary: false },
  88242. ".glb": { isBinary: true }
  88243. };
  88244. }
  88245. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  88246. set: function (callback) {
  88247. if (this._onParsedObserver) {
  88248. this.onParsedObservable.remove(this._onParsedObserver);
  88249. }
  88250. this._onParsedObserver = this.onParsedObservable.add(callback);
  88251. },
  88252. enumerable: true,
  88253. configurable: true
  88254. });
  88255. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  88256. set: function (callback) {
  88257. if (this._onMeshLoadedObserver) {
  88258. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  88259. }
  88260. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  88261. },
  88262. enumerable: true,
  88263. configurable: true
  88264. });
  88265. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  88266. set: function (callback) {
  88267. if (this._onTextureLoadedObserver) {
  88268. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  88269. }
  88270. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  88271. },
  88272. enumerable: true,
  88273. configurable: true
  88274. });
  88275. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  88276. set: function (callback) {
  88277. if (this._onMaterialLoadedObserver) {
  88278. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  88279. }
  88280. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  88281. },
  88282. enumerable: true,
  88283. configurable: true
  88284. });
  88285. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  88286. set: function (callback) {
  88287. if (this._onCompleteObserver) {
  88288. this.onCompleteObservable.remove(this._onCompleteObserver);
  88289. }
  88290. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  88291. },
  88292. enumerable: true,
  88293. configurable: true
  88294. });
  88295. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  88296. set: function (callback) {
  88297. if (this._onDisposeObserver) {
  88298. this.onDisposeObservable.remove(this._onDisposeObserver);
  88299. }
  88300. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88301. },
  88302. enumerable: true,
  88303. configurable: true
  88304. });
  88305. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  88306. set: function (callback) {
  88307. if (this._onExtensionLoadedObserver) {
  88308. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  88309. }
  88310. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  88311. },
  88312. enumerable: true,
  88313. configurable: true
  88314. });
  88315. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  88316. /**
  88317. * The loader state or null if not active.
  88318. */
  88319. get: function () {
  88320. return this._loader ? this._loader.state : null;
  88321. },
  88322. enumerable: true,
  88323. configurable: true
  88324. });
  88325. /**
  88326. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  88327. */
  88328. GLTFFileLoader.prototype.dispose = function () {
  88329. if (this._loader) {
  88330. this._loader.dispose();
  88331. this._loader = null;
  88332. }
  88333. this.onMeshLoadedObservable.clear();
  88334. this.onTextureLoadedObservable.clear();
  88335. this.onMaterialLoadedObservable.clear();
  88336. this.onDisposeObservable.notifyObservers(this);
  88337. this.onDisposeObservable.clear();
  88338. };
  88339. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  88340. var _this = this;
  88341. return Promise.resolve().then(function () {
  88342. var loaderData = _this._parse(data);
  88343. _this._loader = _this._getLoader(loaderData);
  88344. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  88345. });
  88346. };
  88347. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  88348. var _this = this;
  88349. return Promise.resolve().then(function () {
  88350. var loaderData = _this._parse(data);
  88351. _this._loader = _this._getLoader(loaderData);
  88352. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  88353. });
  88354. };
  88355. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  88356. var _this = this;
  88357. return Promise.resolve().then(function () {
  88358. var loaderData = _this._parse(data);
  88359. _this._loader = _this._getLoader(loaderData);
  88360. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  88361. var container = new BABYLON.AssetContainer(scene);
  88362. Array.prototype.push.apply(container.meshes, result.meshes);
  88363. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  88364. Array.prototype.push.apply(container.skeletons, result.skeletons);
  88365. container.removeAllFromScene();
  88366. return container;
  88367. });
  88368. });
  88369. };
  88370. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  88371. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  88372. };
  88373. GLTFFileLoader.prototype.createPlugin = function () {
  88374. return new GLTFFileLoader();
  88375. };
  88376. GLTFFileLoader.prototype._parse = function (data) {
  88377. var parsedData;
  88378. if (data instanceof ArrayBuffer) {
  88379. parsedData = GLTFFileLoader._parseBinary(data);
  88380. }
  88381. else {
  88382. parsedData = {
  88383. json: JSON.parse(data),
  88384. bin: null
  88385. };
  88386. }
  88387. this.onParsedObservable.notifyObservers(parsedData);
  88388. this.onParsedObservable.clear();
  88389. return parsedData;
  88390. };
  88391. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  88392. var _this = this;
  88393. var loaderVersion = { major: 2, minor: 0 };
  88394. var asset = loaderData.json.asset || {};
  88395. var version = GLTFFileLoader._parseVersion(asset.version);
  88396. if (!version) {
  88397. throw new Error("Invalid version: " + asset.version);
  88398. }
  88399. if (asset.minVersion !== undefined) {
  88400. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  88401. if (!minVersion) {
  88402. throw new Error("Invalid minimum version: " + asset.minVersion);
  88403. }
  88404. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  88405. throw new Error("Incompatible minimum version: " + asset.minVersion);
  88406. }
  88407. }
  88408. var createLoaders = {
  88409. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  88410. 2: GLTFFileLoader.CreateGLTFLoaderV2
  88411. };
  88412. var createLoader = createLoaders[version.major];
  88413. if (!createLoader) {
  88414. throw new Error("Unsupported version: " + asset.version);
  88415. }
  88416. var loader = createLoader();
  88417. loader.coordinateSystemMode = this.coordinateSystemMode;
  88418. loader.animationStartMode = this.animationStartMode;
  88419. loader.compileMaterials = this.compileMaterials;
  88420. loader.useClipPlane = this.useClipPlane;
  88421. loader.compileShadowGenerators = this.compileShadowGenerators;
  88422. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  88423. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  88424. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  88425. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  88426. loader.onCompleteObservable.add(function () {
  88427. _this.onMeshLoadedObservable.clear();
  88428. _this.onTextureLoadedObservable.clear();
  88429. _this.onMaterialLoadedObservable.clear();
  88430. _this.onCompleteObservable.notifyObservers(_this);
  88431. _this.onCompleteObservable.clear();
  88432. });
  88433. return loader;
  88434. };
  88435. GLTFFileLoader._parseBinary = function (data) {
  88436. var Binary = {
  88437. Magic: 0x46546C67
  88438. };
  88439. var binaryReader = new BinaryReader(data);
  88440. var magic = binaryReader.readUint32();
  88441. if (magic !== Binary.Magic) {
  88442. throw new Error("Unexpected magic: " + magic);
  88443. }
  88444. var version = binaryReader.readUint32();
  88445. switch (version) {
  88446. case 1: return GLTFFileLoader._parseV1(binaryReader);
  88447. case 2: return GLTFFileLoader._parseV2(binaryReader);
  88448. }
  88449. throw new Error("Unsupported version: " + version);
  88450. };
  88451. GLTFFileLoader._parseV1 = function (binaryReader) {
  88452. var ContentFormat = {
  88453. JSON: 0
  88454. };
  88455. var length = binaryReader.readUint32();
  88456. if (length != binaryReader.getLength()) {
  88457. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88458. }
  88459. var contentLength = binaryReader.readUint32();
  88460. var contentFormat = binaryReader.readUint32();
  88461. var content;
  88462. switch (contentFormat) {
  88463. case ContentFormat.JSON: {
  88464. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  88465. break;
  88466. }
  88467. default: {
  88468. throw new Error("Unexpected content format: " + contentFormat);
  88469. }
  88470. }
  88471. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  88472. var body = binaryReader.readUint8Array(bytesRemaining);
  88473. return {
  88474. json: content,
  88475. bin: body
  88476. };
  88477. };
  88478. GLTFFileLoader._parseV2 = function (binaryReader) {
  88479. var ChunkFormat = {
  88480. JSON: 0x4E4F534A,
  88481. BIN: 0x004E4942
  88482. };
  88483. var length = binaryReader.readUint32();
  88484. if (length !== binaryReader.getLength()) {
  88485. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88486. }
  88487. // JSON chunk
  88488. var chunkLength = binaryReader.readUint32();
  88489. var chunkFormat = binaryReader.readUint32();
  88490. if (chunkFormat !== ChunkFormat.JSON) {
  88491. throw new Error("First chunk format is not JSON");
  88492. }
  88493. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  88494. // Look for BIN chunk
  88495. var bin = null;
  88496. while (binaryReader.getPosition() < binaryReader.getLength()) {
  88497. var chunkLength_1 = binaryReader.readUint32();
  88498. var chunkFormat_1 = binaryReader.readUint32();
  88499. switch (chunkFormat_1) {
  88500. case ChunkFormat.JSON: {
  88501. throw new Error("Unexpected JSON chunk");
  88502. }
  88503. case ChunkFormat.BIN: {
  88504. bin = binaryReader.readUint8Array(chunkLength_1);
  88505. break;
  88506. }
  88507. default: {
  88508. // ignore unrecognized chunkFormat
  88509. binaryReader.skipBytes(chunkLength_1);
  88510. break;
  88511. }
  88512. }
  88513. }
  88514. return {
  88515. json: json,
  88516. bin: bin
  88517. };
  88518. };
  88519. GLTFFileLoader._parseVersion = function (version) {
  88520. if (version === "1.0" || version === "1.0.1") {
  88521. return {
  88522. major: 1,
  88523. minor: 0
  88524. };
  88525. }
  88526. var match = (version + "").match(/^(\d+)\.(\d+)/);
  88527. if (!match) {
  88528. return null;
  88529. }
  88530. return {
  88531. major: parseInt(match[1]),
  88532. minor: parseInt(match[2])
  88533. };
  88534. };
  88535. GLTFFileLoader._compareVersion = function (a, b) {
  88536. if (a.major > b.major)
  88537. return 1;
  88538. if (a.major < b.major)
  88539. return -1;
  88540. if (a.minor > b.minor)
  88541. return 1;
  88542. if (a.minor < b.minor)
  88543. return -1;
  88544. return 0;
  88545. };
  88546. GLTFFileLoader._decodeBufferToText = function (buffer) {
  88547. var result = "";
  88548. var length = buffer.byteLength;
  88549. for (var i = 0; i < length; i++) {
  88550. result += String.fromCharCode(buffer[i]);
  88551. }
  88552. return result;
  88553. };
  88554. // #endregion
  88555. // #region V1 options
  88556. GLTFFileLoader.IncrementalLoading = true;
  88557. GLTFFileLoader.HomogeneousCoordinates = false;
  88558. return GLTFFileLoader;
  88559. }());
  88560. BABYLON.GLTFFileLoader = GLTFFileLoader;
  88561. var BinaryReader = /** @class */ (function () {
  88562. function BinaryReader(arrayBuffer) {
  88563. this._arrayBuffer = arrayBuffer;
  88564. this._dataView = new DataView(arrayBuffer);
  88565. this._byteOffset = 0;
  88566. }
  88567. BinaryReader.prototype.getPosition = function () {
  88568. return this._byteOffset;
  88569. };
  88570. BinaryReader.prototype.getLength = function () {
  88571. return this._arrayBuffer.byteLength;
  88572. };
  88573. BinaryReader.prototype.readUint32 = function () {
  88574. var value = this._dataView.getUint32(this._byteOffset, true);
  88575. this._byteOffset += 4;
  88576. return value;
  88577. };
  88578. BinaryReader.prototype.readUint8Array = function (length) {
  88579. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  88580. this._byteOffset += length;
  88581. return value;
  88582. };
  88583. BinaryReader.prototype.skipBytes = function (length) {
  88584. this._byteOffset += length;
  88585. };
  88586. return BinaryReader;
  88587. }());
  88588. if (BABYLON.SceneLoader) {
  88589. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  88590. }
  88591. })(BABYLON || (BABYLON = {}));
  88592. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  88593. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88594. var BABYLON;
  88595. (function (BABYLON) {
  88596. var GLTF1;
  88597. (function (GLTF1) {
  88598. /**
  88599. * Enums
  88600. */
  88601. var EComponentType;
  88602. (function (EComponentType) {
  88603. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  88604. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88605. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  88606. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88607. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  88608. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  88609. var EShaderType;
  88610. (function (EShaderType) {
  88611. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  88612. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  88613. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  88614. var EParameterType;
  88615. (function (EParameterType) {
  88616. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  88617. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88618. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  88619. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88620. EParameterType[EParameterType["INT"] = 5124] = "INT";
  88621. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  88622. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  88623. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  88624. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  88625. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  88626. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  88627. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  88628. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  88629. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  88630. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  88631. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  88632. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  88633. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  88634. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  88635. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  88636. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  88637. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  88638. var ETextureWrapMode;
  88639. (function (ETextureWrapMode) {
  88640. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  88641. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  88642. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  88643. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  88644. var ETextureFilterType;
  88645. (function (ETextureFilterType) {
  88646. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  88647. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  88648. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  88649. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  88650. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  88651. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  88652. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  88653. var ETextureFormat;
  88654. (function (ETextureFormat) {
  88655. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  88656. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  88657. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  88658. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  88659. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  88660. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  88661. var ECullingType;
  88662. (function (ECullingType) {
  88663. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  88664. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  88665. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  88666. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  88667. var EBlendingFunction;
  88668. (function (EBlendingFunction) {
  88669. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  88670. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  88671. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  88672. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  88673. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  88674. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  88675. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  88676. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  88677. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  88678. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  88679. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  88680. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  88681. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  88682. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  88683. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  88684. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  88685. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  88686. })(BABYLON || (BABYLON = {}));
  88687. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  88688. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88689. var BABYLON;
  88690. (function (BABYLON) {
  88691. var GLTF1;
  88692. (function (GLTF1) {
  88693. /**
  88694. * Tokenizer. Used for shaders compatibility
  88695. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  88696. */
  88697. var ETokenType;
  88698. (function (ETokenType) {
  88699. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  88700. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  88701. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  88702. })(ETokenType || (ETokenType = {}));
  88703. var Tokenizer = /** @class */ (function () {
  88704. function Tokenizer(toParse) {
  88705. this._pos = 0;
  88706. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  88707. this._toParse = toParse;
  88708. this._maxPos = toParse.length;
  88709. }
  88710. Tokenizer.prototype.getNextToken = function () {
  88711. if (this.isEnd())
  88712. return ETokenType.END_OF_INPUT;
  88713. this.currentString = this.read();
  88714. this.currentToken = ETokenType.UNKNOWN;
  88715. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  88716. this.currentToken = ETokenType.IDENTIFIER;
  88717. this.currentIdentifier = this.currentString;
  88718. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  88719. this.currentIdentifier += this.currentString;
  88720. this.forward();
  88721. }
  88722. }
  88723. return this.currentToken;
  88724. };
  88725. Tokenizer.prototype.peek = function () {
  88726. return this._toParse[this._pos];
  88727. };
  88728. Tokenizer.prototype.read = function () {
  88729. return this._toParse[this._pos++];
  88730. };
  88731. Tokenizer.prototype.forward = function () {
  88732. this._pos++;
  88733. };
  88734. Tokenizer.prototype.isEnd = function () {
  88735. return this._pos >= this._maxPos;
  88736. };
  88737. return Tokenizer;
  88738. }());
  88739. /**
  88740. * Values
  88741. */
  88742. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  88743. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  88744. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  88745. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  88746. /**
  88747. * Parse
  88748. */
  88749. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  88750. for (var buf in parsedBuffers) {
  88751. var parsedBuffer = parsedBuffers[buf];
  88752. gltfRuntime.buffers[buf] = parsedBuffer;
  88753. gltfRuntime.buffersCount++;
  88754. }
  88755. };
  88756. var parseShaders = function (parsedShaders, gltfRuntime) {
  88757. for (var sha in parsedShaders) {
  88758. var parsedShader = parsedShaders[sha];
  88759. gltfRuntime.shaders[sha] = parsedShader;
  88760. gltfRuntime.shaderscount++;
  88761. }
  88762. };
  88763. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  88764. for (var object in parsedObjects) {
  88765. var parsedObject = parsedObjects[object];
  88766. gltfRuntime[runtimeProperty][object] = parsedObject;
  88767. }
  88768. };
  88769. /**
  88770. * Utils
  88771. */
  88772. var normalizeUVs = function (buffer) {
  88773. if (!buffer) {
  88774. return;
  88775. }
  88776. for (var i = 0; i < buffer.length / 2; i++) {
  88777. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  88778. }
  88779. };
  88780. var getAttribute = function (attributeParameter) {
  88781. if (attributeParameter.semantic === "NORMAL") {
  88782. return "normal";
  88783. }
  88784. else if (attributeParameter.semantic === "POSITION") {
  88785. return "position";
  88786. }
  88787. else if (attributeParameter.semantic === "JOINT") {
  88788. return "matricesIndices";
  88789. }
  88790. else if (attributeParameter.semantic === "WEIGHT") {
  88791. return "matricesWeights";
  88792. }
  88793. else if (attributeParameter.semantic === "COLOR") {
  88794. return "color";
  88795. }
  88796. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  88797. var channel = Number(attributeParameter.semantic.split("_")[1]);
  88798. return "uv" + (channel === 0 ? "" : channel + 1);
  88799. }
  88800. return null;
  88801. };
  88802. /**
  88803. * Loads and creates animations
  88804. */
  88805. var loadAnimations = function (gltfRuntime) {
  88806. for (var anim in gltfRuntime.animations) {
  88807. var animation = gltfRuntime.animations[anim];
  88808. if (!animation.channels || !animation.samplers) {
  88809. continue;
  88810. }
  88811. var lastAnimation = null;
  88812. for (var i = 0; i < animation.channels.length; i++) {
  88813. // Get parameters and load buffers
  88814. var channel = animation.channels[i];
  88815. var sampler = animation.samplers[channel.sampler];
  88816. if (!sampler) {
  88817. continue;
  88818. }
  88819. var inputData = null;
  88820. var outputData = null;
  88821. if (animation.parameters) {
  88822. inputData = animation.parameters[sampler.input];
  88823. outputData = animation.parameters[sampler.output];
  88824. }
  88825. else {
  88826. inputData = sampler.input;
  88827. outputData = sampler.output;
  88828. }
  88829. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  88830. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  88831. var targetID = channel.target.id;
  88832. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  88833. if (targetNode === null) {
  88834. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  88835. }
  88836. if (targetNode === null) {
  88837. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  88838. continue;
  88839. }
  88840. var isBone = targetNode instanceof BABYLON.Bone;
  88841. // Get target path (position, rotation or scaling)
  88842. var targetPath = channel.target.path;
  88843. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  88844. if (targetPathIndex !== -1) {
  88845. targetPath = babylonAnimationPaths[targetPathIndex];
  88846. }
  88847. // Determine animation type
  88848. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  88849. if (!isBone) {
  88850. if (targetPath === "rotationQuaternion") {
  88851. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  88852. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  88853. }
  88854. else {
  88855. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  88856. }
  88857. }
  88858. // Create animation and key frames
  88859. var babylonAnimation = null;
  88860. var keys = [];
  88861. var arrayOffset = 0;
  88862. var modifyKey = false;
  88863. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  88864. babylonAnimation = lastAnimation;
  88865. modifyKey = true;
  88866. }
  88867. if (!modifyKey) {
  88868. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88869. }
  88870. // For each frame
  88871. for (var j = 0; j < bufferInput.length; j++) {
  88872. var value = null;
  88873. if (targetPath === "rotationQuaternion") {
  88874. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  88875. arrayOffset += 4;
  88876. }
  88877. else {
  88878. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  88879. arrayOffset += 3;
  88880. }
  88881. if (isBone) {
  88882. var bone = targetNode;
  88883. var translation = BABYLON.Vector3.Zero();
  88884. var rotationQuaternion = new BABYLON.Quaternion();
  88885. var scaling = BABYLON.Vector3.Zero();
  88886. // Warning on decompose
  88887. var mat = bone.getBaseMatrix();
  88888. if (modifyKey && lastAnimation) {
  88889. mat = lastAnimation.getKeys()[j].value;
  88890. }
  88891. mat.decompose(scaling, rotationQuaternion, translation);
  88892. if (targetPath === "position") {
  88893. translation = value;
  88894. }
  88895. else if (targetPath === "rotationQuaternion") {
  88896. rotationQuaternion = value;
  88897. }
  88898. else {
  88899. scaling = value;
  88900. }
  88901. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  88902. }
  88903. if (!modifyKey) {
  88904. keys.push({
  88905. frame: bufferInput[j],
  88906. value: value
  88907. });
  88908. }
  88909. else if (lastAnimation) {
  88910. lastAnimation.getKeys()[j].value = value;
  88911. }
  88912. }
  88913. // Finish
  88914. if (!modifyKey && babylonAnimation) {
  88915. babylonAnimation.setKeys(keys);
  88916. targetNode.animations.push(babylonAnimation);
  88917. }
  88918. lastAnimation = babylonAnimation;
  88919. gltfRuntime.scene.stopAnimation(targetNode);
  88920. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  88921. }
  88922. }
  88923. };
  88924. /**
  88925. * Returns the bones transformation matrix
  88926. */
  88927. var configureBoneTransformation = function (node) {
  88928. var mat = null;
  88929. if (node.translation || node.rotation || node.scale) {
  88930. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  88931. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  88932. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  88933. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  88934. }
  88935. else {
  88936. mat = BABYLON.Matrix.FromArray(node.matrix);
  88937. }
  88938. return mat;
  88939. };
  88940. /**
  88941. * Returns the parent bone
  88942. */
  88943. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  88944. // Try to find
  88945. for (var i = 0; i < newSkeleton.bones.length; i++) {
  88946. if (newSkeleton.bones[i].name === jointName) {
  88947. return newSkeleton.bones[i];
  88948. }
  88949. }
  88950. // Not found, search in gltf nodes
  88951. var nodes = gltfRuntime.nodes;
  88952. for (var nde in nodes) {
  88953. var node = nodes[nde];
  88954. if (!node.jointName) {
  88955. continue;
  88956. }
  88957. var children = node.children;
  88958. for (var i = 0; i < children.length; i++) {
  88959. var child = gltfRuntime.nodes[children[i]];
  88960. if (!child.jointName) {
  88961. continue;
  88962. }
  88963. if (child.jointName === jointName) {
  88964. var mat = configureBoneTransformation(node);
  88965. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  88966. bone.id = nde;
  88967. return bone;
  88968. }
  88969. }
  88970. }
  88971. return null;
  88972. };
  88973. /**
  88974. * Returns the appropriate root node
  88975. */
  88976. var getNodeToRoot = function (nodesToRoot, id) {
  88977. for (var i = 0; i < nodesToRoot.length; i++) {
  88978. var nodeToRoot = nodesToRoot[i];
  88979. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  88980. var child = nodeToRoot.node.children[j];
  88981. if (child === id) {
  88982. return nodeToRoot.bone;
  88983. }
  88984. }
  88985. }
  88986. return null;
  88987. };
  88988. /**
  88989. * Returns the node with the joint name
  88990. */
  88991. var getJointNode = function (gltfRuntime, jointName) {
  88992. var nodes = gltfRuntime.nodes;
  88993. var node = nodes[jointName];
  88994. if (node) {
  88995. return {
  88996. node: node,
  88997. id: jointName
  88998. };
  88999. }
  89000. for (var nde in nodes) {
  89001. node = nodes[nde];
  89002. if (node.jointName === jointName) {
  89003. return {
  89004. node: node,
  89005. id: nde
  89006. };
  89007. }
  89008. }
  89009. return null;
  89010. };
  89011. /**
  89012. * Checks if a nodes is in joints
  89013. */
  89014. var nodeIsInJoints = function (skins, id) {
  89015. for (var i = 0; i < skins.jointNames.length; i++) {
  89016. if (skins.jointNames[i] === id) {
  89017. return true;
  89018. }
  89019. }
  89020. return false;
  89021. };
  89022. /**
  89023. * Fills the nodes to root for bones and builds hierarchy
  89024. */
  89025. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  89026. // Creates nodes for root
  89027. for (var nde in gltfRuntime.nodes) {
  89028. var node = gltfRuntime.nodes[nde];
  89029. var id = nde;
  89030. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  89031. continue;
  89032. }
  89033. // Create node to root bone
  89034. var mat = configureBoneTransformation(node);
  89035. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  89036. bone.id = id;
  89037. nodesToRoot.push({ bone: bone, node: node, id: id });
  89038. }
  89039. // Parenting
  89040. for (var i = 0; i < nodesToRoot.length; i++) {
  89041. var nodeToRoot = nodesToRoot[i];
  89042. var children = nodeToRoot.node.children;
  89043. for (var j = 0; j < children.length; j++) {
  89044. var child = null;
  89045. for (var k = 0; k < nodesToRoot.length; k++) {
  89046. if (nodesToRoot[k].id === children[j]) {
  89047. child = nodesToRoot[k];
  89048. break;
  89049. }
  89050. }
  89051. if (child) {
  89052. child.bone._parent = nodeToRoot.bone;
  89053. nodeToRoot.bone.children.push(child.bone);
  89054. }
  89055. }
  89056. }
  89057. };
  89058. /**
  89059. * Imports a skeleton
  89060. */
  89061. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  89062. if (!newSkeleton) {
  89063. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  89064. }
  89065. if (!skins.babylonSkeleton) {
  89066. return newSkeleton;
  89067. }
  89068. // Find the root bones
  89069. var nodesToRoot = [];
  89070. var nodesToRootToAdd = [];
  89071. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  89072. newSkeleton.bones = [];
  89073. // Joints
  89074. for (var i = 0; i < skins.jointNames.length; i++) {
  89075. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  89076. if (!jointNode) {
  89077. continue;
  89078. }
  89079. var node = jointNode.node;
  89080. if (!node) {
  89081. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  89082. continue;
  89083. }
  89084. var id = jointNode.id;
  89085. // Optimize, if the bone already exists...
  89086. var existingBone = gltfRuntime.scene.getBoneByID(id);
  89087. if (existingBone) {
  89088. newSkeleton.bones.push(existingBone);
  89089. continue;
  89090. }
  89091. // Search for parent bone
  89092. var foundBone = false;
  89093. var parentBone = null;
  89094. for (var j = 0; j < i; j++) {
  89095. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  89096. if (!jointNode_1) {
  89097. continue;
  89098. }
  89099. var joint = jointNode_1.node;
  89100. if (!joint) {
  89101. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  89102. continue;
  89103. }
  89104. var children = joint.children;
  89105. if (!children) {
  89106. continue;
  89107. }
  89108. foundBone = false;
  89109. for (var k = 0; k < children.length; k++) {
  89110. if (children[k] === id) {
  89111. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  89112. foundBone = true;
  89113. break;
  89114. }
  89115. }
  89116. if (foundBone) {
  89117. break;
  89118. }
  89119. }
  89120. // Create bone
  89121. var mat = configureBoneTransformation(node);
  89122. if (!parentBone && nodesToRoot.length > 0) {
  89123. parentBone = getNodeToRoot(nodesToRoot, id);
  89124. if (parentBone) {
  89125. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  89126. nodesToRootToAdd.push(parentBone);
  89127. }
  89128. }
  89129. }
  89130. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  89131. bone.id = id;
  89132. }
  89133. // Polish
  89134. var bones = newSkeleton.bones;
  89135. newSkeleton.bones = [];
  89136. for (var i = 0; i < skins.jointNames.length; i++) {
  89137. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  89138. if (!jointNode) {
  89139. continue;
  89140. }
  89141. for (var j = 0; j < bones.length; j++) {
  89142. if (bones[j].id === jointNode.id) {
  89143. newSkeleton.bones.push(bones[j]);
  89144. break;
  89145. }
  89146. }
  89147. }
  89148. newSkeleton.prepare();
  89149. // Finish
  89150. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  89151. newSkeleton.bones.push(nodesToRootToAdd[i]);
  89152. }
  89153. return newSkeleton;
  89154. };
  89155. /**
  89156. * Imports a mesh and its geometries
  89157. */
  89158. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  89159. if (!newMesh) {
  89160. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  89161. newMesh.id = id;
  89162. }
  89163. if (!node.babylonNode) {
  89164. return newMesh;
  89165. }
  89166. var subMaterials = [];
  89167. var vertexData = null;
  89168. var verticesStarts = new Array();
  89169. var verticesCounts = new Array();
  89170. var indexStarts = new Array();
  89171. var indexCounts = new Array();
  89172. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  89173. var meshID = meshes[meshIndex];
  89174. var mesh = gltfRuntime.meshes[meshID];
  89175. if (!mesh) {
  89176. continue;
  89177. }
  89178. // Positions, normals and UVs
  89179. for (var i = 0; i < mesh.primitives.length; i++) {
  89180. // Temporary vertex data
  89181. var tempVertexData = new BABYLON.VertexData();
  89182. var primitive = mesh.primitives[i];
  89183. if (primitive.mode !== 4) {
  89184. // continue;
  89185. }
  89186. var attributes = primitive.attributes;
  89187. var accessor = null;
  89188. var buffer = null;
  89189. // Set positions, normal and uvs
  89190. for (var semantic in attributes) {
  89191. // Link accessor and buffer view
  89192. accessor = gltfRuntime.accessors[attributes[semantic]];
  89193. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  89194. if (semantic === "NORMAL") {
  89195. tempVertexData.normals = new Float32Array(buffer.length);
  89196. tempVertexData.normals.set(buffer);
  89197. }
  89198. else if (semantic === "POSITION") {
  89199. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  89200. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  89201. for (var j = 0; j < buffer.length; j += 4) {
  89202. tempVertexData.positions[j] = buffer[j];
  89203. tempVertexData.positions[j + 1] = buffer[j + 1];
  89204. tempVertexData.positions[j + 2] = buffer[j + 2];
  89205. }
  89206. }
  89207. else {
  89208. tempVertexData.positions = new Float32Array(buffer.length);
  89209. tempVertexData.positions.set(buffer);
  89210. }
  89211. verticesCounts.push(tempVertexData.positions.length);
  89212. }
  89213. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  89214. var channel = Number(semantic.split("_")[1]);
  89215. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  89216. var uvs = new Float32Array(buffer.length);
  89217. uvs.set(buffer);
  89218. normalizeUVs(uvs);
  89219. tempVertexData.set(uvs, uvKind);
  89220. }
  89221. else if (semantic === "JOINT") {
  89222. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  89223. tempVertexData.matricesIndices.set(buffer);
  89224. }
  89225. else if (semantic === "WEIGHT") {
  89226. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  89227. tempVertexData.matricesWeights.set(buffer);
  89228. }
  89229. else if (semantic === "COLOR") {
  89230. tempVertexData.colors = new Float32Array(buffer.length);
  89231. tempVertexData.colors.set(buffer);
  89232. }
  89233. }
  89234. // Indices
  89235. accessor = gltfRuntime.accessors[primitive.indices];
  89236. if (accessor) {
  89237. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  89238. tempVertexData.indices = new Int32Array(buffer.length);
  89239. tempVertexData.indices.set(buffer);
  89240. indexCounts.push(tempVertexData.indices.length);
  89241. }
  89242. else {
  89243. // Set indices on the fly
  89244. var indices = [];
  89245. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  89246. indices.push(j);
  89247. }
  89248. tempVertexData.indices = new Int32Array(indices);
  89249. indexCounts.push(tempVertexData.indices.length);
  89250. }
  89251. if (!vertexData) {
  89252. vertexData = tempVertexData;
  89253. }
  89254. else {
  89255. vertexData.merge(tempVertexData);
  89256. }
  89257. // Sub material
  89258. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  89259. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  89260. // Update vertices start and index start
  89261. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  89262. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  89263. }
  89264. }
  89265. var material;
  89266. if (subMaterials.length > 1) {
  89267. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  89268. material.subMaterials = subMaterials;
  89269. }
  89270. else {
  89271. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  89272. }
  89273. if (subMaterials.length === 1) {
  89274. material = subMaterials[0];
  89275. }
  89276. if (!newMesh.material) {
  89277. newMesh.material = material;
  89278. }
  89279. // Apply geometry
  89280. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  89281. newMesh.computeWorldMatrix(true);
  89282. // Apply submeshes
  89283. newMesh.subMeshes = [];
  89284. var index = 0;
  89285. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  89286. var meshID = meshes[meshIndex];
  89287. var mesh = gltfRuntime.meshes[meshID];
  89288. if (!mesh) {
  89289. continue;
  89290. }
  89291. for (var i = 0; i < mesh.primitives.length; i++) {
  89292. if (mesh.primitives[i].mode !== 4) {
  89293. //continue;
  89294. }
  89295. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  89296. index++;
  89297. }
  89298. }
  89299. // Finish
  89300. return newMesh;
  89301. };
  89302. /**
  89303. * Configure node transformation from position, rotation and scaling
  89304. */
  89305. var configureNode = function (newNode, position, rotation, scaling) {
  89306. if (newNode.position) {
  89307. newNode.position = position;
  89308. }
  89309. if (newNode.rotationQuaternion || newNode.rotation) {
  89310. newNode.rotationQuaternion = rotation;
  89311. }
  89312. if (newNode.scaling) {
  89313. newNode.scaling = scaling;
  89314. }
  89315. };
  89316. /**
  89317. * Configures node from transformation matrix
  89318. */
  89319. var configureNodeFromMatrix = function (newNode, node, parent) {
  89320. if (node.matrix) {
  89321. var position = new BABYLON.Vector3(0, 0, 0);
  89322. var rotation = new BABYLON.Quaternion();
  89323. var scaling = new BABYLON.Vector3(0, 0, 0);
  89324. var mat = BABYLON.Matrix.FromArray(node.matrix);
  89325. mat.decompose(scaling, rotation, position);
  89326. configureNode(newNode, position, rotation, scaling);
  89327. }
  89328. else if (node.translation && node.rotation && node.scale) {
  89329. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  89330. }
  89331. newNode.computeWorldMatrix(true);
  89332. };
  89333. /**
  89334. * Imports a node
  89335. */
  89336. var importNode = function (gltfRuntime, node, id, parent) {
  89337. var lastNode = null;
  89338. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  89339. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  89340. return null;
  89341. }
  89342. }
  89343. // Meshes
  89344. if (node.skin) {
  89345. if (node.meshes) {
  89346. var skin = gltfRuntime.skins[node.skin];
  89347. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  89348. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  89349. if (newMesh.skeleton === null) {
  89350. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  89351. if (!skin.babylonSkeleton) {
  89352. skin.babylonSkeleton = newMesh.skeleton;
  89353. }
  89354. }
  89355. lastNode = newMesh;
  89356. }
  89357. }
  89358. else if (node.meshes) {
  89359. /**
  89360. * Improve meshes property
  89361. */
  89362. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  89363. lastNode = newMesh;
  89364. }
  89365. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89366. var light = gltfRuntime.lights[node.light];
  89367. if (light) {
  89368. if (light.type === "ambient") {
  89369. var ambienLight = light[light.type];
  89370. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89371. hemiLight.name = node.name || "";
  89372. if (ambienLight.color) {
  89373. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  89374. }
  89375. lastNode = hemiLight;
  89376. }
  89377. else if (light.type === "directional") {
  89378. var directionalLight = light[light.type];
  89379. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89380. dirLight.name = node.name || "";
  89381. if (directionalLight.color) {
  89382. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  89383. }
  89384. lastNode = dirLight;
  89385. }
  89386. else if (light.type === "point") {
  89387. var pointLight = light[light.type];
  89388. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89389. ptLight.name = node.name || "";
  89390. if (pointLight.color) {
  89391. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  89392. }
  89393. lastNode = ptLight;
  89394. }
  89395. else if (light.type === "spot") {
  89396. var spotLight = light[light.type];
  89397. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  89398. spLight.name = node.name || "";
  89399. if (spotLight.color) {
  89400. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  89401. }
  89402. if (spotLight.fallOfAngle) {
  89403. spLight.angle = spotLight.fallOfAngle;
  89404. }
  89405. if (spotLight.fallOffExponent) {
  89406. spLight.exponent = spotLight.fallOffExponent;
  89407. }
  89408. lastNode = spLight;
  89409. }
  89410. }
  89411. }
  89412. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89413. var camera = gltfRuntime.cameras[node.camera];
  89414. if (camera) {
  89415. if (camera.type === "orthographic") {
  89416. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89417. orthoCamera.name = node.name || "";
  89418. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  89419. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89420. lastNode = orthoCamera;
  89421. }
  89422. else if (camera.type === "perspective") {
  89423. var perspectiveCamera = camera[camera.type];
  89424. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89425. persCamera.name = node.name || "";
  89426. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89427. if (!perspectiveCamera.aspectRatio) {
  89428. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  89429. }
  89430. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  89431. persCamera.maxZ = perspectiveCamera.zfar;
  89432. persCamera.minZ = perspectiveCamera.znear;
  89433. }
  89434. lastNode = persCamera;
  89435. }
  89436. }
  89437. }
  89438. // Empty node
  89439. if (!node.jointName) {
  89440. if (node.babylonNode) {
  89441. return node.babylonNode;
  89442. }
  89443. else if (lastNode === null) {
  89444. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  89445. node.babylonNode = dummy;
  89446. lastNode = dummy;
  89447. }
  89448. }
  89449. if (lastNode !== null) {
  89450. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  89451. configureNodeFromMatrix(lastNode, node, parent);
  89452. }
  89453. else {
  89454. var translation = node.translation || [0, 0, 0];
  89455. var rotation = node.rotation || [0, 0, 0, 1];
  89456. var scale = node.scale || [1, 1, 1];
  89457. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  89458. }
  89459. lastNode.updateCache(true);
  89460. node.babylonNode = lastNode;
  89461. }
  89462. return lastNode;
  89463. };
  89464. /**
  89465. * Traverses nodes and creates them
  89466. */
  89467. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  89468. if (meshIncluded === void 0) { meshIncluded = false; }
  89469. var node = gltfRuntime.nodes[id];
  89470. var newNode = null;
  89471. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  89472. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  89473. meshIncluded = true;
  89474. }
  89475. else {
  89476. meshIncluded = false;
  89477. }
  89478. }
  89479. else {
  89480. meshIncluded = true;
  89481. }
  89482. if (!node.jointName && meshIncluded) {
  89483. newNode = importNode(gltfRuntime, node, id, parent);
  89484. if (newNode !== null) {
  89485. newNode.id = id;
  89486. newNode.parent = parent;
  89487. }
  89488. }
  89489. if (node.children) {
  89490. for (var i = 0; i < node.children.length; i++) {
  89491. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  89492. }
  89493. }
  89494. };
  89495. /**
  89496. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  89497. */
  89498. var postLoad = function (gltfRuntime) {
  89499. // Nodes
  89500. var currentScene = gltfRuntime.currentScene;
  89501. if (currentScene) {
  89502. for (var i = 0; i < currentScene.nodes.length; i++) {
  89503. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89504. }
  89505. }
  89506. else {
  89507. for (var thing in gltfRuntime.scenes) {
  89508. currentScene = gltfRuntime.scenes[thing];
  89509. for (var i = 0; i < currentScene.nodes.length; i++) {
  89510. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89511. }
  89512. }
  89513. }
  89514. // Set animations
  89515. loadAnimations(gltfRuntime);
  89516. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  89517. var skeleton = gltfRuntime.scene.skeletons[i];
  89518. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  89519. }
  89520. };
  89521. /**
  89522. * onBind shaderrs callback to set uniforms and matrices
  89523. */
  89524. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  89525. var materialValues = material.values || technique.parameters;
  89526. for (var unif in unTreatedUniforms) {
  89527. var uniform = unTreatedUniforms[unif];
  89528. var type = uniform.type;
  89529. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  89530. if (uniform.semantic && !uniform.source && !uniform.node) {
  89531. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  89532. }
  89533. else if (uniform.semantic && (uniform.source || uniform.node)) {
  89534. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  89535. if (source === null) {
  89536. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  89537. }
  89538. if (source === null) {
  89539. continue;
  89540. }
  89541. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  89542. }
  89543. }
  89544. else {
  89545. var value = materialValues[technique.uniforms[unif]];
  89546. if (!value) {
  89547. continue;
  89548. }
  89549. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89550. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  89551. if (texture === null || texture === undefined) {
  89552. continue;
  89553. }
  89554. shaderMaterial.getEffect().setTexture(unif, texture);
  89555. }
  89556. else {
  89557. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  89558. }
  89559. }
  89560. }
  89561. onSuccess(shaderMaterial);
  89562. };
  89563. /**
  89564. * Prepare uniforms to send the only one time
  89565. * Loads the appropriate textures
  89566. */
  89567. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  89568. var materialValues = material.values || technique.parameters;
  89569. var techniqueUniforms = technique.uniforms;
  89570. /**
  89571. * Prepare values here (not matrices)
  89572. */
  89573. for (var unif in unTreatedUniforms) {
  89574. var uniform = unTreatedUniforms[unif];
  89575. var type = uniform.type;
  89576. var value = materialValues[techniqueUniforms[unif]];
  89577. if (value === undefined) {
  89578. // In case the value is the same for all materials
  89579. value = uniform.value;
  89580. }
  89581. if (!value) {
  89582. continue;
  89583. }
  89584. var onLoadTexture = function (uniformName) {
  89585. return function (texture) {
  89586. if (uniform.value && uniformName) {
  89587. // Static uniform
  89588. shaderMaterial.setTexture(uniformName, texture);
  89589. delete unTreatedUniforms[uniformName];
  89590. }
  89591. };
  89592. };
  89593. // Texture (sampler2D)
  89594. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89595. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  89596. }
  89597. else {
  89598. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  89599. // Static uniform
  89600. delete unTreatedUniforms[unif];
  89601. }
  89602. }
  89603. }
  89604. };
  89605. /**
  89606. * Shader compilation failed
  89607. */
  89608. var onShaderCompileError = function (program, shaderMaterial, onError) {
  89609. return function (effect, error) {
  89610. shaderMaterial.dispose(true);
  89611. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  89612. };
  89613. };
  89614. /**
  89615. * Shader compilation success
  89616. */
  89617. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  89618. return function (_) {
  89619. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  89620. shaderMaterial.onBind = function (mesh) {
  89621. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  89622. };
  89623. };
  89624. };
  89625. /**
  89626. * Returns the appropriate uniform if already handled by babylon
  89627. */
  89628. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  89629. for (var unif in technique.uniforms) {
  89630. var uniform = technique.uniforms[unif];
  89631. var uniformParameter = technique.parameters[uniform];
  89632. if (tokenizer.currentIdentifier === unif) {
  89633. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  89634. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  89635. if (transformIndex !== -1) {
  89636. delete unTreatedUniforms[unif];
  89637. return babylonTransforms[transformIndex];
  89638. }
  89639. }
  89640. }
  89641. }
  89642. return tokenizer.currentIdentifier;
  89643. };
  89644. /**
  89645. * All shaders loaded. Create materials one by one
  89646. */
  89647. var importMaterials = function (gltfRuntime) {
  89648. // Create materials
  89649. for (var mat in gltfRuntime.materials) {
  89650. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  89651. }
  89652. };
  89653. /**
  89654. * Implementation of the base glTF spec
  89655. */
  89656. var GLTFLoaderBase = /** @class */ (function () {
  89657. function GLTFLoaderBase() {
  89658. }
  89659. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  89660. var gltfRuntime = {
  89661. extensions: {},
  89662. accessors: {},
  89663. buffers: {},
  89664. bufferViews: {},
  89665. meshes: {},
  89666. lights: {},
  89667. cameras: {},
  89668. nodes: {},
  89669. images: {},
  89670. textures: {},
  89671. shaders: {},
  89672. programs: {},
  89673. samplers: {},
  89674. techniques: {},
  89675. materials: {},
  89676. animations: {},
  89677. skins: {},
  89678. extensionsUsed: [],
  89679. scenes: {},
  89680. buffersCount: 0,
  89681. shaderscount: 0,
  89682. scene: scene,
  89683. rootUrl: rootUrl,
  89684. loadedBufferCount: 0,
  89685. loadedBufferViews: {},
  89686. loadedShaderCount: 0,
  89687. importOnlyMeshes: false,
  89688. dummyNodes: []
  89689. };
  89690. // Parse
  89691. if (parsedData.extensions) {
  89692. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  89693. }
  89694. if (parsedData.extensionsUsed) {
  89695. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  89696. }
  89697. if (parsedData.buffers) {
  89698. parseBuffers(parsedData.buffers, gltfRuntime);
  89699. }
  89700. if (parsedData.bufferViews) {
  89701. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  89702. }
  89703. if (parsedData.accessors) {
  89704. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  89705. }
  89706. if (parsedData.meshes) {
  89707. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  89708. }
  89709. if (parsedData.lights) {
  89710. parseObject(parsedData.lights, "lights", gltfRuntime);
  89711. }
  89712. if (parsedData.cameras) {
  89713. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  89714. }
  89715. if (parsedData.nodes) {
  89716. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  89717. }
  89718. if (parsedData.images) {
  89719. parseObject(parsedData.images, "images", gltfRuntime);
  89720. }
  89721. if (parsedData.textures) {
  89722. parseObject(parsedData.textures, "textures", gltfRuntime);
  89723. }
  89724. if (parsedData.shaders) {
  89725. parseShaders(parsedData.shaders, gltfRuntime);
  89726. }
  89727. if (parsedData.programs) {
  89728. parseObject(parsedData.programs, "programs", gltfRuntime);
  89729. }
  89730. if (parsedData.samplers) {
  89731. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  89732. }
  89733. if (parsedData.techniques) {
  89734. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  89735. }
  89736. if (parsedData.materials) {
  89737. parseObject(parsedData.materials, "materials", gltfRuntime);
  89738. }
  89739. if (parsedData.animations) {
  89740. parseObject(parsedData.animations, "animations", gltfRuntime);
  89741. }
  89742. if (parsedData.skins) {
  89743. parseObject(parsedData.skins, "skins", gltfRuntime);
  89744. }
  89745. if (parsedData.scenes) {
  89746. gltfRuntime.scenes = parsedData.scenes;
  89747. }
  89748. if (parsedData.scene && parsedData.scenes) {
  89749. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  89750. }
  89751. return gltfRuntime;
  89752. };
  89753. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  89754. var buffer = gltfRuntime.buffers[id];
  89755. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  89756. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  89757. }
  89758. else {
  89759. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  89760. if (request) {
  89761. onError(request.status + " " + request.statusText);
  89762. }
  89763. });
  89764. }
  89765. };
  89766. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  89767. var texture = gltfRuntime.textures[id];
  89768. if (!texture || !texture.source) {
  89769. onError("");
  89770. return;
  89771. }
  89772. if (texture.babylonTexture) {
  89773. onSuccess(null);
  89774. return;
  89775. }
  89776. var source = gltfRuntime.images[texture.source];
  89777. if (BABYLON.Tools.IsBase64(source.uri)) {
  89778. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  89779. }
  89780. else {
  89781. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  89782. if (request) {
  89783. onError(request.status + " " + request.statusText);
  89784. }
  89785. });
  89786. }
  89787. };
  89788. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  89789. var texture = gltfRuntime.textures[id];
  89790. if (texture.babylonTexture) {
  89791. onSuccess(texture.babylonTexture);
  89792. return;
  89793. }
  89794. var sampler = gltfRuntime.samplers[texture.sampler];
  89795. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  89796. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  89797. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  89798. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  89799. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  89800. var blob = new Blob([buffer]);
  89801. var blobURL = URL.createObjectURL(blob);
  89802. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  89803. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  89804. if (sampler.wrapS !== undefined) {
  89805. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  89806. }
  89807. if (sampler.wrapT !== undefined) {
  89808. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  89809. }
  89810. newTexture.name = id;
  89811. texture.babylonTexture = newTexture;
  89812. onSuccess(newTexture);
  89813. };
  89814. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  89815. var shader = gltfRuntime.shaders[id];
  89816. if (BABYLON.Tools.IsBase64(shader.uri)) {
  89817. var shaderString = atob(shader.uri.split(",")[1]);
  89818. onSuccess(shaderString);
  89819. }
  89820. else {
  89821. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  89822. if (request) {
  89823. onError(request.status + " " + request.statusText);
  89824. }
  89825. });
  89826. }
  89827. };
  89828. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  89829. var material = gltfRuntime.materials[id];
  89830. if (!material.technique) {
  89831. if (onError) {
  89832. onError("No technique found.");
  89833. }
  89834. return;
  89835. }
  89836. var technique = gltfRuntime.techniques[material.technique];
  89837. if (!technique) {
  89838. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  89839. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  89840. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  89841. onSuccess(defaultMaterial);
  89842. return;
  89843. }
  89844. var program = gltfRuntime.programs[technique.program];
  89845. var states = technique.states;
  89846. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  89847. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  89848. var newVertexShader = "";
  89849. var newPixelShader = "";
  89850. var vertexTokenizer = new Tokenizer(vertexShader);
  89851. var pixelTokenizer = new Tokenizer(pixelShader);
  89852. var unTreatedUniforms = {};
  89853. var uniforms = [];
  89854. var attributes = [];
  89855. var samplers = [];
  89856. // Fill uniform, sampler2D and attributes
  89857. for (var unif in technique.uniforms) {
  89858. var uniform = technique.uniforms[unif];
  89859. var uniformParameter = technique.parameters[uniform];
  89860. unTreatedUniforms[unif] = uniformParameter;
  89861. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  89862. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  89863. if (transformIndex !== -1) {
  89864. uniforms.push(babylonTransforms[transformIndex]);
  89865. delete unTreatedUniforms[unif];
  89866. }
  89867. else {
  89868. uniforms.push(unif);
  89869. }
  89870. }
  89871. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  89872. samplers.push(unif);
  89873. }
  89874. else {
  89875. uniforms.push(unif);
  89876. }
  89877. }
  89878. for (var attr in technique.attributes) {
  89879. var attribute = technique.attributes[attr];
  89880. var attributeParameter = technique.parameters[attribute];
  89881. if (attributeParameter.semantic) {
  89882. attributes.push(getAttribute(attributeParameter));
  89883. }
  89884. }
  89885. // Configure vertex shader
  89886. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  89887. var tokenType = vertexTokenizer.currentToken;
  89888. if (tokenType !== ETokenType.IDENTIFIER) {
  89889. newVertexShader += vertexTokenizer.currentString;
  89890. continue;
  89891. }
  89892. var foundAttribute = false;
  89893. for (var attr in technique.attributes) {
  89894. var attribute = technique.attributes[attr];
  89895. var attributeParameter = technique.parameters[attribute];
  89896. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  89897. newVertexShader += getAttribute(attributeParameter);
  89898. foundAttribute = true;
  89899. break;
  89900. }
  89901. }
  89902. if (foundAttribute) {
  89903. continue;
  89904. }
  89905. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  89906. }
  89907. // Configure pixel shader
  89908. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  89909. var tokenType = pixelTokenizer.currentToken;
  89910. if (tokenType !== ETokenType.IDENTIFIER) {
  89911. newPixelShader += pixelTokenizer.currentString;
  89912. continue;
  89913. }
  89914. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  89915. }
  89916. // Create shader material
  89917. var shaderPath = {
  89918. vertex: program.vertexShader + id,
  89919. fragment: program.fragmentShader + id
  89920. };
  89921. var options = {
  89922. attributes: attributes,
  89923. uniforms: uniforms,
  89924. samplers: samplers,
  89925. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  89926. };
  89927. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  89928. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  89929. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  89930. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  89931. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  89932. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  89933. if (states && states.functions) {
  89934. var functions = states.functions;
  89935. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  89936. shaderMaterial.backFaceCulling = false;
  89937. }
  89938. var blendFunc = functions.blendFuncSeparate;
  89939. if (blendFunc) {
  89940. 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) {
  89941. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  89942. }
  89943. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89944. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  89945. }
  89946. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89947. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  89948. }
  89949. 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) {
  89950. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  89951. }
  89952. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89953. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  89954. }
  89955. 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) {
  89956. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  89957. }
  89958. }
  89959. }
  89960. };
  89961. return GLTFLoaderBase;
  89962. }());
  89963. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  89964. /**
  89965. * glTF V1 Loader
  89966. */
  89967. var GLTFLoader = /** @class */ (function () {
  89968. function GLTFLoader() {
  89969. // #region Stubs for IGLTFLoader interface
  89970. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  89971. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  89972. this.compileMaterials = false;
  89973. this.useClipPlane = false;
  89974. this.compileShadowGenerators = false;
  89975. this.onDisposeObservable = new BABYLON.Observable();
  89976. this.onMeshLoadedObservable = new BABYLON.Observable();
  89977. this.onTextureLoadedObservable = new BABYLON.Observable();
  89978. this.onMaterialLoadedObservable = new BABYLON.Observable();
  89979. this.onCompleteObservable = new BABYLON.Observable();
  89980. this.onExtensionLoadedObservable = new BABYLON.Observable();
  89981. this.state = null;
  89982. }
  89983. GLTFLoader.RegisterExtension = function (extension) {
  89984. if (GLTFLoader.Extensions[extension.name]) {
  89985. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  89986. return;
  89987. }
  89988. GLTFLoader.Extensions[extension.name] = extension;
  89989. };
  89990. GLTFLoader.prototype.dispose = function () { };
  89991. // #endregion
  89992. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  89993. var _this = this;
  89994. scene.useRightHandedSystem = true;
  89995. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  89996. gltfRuntime.importOnlyMeshes = true;
  89997. if (meshesNames === "") {
  89998. gltfRuntime.importMeshesNames = [];
  89999. }
  90000. else if (typeof meshesNames === "string") {
  90001. gltfRuntime.importMeshesNames = [meshesNames];
  90002. }
  90003. else if (meshesNames && !(meshesNames instanceof Array)) {
  90004. gltfRuntime.importMeshesNames = [meshesNames];
  90005. }
  90006. else {
  90007. gltfRuntime.importMeshesNames = [];
  90008. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  90009. }
  90010. // Create nodes
  90011. _this._createNodes(gltfRuntime);
  90012. var meshes = new Array();
  90013. var skeletons = new Array();
  90014. // Fill arrays of meshes and skeletons
  90015. for (var nde in gltfRuntime.nodes) {
  90016. var node = gltfRuntime.nodes[nde];
  90017. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  90018. meshes.push(node.babylonNode);
  90019. }
  90020. }
  90021. for (var skl in gltfRuntime.skins) {
  90022. var skin = gltfRuntime.skins[skl];
  90023. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  90024. skeletons.push(skin.babylonSkeleton);
  90025. }
  90026. }
  90027. // Load buffers, shaders, materials, etc.
  90028. _this._loadBuffersAsync(gltfRuntime, function () {
  90029. _this._loadShadersAsync(gltfRuntime, function () {
  90030. importMaterials(gltfRuntime);
  90031. postLoad(gltfRuntime);
  90032. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  90033. onSuccess(meshes, [], skeletons);
  90034. }
  90035. });
  90036. }, onProgress);
  90037. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  90038. onSuccess(meshes, [], skeletons);
  90039. }
  90040. }, onError);
  90041. return true;
  90042. };
  90043. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  90044. var _this = this;
  90045. return new Promise(function (resolve, reject) {
  90046. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  90047. resolve({
  90048. meshes: meshes,
  90049. particleSystems: particleSystems,
  90050. skeletons: skeletons
  90051. });
  90052. }, onProgress, function (message) {
  90053. reject(new Error(message));
  90054. });
  90055. });
  90056. };
  90057. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  90058. var _this = this;
  90059. scene.useRightHandedSystem = true;
  90060. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  90061. // Load runtime extensios
  90062. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  90063. // Create nodes
  90064. _this._createNodes(gltfRuntime);
  90065. // Load buffers, shaders, materials, etc.
  90066. _this._loadBuffersAsync(gltfRuntime, function () {
  90067. _this._loadShadersAsync(gltfRuntime, function () {
  90068. importMaterials(gltfRuntime);
  90069. postLoad(gltfRuntime);
  90070. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  90071. onSuccess();
  90072. }
  90073. });
  90074. });
  90075. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  90076. onSuccess();
  90077. }
  90078. }, onError);
  90079. }, onError);
  90080. };
  90081. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  90082. var _this = this;
  90083. return new Promise(function (resolve, reject) {
  90084. _this._loadAsync(scene, data, rootUrl, function () {
  90085. resolve();
  90086. }, onProgress, function (message) {
  90087. reject(new Error(message));
  90088. });
  90089. });
  90090. };
  90091. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  90092. var hasShaders = false;
  90093. var processShader = function (sha, shader) {
  90094. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  90095. gltfRuntime.loadedShaderCount++;
  90096. if (shaderString) {
  90097. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  90098. }
  90099. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  90100. onload();
  90101. }
  90102. }, function () {
  90103. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  90104. });
  90105. };
  90106. for (var sha in gltfRuntime.shaders) {
  90107. hasShaders = true;
  90108. var shader = gltfRuntime.shaders[sha];
  90109. if (shader) {
  90110. processShader.bind(this, sha, shader)();
  90111. }
  90112. else {
  90113. BABYLON.Tools.Error("No shader named: " + sha);
  90114. }
  90115. }
  90116. if (!hasShaders) {
  90117. onload();
  90118. }
  90119. };
  90120. ;
  90121. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  90122. var hasBuffers = false;
  90123. var processBuffer = function (buf, buffer) {
  90124. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  90125. gltfRuntime.loadedBufferCount++;
  90126. if (bufferView) {
  90127. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  90128. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  90129. }
  90130. gltfRuntime.loadedBufferViews[buf] = bufferView;
  90131. }
  90132. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  90133. onLoad();
  90134. }
  90135. }, function () {
  90136. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  90137. });
  90138. };
  90139. for (var buf in gltfRuntime.buffers) {
  90140. hasBuffers = true;
  90141. var buffer = gltfRuntime.buffers[buf];
  90142. if (buffer) {
  90143. processBuffer.bind(this, buf, buffer)();
  90144. }
  90145. else {
  90146. BABYLON.Tools.Error("No buffer named: " + buf);
  90147. }
  90148. }
  90149. if (!hasBuffers) {
  90150. onLoad();
  90151. }
  90152. };
  90153. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  90154. var currentScene = gltfRuntime.currentScene;
  90155. if (currentScene) {
  90156. // Only one scene even if multiple scenes are defined
  90157. for (var i = 0; i < currentScene.nodes.length; i++) {
  90158. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90159. }
  90160. }
  90161. else {
  90162. // Load all scenes
  90163. for (var thing in gltfRuntime.scenes) {
  90164. currentScene = gltfRuntime.scenes[thing];
  90165. for (var i = 0; i < currentScene.nodes.length; i++) {
  90166. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90167. }
  90168. }
  90169. }
  90170. };
  90171. GLTFLoader.Extensions = {};
  90172. return GLTFLoader;
  90173. }());
  90174. GLTF1.GLTFLoader = GLTFLoader;
  90175. ;
  90176. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  90177. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90178. })(BABYLON || (BABYLON = {}));
  90179. //# sourceMappingURL=babylon.glTFLoader.js.map
  90180. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90181. var BABYLON;
  90182. (function (BABYLON) {
  90183. var GLTF1;
  90184. (function (GLTF1) {
  90185. /**
  90186. * Utils functions for GLTF
  90187. */
  90188. var GLTFUtils = /** @class */ (function () {
  90189. function GLTFUtils() {
  90190. }
  90191. /**
  90192. * Sets the given "parameter" matrix
  90193. * @param scene: the {BABYLON.Scene} object
  90194. * @param source: the source node where to pick the matrix
  90195. * @param parameter: the GLTF technique parameter
  90196. * @param uniformName: the name of the shader's uniform
  90197. * @param shaderMaterial: the shader material
  90198. */
  90199. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  90200. var mat = null;
  90201. if (parameter.semantic === "MODEL") {
  90202. mat = source.getWorldMatrix();
  90203. }
  90204. else if (parameter.semantic === "PROJECTION") {
  90205. mat = scene.getProjectionMatrix();
  90206. }
  90207. else if (parameter.semantic === "VIEW") {
  90208. mat = scene.getViewMatrix();
  90209. }
  90210. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  90211. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  90212. }
  90213. else if (parameter.semantic === "MODELVIEW") {
  90214. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  90215. }
  90216. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  90217. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  90218. }
  90219. else if (parameter.semantic === "MODELINVERSE") {
  90220. mat = source.getWorldMatrix().invert();
  90221. }
  90222. else if (parameter.semantic === "VIEWINVERSE") {
  90223. mat = scene.getViewMatrix().invert();
  90224. }
  90225. else if (parameter.semantic === "PROJECTIONINVERSE") {
  90226. mat = scene.getProjectionMatrix().invert();
  90227. }
  90228. else if (parameter.semantic === "MODELVIEWINVERSE") {
  90229. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  90230. }
  90231. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  90232. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  90233. }
  90234. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  90235. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  90236. }
  90237. else {
  90238. debugger;
  90239. }
  90240. if (mat) {
  90241. switch (parameter.type) {
  90242. case GLTF1.EParameterType.FLOAT_MAT2:
  90243. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  90244. break;
  90245. case GLTF1.EParameterType.FLOAT_MAT3:
  90246. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  90247. break;
  90248. case GLTF1.EParameterType.FLOAT_MAT4:
  90249. shaderMaterial.setMatrix(uniformName, mat);
  90250. break;
  90251. default: break;
  90252. }
  90253. }
  90254. };
  90255. /**
  90256. * Sets the given "parameter" matrix
  90257. * @param shaderMaterial: the shader material
  90258. * @param uniform: the name of the shader's uniform
  90259. * @param value: the value of the uniform
  90260. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  90261. */
  90262. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  90263. switch (type) {
  90264. case GLTF1.EParameterType.FLOAT:
  90265. shaderMaterial.setFloat(uniform, value);
  90266. return true;
  90267. case GLTF1.EParameterType.FLOAT_VEC2:
  90268. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  90269. return true;
  90270. case GLTF1.EParameterType.FLOAT_VEC3:
  90271. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  90272. return true;
  90273. case GLTF1.EParameterType.FLOAT_VEC4:
  90274. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  90275. return true;
  90276. default: return false;
  90277. }
  90278. };
  90279. /**
  90280. * Returns the wrap mode of the texture
  90281. * @param mode: the mode value
  90282. */
  90283. GLTFUtils.GetWrapMode = function (mode) {
  90284. switch (mode) {
  90285. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  90286. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  90287. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90288. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90289. }
  90290. };
  90291. /**
  90292. * Returns the byte stride giving an accessor
  90293. * @param accessor: the GLTF accessor objet
  90294. */
  90295. GLTFUtils.GetByteStrideFromType = function (accessor) {
  90296. // Needs this function since "byteStride" isn't requiered in glTF format
  90297. var type = accessor.type;
  90298. switch (type) {
  90299. case "VEC2": return 2;
  90300. case "VEC3": return 3;
  90301. case "VEC4": return 4;
  90302. case "MAT2": return 4;
  90303. case "MAT3": return 9;
  90304. case "MAT4": return 16;
  90305. default: return 1;
  90306. }
  90307. };
  90308. /**
  90309. * Returns the texture filter mode giving a mode value
  90310. * @param mode: the filter mode value
  90311. */
  90312. GLTFUtils.GetTextureFilterMode = function (mode) {
  90313. switch (mode) {
  90314. case GLTF1.ETextureFilterType.LINEAR:
  90315. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  90316. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90317. case GLTF1.ETextureFilterType.NEAREST:
  90318. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  90319. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  90320. }
  90321. };
  90322. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  90323. var byteOffset = bufferView.byteOffset + byteOffset;
  90324. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  90325. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  90326. throw new Error("Buffer access is out of range");
  90327. }
  90328. var buffer = loadedBufferView.buffer;
  90329. byteOffset += loadedBufferView.byteOffset;
  90330. switch (componentType) {
  90331. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  90332. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  90333. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  90334. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  90335. default: return new Float32Array(buffer, byteOffset, byteLength);
  90336. }
  90337. };
  90338. /**
  90339. * Returns a buffer from its accessor
  90340. * @param gltfRuntime: the GLTF runtime
  90341. * @param accessor: the GLTF accessor
  90342. */
  90343. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  90344. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  90345. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  90346. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  90347. };
  90348. /**
  90349. * Decodes a buffer view into a string
  90350. * @param view: the buffer view
  90351. */
  90352. GLTFUtils.DecodeBufferToText = function (view) {
  90353. var result = "";
  90354. var length = view.byteLength;
  90355. for (var i = 0; i < length; ++i) {
  90356. result += String.fromCharCode(view[i]);
  90357. }
  90358. return result;
  90359. };
  90360. /**
  90361. * Returns the default material of gltf. Related to
  90362. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  90363. * @param scene: the Babylon.js scene
  90364. */
  90365. GLTFUtils.GetDefaultMaterial = function (scene) {
  90366. if (!GLTFUtils._DefaultMaterial) {
  90367. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  90368. "precision highp float;",
  90369. "",
  90370. "uniform mat4 worldView;",
  90371. "uniform mat4 projection;",
  90372. "",
  90373. "attribute vec3 position;",
  90374. "",
  90375. "void main(void)",
  90376. "{",
  90377. " gl_Position = projection * worldView * vec4(position, 1.0);",
  90378. "}"
  90379. ].join("\n");
  90380. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  90381. "precision highp float;",
  90382. "",
  90383. "uniform vec4 u_emission;",
  90384. "",
  90385. "void main(void)",
  90386. "{",
  90387. " gl_FragColor = u_emission;",
  90388. "}"
  90389. ].join("\n");
  90390. var shaderPath = {
  90391. vertex: "GLTFDefaultMaterial",
  90392. fragment: "GLTFDefaultMaterial"
  90393. };
  90394. var options = {
  90395. attributes: ["position"],
  90396. uniforms: ["worldView", "projection", "u_emission"],
  90397. samplers: new Array(),
  90398. needAlphaBlending: false
  90399. };
  90400. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  90401. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  90402. }
  90403. return GLTFUtils._DefaultMaterial;
  90404. };
  90405. // The GLTF default material
  90406. GLTFUtils._DefaultMaterial = null;
  90407. return GLTFUtils;
  90408. }());
  90409. GLTF1.GLTFUtils = GLTFUtils;
  90410. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90411. })(BABYLON || (BABYLON = {}));
  90412. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  90413. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90414. var BABYLON;
  90415. (function (BABYLON) {
  90416. var GLTF1;
  90417. (function (GLTF1) {
  90418. var GLTFLoaderExtension = /** @class */ (function () {
  90419. function GLTFLoaderExtension(name) {
  90420. this._name = name;
  90421. }
  90422. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  90423. get: function () {
  90424. return this._name;
  90425. },
  90426. enumerable: true,
  90427. configurable: true
  90428. });
  90429. /**
  90430. * Defines an override for loading the runtime
  90431. * Return true to stop further extensions from loading the runtime
  90432. */
  90433. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90434. return false;
  90435. };
  90436. /**
  90437. * Defines an onverride for creating gltf runtime
  90438. * Return true to stop further extensions from creating the runtime
  90439. */
  90440. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90441. return false;
  90442. };
  90443. /**
  90444. * Defines an override for loading buffers
  90445. * Return true to stop further extensions from loading this buffer
  90446. */
  90447. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90448. return false;
  90449. };
  90450. /**
  90451. * Defines an override for loading texture buffers
  90452. * Return true to stop further extensions from loading this texture data
  90453. */
  90454. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90455. return false;
  90456. };
  90457. /**
  90458. * Defines an override for creating textures
  90459. * Return true to stop further extensions from loading this texture
  90460. */
  90461. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90462. return false;
  90463. };
  90464. /**
  90465. * Defines an override for loading shader strings
  90466. * Return true to stop further extensions from loading this shader data
  90467. */
  90468. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90469. return false;
  90470. };
  90471. /**
  90472. * Defines an override for loading materials
  90473. * Return true to stop further extensions from loading this material
  90474. */
  90475. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90476. return false;
  90477. };
  90478. // ---------
  90479. // Utilities
  90480. // ---------
  90481. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90482. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90483. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  90484. }, function () {
  90485. setTimeout(function () {
  90486. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90487. });
  90488. });
  90489. };
  90490. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90491. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90492. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  90493. }, function () {
  90494. setTimeout(function () {
  90495. onSuccess();
  90496. });
  90497. });
  90498. };
  90499. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90500. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90501. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90502. }, function () {
  90503. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90504. });
  90505. };
  90506. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  90507. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  90508. };
  90509. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90510. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90511. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90512. }, function () {
  90513. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90514. });
  90515. };
  90516. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90517. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90518. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90519. }, function () {
  90520. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90521. });
  90522. };
  90523. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90524. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90525. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90526. }, function () {
  90527. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90528. });
  90529. };
  90530. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90531. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90532. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90533. }, function () {
  90534. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90535. });
  90536. };
  90537. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  90538. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  90539. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  90540. if (func(loaderExtension)) {
  90541. return;
  90542. }
  90543. }
  90544. defaultFunc();
  90545. };
  90546. return GLTFLoaderExtension;
  90547. }());
  90548. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  90549. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90550. })(BABYLON || (BABYLON = {}));
  90551. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  90552. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90553. var BABYLON;
  90554. (function (BABYLON) {
  90555. var GLTF1;
  90556. (function (GLTF1) {
  90557. var BinaryExtensionBufferName = "binary_glTF";
  90558. ;
  90559. ;
  90560. var GLTFBinaryExtension = /** @class */ (function (_super) {
  90561. __extends(GLTFBinaryExtension, _super);
  90562. function GLTFBinaryExtension() {
  90563. return _super.call(this, "KHR_binary_glTF") || this;
  90564. }
  90565. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90566. var extensionsUsed = data.json.extensionsUsed;
  90567. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  90568. return false;
  90569. }
  90570. this._bin = data.bin;
  90571. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90572. return true;
  90573. };
  90574. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90575. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  90576. return false;
  90577. }
  90578. if (id !== BinaryExtensionBufferName) {
  90579. return false;
  90580. }
  90581. onSuccess(this._bin);
  90582. return true;
  90583. };
  90584. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90585. var texture = gltfRuntime.textures[id];
  90586. var source = gltfRuntime.images[texture.source];
  90587. if (!source.extensions || !(this.name in source.extensions)) {
  90588. return false;
  90589. }
  90590. var sourceExt = source.extensions[this.name];
  90591. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  90592. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90593. onSuccess(buffer);
  90594. return true;
  90595. };
  90596. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90597. var shader = gltfRuntime.shaders[id];
  90598. if (!shader.extensions || !(this.name in shader.extensions)) {
  90599. return false;
  90600. }
  90601. var binaryExtensionShader = shader.extensions[this.name];
  90602. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  90603. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90604. setTimeout(function () {
  90605. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  90606. onSuccess(shaderString);
  90607. });
  90608. return true;
  90609. };
  90610. return GLTFBinaryExtension;
  90611. }(GLTF1.GLTFLoaderExtension));
  90612. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  90613. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  90614. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90615. })(BABYLON || (BABYLON = {}));
  90616. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  90617. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90618. var BABYLON;
  90619. (function (BABYLON) {
  90620. var GLTF1;
  90621. (function (GLTF1) {
  90622. ;
  90623. ;
  90624. ;
  90625. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  90626. __extends(GLTFMaterialsCommonExtension, _super);
  90627. function GLTFMaterialsCommonExtension() {
  90628. return _super.call(this, "KHR_materials_common") || this;
  90629. }
  90630. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90631. if (!gltfRuntime.extensions)
  90632. return false;
  90633. var extension = gltfRuntime.extensions[this.name];
  90634. if (!extension)
  90635. return false;
  90636. // Create lights
  90637. var lights = extension.lights;
  90638. if (lights) {
  90639. for (var thing in lights) {
  90640. var light = lights[thing];
  90641. switch (light.type) {
  90642. case "ambient":
  90643. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  90644. var ambient = light.ambient;
  90645. if (ambient) {
  90646. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  90647. }
  90648. break;
  90649. case "point":
  90650. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  90651. var point = light.point;
  90652. if (point) {
  90653. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  90654. }
  90655. break;
  90656. case "directional":
  90657. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  90658. var directional = light.directional;
  90659. if (directional) {
  90660. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  90661. }
  90662. break;
  90663. case "spot":
  90664. var spot = light.spot;
  90665. if (spot) {
  90666. 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);
  90667. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  90668. }
  90669. break;
  90670. default:
  90671. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  90672. break;
  90673. }
  90674. }
  90675. }
  90676. return false;
  90677. };
  90678. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90679. var material = gltfRuntime.materials[id];
  90680. if (!material || !material.extensions)
  90681. return false;
  90682. var extension = material.extensions[this.name];
  90683. if (!extension)
  90684. return false;
  90685. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  90686. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  90687. if (extension.technique === "CONSTANT") {
  90688. standardMaterial.disableLighting = true;
  90689. }
  90690. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  90691. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  90692. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  90693. // Ambient
  90694. if (typeof extension.values.ambient === "string") {
  90695. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  90696. }
  90697. else {
  90698. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  90699. }
  90700. // Diffuse
  90701. if (typeof extension.values.diffuse === "string") {
  90702. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  90703. }
  90704. else {
  90705. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  90706. }
  90707. // Emission
  90708. if (typeof extension.values.emission === "string") {
  90709. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  90710. }
  90711. else {
  90712. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  90713. }
  90714. // Specular
  90715. if (typeof extension.values.specular === "string") {
  90716. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  90717. }
  90718. else {
  90719. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  90720. }
  90721. return true;
  90722. };
  90723. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  90724. // Create buffer from texture url
  90725. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  90726. // Create texture from buffer
  90727. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  90728. }, onError);
  90729. };
  90730. return GLTFMaterialsCommonExtension;
  90731. }(GLTF1.GLTFLoaderExtension));
  90732. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  90733. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  90734. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90735. })(BABYLON || (BABYLON = {}));
  90736. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  90737. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90738. var BABYLON;
  90739. (function (BABYLON) {
  90740. var GLTF2;
  90741. (function (GLTF2) {
  90742. var ArrayItem = /** @class */ (function () {
  90743. function ArrayItem() {
  90744. }
  90745. ArrayItem.Assign = function (values) {
  90746. if (values) {
  90747. for (var index = 0; index < values.length; index++) {
  90748. values[index]._index = index;
  90749. }
  90750. }
  90751. };
  90752. return ArrayItem;
  90753. }());
  90754. GLTF2.ArrayItem = ArrayItem;
  90755. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  90756. })(BABYLON || (BABYLON = {}));
  90757. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  90758. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90759. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  90760. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90761. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90762. var BABYLON;
  90763. (function (BABYLON) {
  90764. var GLTF2;
  90765. (function (GLTF2) {
  90766. var GLTFLoader = /** @class */ (function () {
  90767. function GLTFLoader() {
  90768. this._completePromises = new Array();
  90769. this._disposed = false;
  90770. this._state = null;
  90771. this._extensions = {};
  90772. this._defaultSampler = {};
  90773. this._requests = new Array();
  90774. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  90775. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  90776. this.compileMaterials = false;
  90777. this.useClipPlane = false;
  90778. this.compileShadowGenerators = false;
  90779. this.onDisposeObservable = new BABYLON.Observable();
  90780. this.onMeshLoadedObservable = new BABYLON.Observable();
  90781. this.onTextureLoadedObservable = new BABYLON.Observable();
  90782. this.onMaterialLoadedObservable = new BABYLON.Observable();
  90783. this.onExtensionLoadedObservable = new BABYLON.Observable();
  90784. this.onCompleteObservable = new BABYLON.Observable();
  90785. }
  90786. GLTFLoader._Register = function (name, factory) {
  90787. if (GLTFLoader._Factories[name]) {
  90788. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  90789. return;
  90790. }
  90791. GLTFLoader._Factories[name] = factory;
  90792. // Keep the order of registration so that extensions registered first are called first.
  90793. GLTFLoader._Names.push(name);
  90794. };
  90795. Object.defineProperty(GLTFLoader.prototype, "state", {
  90796. get: function () {
  90797. return this._state;
  90798. },
  90799. enumerable: true,
  90800. configurable: true
  90801. });
  90802. GLTFLoader.prototype.dispose = function () {
  90803. if (this._disposed) {
  90804. return;
  90805. }
  90806. this._disposed = true;
  90807. this.onDisposeObservable.notifyObservers(this);
  90808. this.onDisposeObservable.clear();
  90809. this._clear();
  90810. };
  90811. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  90812. var _this = this;
  90813. return Promise.resolve().then(function () {
  90814. var nodes = null;
  90815. if (meshesNames) {
  90816. var nodeMap_1 = {};
  90817. if (_this._gltf.nodes) {
  90818. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  90819. var node = _a[_i];
  90820. if (node.name) {
  90821. nodeMap_1[node.name] = node;
  90822. }
  90823. }
  90824. }
  90825. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  90826. nodes = names.map(function (name) {
  90827. var node = nodeMap_1[name];
  90828. if (!node) {
  90829. throw new Error("Failed to find node " + name);
  90830. }
  90831. return node;
  90832. });
  90833. }
  90834. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  90835. return {
  90836. meshes: _this._getMeshes(),
  90837. particleSystems: [],
  90838. skeletons: _this._getSkeletons(),
  90839. };
  90840. });
  90841. });
  90842. };
  90843. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  90844. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  90845. };
  90846. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  90847. var _this = this;
  90848. return Promise.resolve().then(function () {
  90849. _this._loadExtensions();
  90850. _this._babylonScene = scene;
  90851. _this._rootUrl = rootUrl;
  90852. _this._progressCallback = onProgress;
  90853. _this._state = BABYLON.GLTFLoaderState.Loading;
  90854. _this._loadData(data);
  90855. var promises = new Array();
  90856. if (nodes) {
  90857. promises.push(_this._loadNodesAsync(nodes));
  90858. }
  90859. else {
  90860. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  90861. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  90862. }
  90863. if (_this.compileMaterials) {
  90864. promises.push(_this._compileMaterialsAsync());
  90865. }
  90866. if (_this.compileShadowGenerators) {
  90867. promises.push(_this._compileShadowGeneratorsAsync());
  90868. }
  90869. return Promise.all(promises).then(function () {
  90870. _this._state = BABYLON.GLTFLoaderState.Ready;
  90871. _this._startAnimations();
  90872. BABYLON.Tools.SetImmediate(function () {
  90873. if (!_this._disposed) {
  90874. Promise.all(_this._completePromises).then(function () {
  90875. _this._state = BABYLON.GLTFLoaderState.Complete;
  90876. _this.onCompleteObservable.notifyObservers(_this);
  90877. _this.onCompleteObservable.clear();
  90878. _this._clear();
  90879. }).catch(function (error) {
  90880. BABYLON.Tools.Error("glTF Loader: " + error.message);
  90881. _this._clear();
  90882. });
  90883. }
  90884. });
  90885. });
  90886. }).catch(function (error) {
  90887. BABYLON.Tools.Error("glTF Loader: " + error.message);
  90888. _this._clear();
  90889. throw error;
  90890. });
  90891. };
  90892. GLTFLoader.prototype._loadExtensions = function () {
  90893. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  90894. var name_1 = _a[_i];
  90895. var extension = GLTFLoader._Factories[name_1](this);
  90896. this._extensions[name_1] = extension;
  90897. this.onExtensionLoadedObservable.notifyObservers(extension);
  90898. }
  90899. this.onExtensionLoadedObservable.clear();
  90900. };
  90901. GLTFLoader.prototype._loadData = function (data) {
  90902. this._gltf = data.json;
  90903. this._setupData();
  90904. if (data.bin) {
  90905. var buffers = this._gltf.buffers;
  90906. if (buffers && buffers[0] && !buffers[0].uri) {
  90907. var binaryBuffer = buffers[0];
  90908. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  90909. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  90910. }
  90911. binaryBuffer._data = Promise.resolve(data.bin);
  90912. }
  90913. else {
  90914. BABYLON.Tools.Warn("Unexpected BIN chunk");
  90915. }
  90916. }
  90917. };
  90918. GLTFLoader.prototype._setupData = function () {
  90919. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  90920. GLTF2.ArrayItem.Assign(this._gltf.animations);
  90921. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  90922. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  90923. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  90924. GLTF2.ArrayItem.Assign(this._gltf.images);
  90925. GLTF2.ArrayItem.Assign(this._gltf.materials);
  90926. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  90927. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  90928. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  90929. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  90930. GLTF2.ArrayItem.Assign(this._gltf.skins);
  90931. GLTF2.ArrayItem.Assign(this._gltf.textures);
  90932. if (this._gltf.nodes) {
  90933. var nodeParents = {};
  90934. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  90935. var node = _a[_i];
  90936. if (node.children) {
  90937. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  90938. var index = _c[_b];
  90939. nodeParents[index] = node._index;
  90940. }
  90941. }
  90942. }
  90943. var rootNode = this._createRootNode();
  90944. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  90945. var node = _e[_d];
  90946. var parentIndex = nodeParents[node._index];
  90947. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  90948. }
  90949. }
  90950. };
  90951. GLTFLoader.prototype._createRootNode = function () {
  90952. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  90953. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  90954. switch (this.coordinateSystemMode) {
  90955. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  90956. if (!this._babylonScene.useRightHandedSystem) {
  90957. rootNode.rotation = [0, 1, 0, 0];
  90958. rootNode.scale = [1, 1, -1];
  90959. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  90960. }
  90961. break;
  90962. }
  90963. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  90964. this._babylonScene.useRightHandedSystem = true;
  90965. break;
  90966. }
  90967. default: {
  90968. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  90969. }
  90970. }
  90971. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  90972. return rootNode;
  90973. };
  90974. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  90975. var promises = new Array();
  90976. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  90977. var node = nodes_1[_i];
  90978. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  90979. }
  90980. promises.push(this._loadAnimationsAsync());
  90981. return Promise.all(promises).then(function () { });
  90982. };
  90983. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  90984. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  90985. if (promise) {
  90986. return promise;
  90987. }
  90988. var promises = new Array();
  90989. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  90990. var index = _a[_i];
  90991. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  90992. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  90993. }
  90994. promises.push(this._loadAnimationsAsync());
  90995. return Promise.all(promises).then(function () { });
  90996. };
  90997. GLTFLoader.prototype._getMeshes = function () {
  90998. var meshes = new Array();
  90999. // Root mesh is always first.
  91000. meshes.push(this._rootBabylonMesh);
  91001. var nodes = this._gltf.nodes;
  91002. if (nodes) {
  91003. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  91004. var node = nodes_2[_i];
  91005. if (node._babylonMesh) {
  91006. meshes.push(node._babylonMesh);
  91007. }
  91008. }
  91009. }
  91010. return meshes;
  91011. };
  91012. GLTFLoader.prototype._getSkeletons = function () {
  91013. var skeletons = new Array();
  91014. var skins = this._gltf.skins;
  91015. if (skins) {
  91016. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  91017. var skin = skins_1[_i];
  91018. if (skin._babylonSkeleton) {
  91019. skeletons.push(skin._babylonSkeleton);
  91020. }
  91021. }
  91022. }
  91023. return skeletons;
  91024. };
  91025. GLTFLoader.prototype._startAnimations = function () {
  91026. var animations = this._gltf.animations;
  91027. if (!animations) {
  91028. return;
  91029. }
  91030. switch (this.animationStartMode) {
  91031. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  91032. // do nothing
  91033. break;
  91034. }
  91035. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  91036. var animation = animations[0];
  91037. animation._babylonAnimationGroup.start(true);
  91038. break;
  91039. }
  91040. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  91041. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  91042. var animation = animations_1[_i];
  91043. animation._babylonAnimationGroup.start(true);
  91044. }
  91045. break;
  91046. }
  91047. default: {
  91048. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  91049. return;
  91050. }
  91051. }
  91052. };
  91053. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  91054. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  91055. if (promise) {
  91056. return promise;
  91057. }
  91058. if (node._babylonMesh) {
  91059. throw new Error(context + ": Invalid recursive node hierarchy");
  91060. }
  91061. var promises = new Array();
  91062. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  91063. node._babylonMesh = babylonMesh;
  91064. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  91065. node._babylonAnimationTargets.push(babylonMesh);
  91066. GLTFLoader._LoadTransform(node, babylonMesh);
  91067. if (node.mesh != undefined) {
  91068. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  91069. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  91070. }
  91071. if (node.children) {
  91072. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  91073. var index = _a[_i];
  91074. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  91075. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  91076. }
  91077. }
  91078. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  91079. return Promise.all(promises).then(function () { });
  91080. };
  91081. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  91082. // TODO: instancing
  91083. var promises = new Array();
  91084. var primitives = mesh.primitives;
  91085. if (!primitives || primitives.length === 0) {
  91086. throw new Error(context + ": Primitives are missing");
  91087. }
  91088. GLTF2.ArrayItem.Assign(primitives);
  91089. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  91090. var primitive = primitives_1[_i];
  91091. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  91092. }
  91093. if (node.skin != undefined) {
  91094. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  91095. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  91096. }
  91097. return Promise.all(promises).then(function () {
  91098. if (node._primitiveBabylonMeshes) {
  91099. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91100. var primitiveBabylonMesh = _a[_i];
  91101. primitiveBabylonMesh._refreshBoundingInfo(true);
  91102. }
  91103. }
  91104. });
  91105. };
  91106. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  91107. var _this = this;
  91108. var promises = new Array();
  91109. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  91110. babylonMesh.setEnabled(false);
  91111. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  91112. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  91113. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  91114. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  91115. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  91116. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  91117. }));
  91118. if (primitive.material == undefined) {
  91119. babylonMesh.material = this._getDefaultMaterial();
  91120. }
  91121. else {
  91122. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  91123. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  91124. }
  91125. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  91126. return Promise.all(promises).then(function () {
  91127. babylonMesh.setEnabled(true);
  91128. });
  91129. };
  91130. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  91131. var _this = this;
  91132. var attributes = primitive.attributes;
  91133. if (!attributes) {
  91134. throw new Error(context + ": Attributes are missing");
  91135. }
  91136. if (primitive.mode && primitive.mode !== 4 /* TRIANGLES */) {
  91137. // TODO: handle other primitive modes
  91138. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  91139. }
  91140. var promises = new Array();
  91141. var babylonVertexData = new BABYLON.VertexData();
  91142. if (primitive.indices == undefined) {
  91143. var positionAccessorIndex = attributes["POSITION"];
  91144. if (positionAccessorIndex != undefined) {
  91145. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  91146. babylonVertexData.indices = new Uint32Array(accessor.count);
  91147. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  91148. babylonVertexData.indices[i] = i;
  91149. }
  91150. }
  91151. }
  91152. else {
  91153. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  91154. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  91155. babylonVertexData.indices = data;
  91156. }));
  91157. }
  91158. var loadAttribute = function (attribute, kind) {
  91159. if (attributes[attribute] == undefined) {
  91160. return;
  91161. }
  91162. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  91163. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  91164. babylonMesh._delayInfo.push(kind);
  91165. }
  91166. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  91167. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91168. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  91169. if (attribute === "COLOR_0") {
  91170. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  91171. babylonMesh.hasVertexAlpha = true;
  91172. if (accessor.type === "VEC3") {
  91173. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  91174. }
  91175. }
  91176. babylonVertexData.set(attributeData, kind);
  91177. }));
  91178. };
  91179. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  91180. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  91181. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  91182. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  91183. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  91184. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  91185. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  91186. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  91187. return Promise.all(promises).then(function () {
  91188. return babylonVertexData;
  91189. });
  91190. };
  91191. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  91192. if (!primitive.targets) {
  91193. return;
  91194. }
  91195. if (node._numMorphTargets == undefined) {
  91196. node._numMorphTargets = primitive.targets.length;
  91197. }
  91198. else if (primitive.targets.length !== node._numMorphTargets) {
  91199. throw new Error(context + ": Primitives do not have the same number of targets");
  91200. }
  91201. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  91202. for (var index = 0; index < primitive.targets.length; index++) {
  91203. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  91204. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  91205. // TODO: tell the target whether it has positions, normals, tangents
  91206. }
  91207. };
  91208. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  91209. if (!primitive.targets) {
  91210. return Promise.resolve();
  91211. }
  91212. var promises = new Array();
  91213. var morphTargetManager = babylonMesh.morphTargetManager;
  91214. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  91215. var babylonMorphTarget = morphTargetManager.getTarget(index);
  91216. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  91217. }
  91218. return Promise.all(promises).then(function () { });
  91219. };
  91220. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  91221. var _this = this;
  91222. var promises = new Array();
  91223. var loadAttribute = function (attribute, setData) {
  91224. if (attributes[attribute] == undefined) {
  91225. return;
  91226. }
  91227. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  91228. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91229. setData(data);
  91230. }));
  91231. };
  91232. loadAttribute("POSITION", function (data) {
  91233. if (babylonVertexData.positions) {
  91234. for (var i = 0; i < data.length; i++) {
  91235. data[i] += babylonVertexData.positions[i];
  91236. }
  91237. babylonMorphTarget.setPositions(data);
  91238. }
  91239. });
  91240. loadAttribute("NORMAL", function (data) {
  91241. if (babylonVertexData.normals) {
  91242. for (var i = 0; i < data.length; i++) {
  91243. data[i] += babylonVertexData.normals[i];
  91244. }
  91245. babylonMorphTarget.setNormals(data);
  91246. }
  91247. });
  91248. loadAttribute("TANGENT", function (data) {
  91249. if (babylonVertexData.tangents) {
  91250. // Tangent data for morph targets is stored as xyz delta.
  91251. // The vertexData.tangent is stored as xyzw.
  91252. // So we need to skip every fourth vertexData.tangent.
  91253. for (var i = 0, j = 0; i < data.length; i++) {
  91254. data[i] += babylonVertexData.tangents[j++];
  91255. if ((i + 1) % 3 == 0) {
  91256. j++;
  91257. }
  91258. }
  91259. babylonMorphTarget.setTangents(data);
  91260. }
  91261. });
  91262. return Promise.all(promises).then(function () { });
  91263. };
  91264. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  91265. if (accessor.componentType == 5126 /* FLOAT */) {
  91266. return data;
  91267. }
  91268. var factor = 1;
  91269. if (accessor.normalized) {
  91270. switch (accessor.componentType) {
  91271. case 5121 /* UNSIGNED_BYTE */: {
  91272. factor = 1 / 255;
  91273. break;
  91274. }
  91275. case 5123 /* UNSIGNED_SHORT */: {
  91276. factor = 1 / 65535;
  91277. break;
  91278. }
  91279. default: {
  91280. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91281. }
  91282. }
  91283. }
  91284. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  91285. for (var i = 0; i < result.length; i++) {
  91286. result[i] = data[i] * factor;
  91287. }
  91288. return result;
  91289. };
  91290. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  91291. var result = new Float32Array(data.length / 3 * 4);
  91292. var offset = 0;
  91293. for (var i = 0; i < result.length; i++) {
  91294. if ((i + 1) % 4 === 0) {
  91295. result[i] = 1;
  91296. }
  91297. else {
  91298. result[i] = data[offset++];
  91299. }
  91300. }
  91301. return result;
  91302. };
  91303. GLTFLoader._LoadTransform = function (node, babylonNode) {
  91304. var position = BABYLON.Vector3.Zero();
  91305. var rotation = BABYLON.Quaternion.Identity();
  91306. var scaling = BABYLON.Vector3.One();
  91307. if (node.matrix) {
  91308. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  91309. matrix.decompose(scaling, rotation, position);
  91310. }
  91311. else {
  91312. if (node.translation)
  91313. position = BABYLON.Vector3.FromArray(node.translation);
  91314. if (node.rotation)
  91315. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  91316. if (node.scale)
  91317. scaling = BABYLON.Vector3.FromArray(node.scale);
  91318. }
  91319. babylonNode.position = position;
  91320. babylonNode.rotationQuaternion = rotation;
  91321. babylonNode.scaling = scaling;
  91322. };
  91323. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  91324. var _this = this;
  91325. var assignSkeleton = function () {
  91326. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91327. var babylonMesh = _a[_i];
  91328. babylonMesh.skeleton = skin._babylonSkeleton;
  91329. }
  91330. node._babylonMesh.parent = _this._rootBabylonMesh;
  91331. node._babylonMesh.position = BABYLON.Vector3.Zero();
  91332. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  91333. node._babylonMesh.scaling = BABYLON.Vector3.One();
  91334. };
  91335. if (skin._loaded) {
  91336. assignSkeleton();
  91337. return skin._loaded;
  91338. }
  91339. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  91340. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  91341. var skeletonId = "skeleton" + skin._index;
  91342. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  91343. skin._babylonSkeleton = babylonSkeleton;
  91344. _this._loadBones(context, skin, inverseBindMatricesData);
  91345. assignSkeleton();
  91346. }));
  91347. };
  91348. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  91349. if (skin.inverseBindMatrices == undefined) {
  91350. return Promise.resolve(null);
  91351. }
  91352. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  91353. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91354. return data;
  91355. });
  91356. };
  91357. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  91358. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  91359. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  91360. node._babylonAnimationTargets.push(babylonBone);
  91361. return babylonBone;
  91362. };
  91363. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  91364. var babylonBones = {};
  91365. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  91366. var index = _a[_i];
  91367. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  91368. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  91369. }
  91370. };
  91371. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  91372. var babylonBone = babylonBones[node._index];
  91373. if (babylonBone) {
  91374. return babylonBone;
  91375. }
  91376. var boneIndex = skin.joints.indexOf(node._index);
  91377. var baseMatrix = BABYLON.Matrix.Identity();
  91378. if (inverseBindMatricesData && boneIndex !== -1) {
  91379. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  91380. baseMatrix.invertToRef(baseMatrix);
  91381. }
  91382. var babylonParentBone = null;
  91383. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  91384. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  91385. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  91386. }
  91387. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  91388. babylonBones[node._index] = babylonBone;
  91389. return babylonBone;
  91390. };
  91391. GLTFLoader.prototype._getNodeMatrix = function (node) {
  91392. return node.matrix ?
  91393. BABYLON.Matrix.FromArray(node.matrix) :
  91394. 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());
  91395. };
  91396. GLTFLoader.prototype._loadAnimationsAsync = function () {
  91397. var animations = this._gltf.animations;
  91398. if (!animations) {
  91399. return Promise.resolve();
  91400. }
  91401. var promises = new Array();
  91402. for (var index = 0; index < animations.length; index++) {
  91403. var animation = animations[index];
  91404. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  91405. }
  91406. return Promise.all(promises).then(function () { });
  91407. };
  91408. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  91409. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  91410. animation._babylonAnimationGroup = babylonAnimationGroup;
  91411. var promises = new Array();
  91412. GLTF2.ArrayItem.Assign(animation.channels);
  91413. GLTF2.ArrayItem.Assign(animation.samplers);
  91414. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  91415. var channel = _a[_i];
  91416. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  91417. }
  91418. return Promise.all(promises).then(function () {
  91419. babylonAnimationGroup.normalize();
  91420. });
  91421. };
  91422. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  91423. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  91424. if (!targetNode._babylonMesh) {
  91425. return Promise.resolve();
  91426. }
  91427. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  91428. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  91429. var targetPath;
  91430. var animationType;
  91431. switch (channel.target.path) {
  91432. case "translation" /* TRANSLATION */: {
  91433. targetPath = "position";
  91434. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91435. break;
  91436. }
  91437. case "rotation" /* ROTATION */: {
  91438. targetPath = "rotationQuaternion";
  91439. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  91440. break;
  91441. }
  91442. case "scale" /* SCALE */: {
  91443. targetPath = "scaling";
  91444. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91445. break;
  91446. }
  91447. case "weights" /* WEIGHTS */: {
  91448. targetPath = "influence";
  91449. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  91450. break;
  91451. }
  91452. default: {
  91453. throw new Error(context + ": Invalid target path " + channel.target.path);
  91454. }
  91455. }
  91456. var outputBufferOffset = 0;
  91457. var getNextOutputValue;
  91458. switch (targetPath) {
  91459. case "position": {
  91460. getNextOutputValue = function () {
  91461. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91462. outputBufferOffset += 3;
  91463. return value;
  91464. };
  91465. break;
  91466. }
  91467. case "rotationQuaternion": {
  91468. getNextOutputValue = function () {
  91469. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  91470. outputBufferOffset += 4;
  91471. return value;
  91472. };
  91473. break;
  91474. }
  91475. case "scaling": {
  91476. getNextOutputValue = function () {
  91477. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91478. outputBufferOffset += 3;
  91479. return value;
  91480. };
  91481. break;
  91482. }
  91483. case "influence": {
  91484. getNextOutputValue = function () {
  91485. var value = new Array(targetNode._numMorphTargets);
  91486. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  91487. value[i] = data.output[outputBufferOffset++];
  91488. }
  91489. return value;
  91490. };
  91491. break;
  91492. }
  91493. }
  91494. var getNextKey;
  91495. switch (data.interpolation) {
  91496. case "STEP" /* STEP */: {
  91497. getNextKey = function (frameIndex) { return ({
  91498. frame: data.input[frameIndex],
  91499. value: getNextOutputValue(),
  91500. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  91501. }); };
  91502. break;
  91503. }
  91504. case "LINEAR" /* LINEAR */: {
  91505. getNextKey = function (frameIndex) { return ({
  91506. frame: data.input[frameIndex],
  91507. value: getNextOutputValue()
  91508. }); };
  91509. break;
  91510. }
  91511. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91512. getNextKey = function (frameIndex) { return ({
  91513. frame: data.input[frameIndex],
  91514. inTangent: getNextOutputValue(),
  91515. value: getNextOutputValue(),
  91516. outTangent: getNextOutputValue()
  91517. }); };
  91518. break;
  91519. }
  91520. }
  91521. var keys;
  91522. if (data.input.length === 1) {
  91523. var key = getNextKey(0);
  91524. keys = [
  91525. { frame: key.frame, value: key.value },
  91526. { frame: key.frame + 1, value: key.value }
  91527. ];
  91528. }
  91529. else {
  91530. keys = new Array(data.input.length);
  91531. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  91532. keys[frameIndex] = getNextKey(frameIndex);
  91533. }
  91534. }
  91535. if (targetPath === "influence") {
  91536. var _loop_1 = function (targetIndex) {
  91537. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91538. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91539. babylonAnimation.setKeys(keys.map(function (key) { return ({
  91540. frame: key.frame,
  91541. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  91542. value: key.value[targetIndex],
  91543. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  91544. }); }));
  91545. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91546. var babylonMesh = _a[_i];
  91547. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  91548. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  91549. }
  91550. };
  91551. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  91552. _loop_1(targetIndex);
  91553. }
  91554. }
  91555. else {
  91556. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91557. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91558. babylonAnimation.setKeys(keys);
  91559. if (targetNode._babylonAnimationTargets) {
  91560. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  91561. var target = _a[_i];
  91562. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  91563. }
  91564. }
  91565. }
  91566. });
  91567. };
  91568. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  91569. if (sampler._data) {
  91570. return sampler._data;
  91571. }
  91572. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  91573. switch (interpolation) {
  91574. case "STEP" /* STEP */:
  91575. case "LINEAR" /* LINEAR */:
  91576. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91577. break;
  91578. }
  91579. default: {
  91580. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  91581. }
  91582. }
  91583. var inputData;
  91584. var outputData;
  91585. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  91586. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  91587. sampler._data = Promise.all([
  91588. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  91589. inputData = data;
  91590. }),
  91591. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  91592. outputData = data;
  91593. })
  91594. ]).then(function () {
  91595. return {
  91596. input: inputData,
  91597. interpolation: interpolation,
  91598. output: outputData,
  91599. };
  91600. });
  91601. return sampler._data;
  91602. };
  91603. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  91604. if (buffer._data) {
  91605. return buffer._data;
  91606. }
  91607. if (!buffer.uri) {
  91608. throw new Error(context + ": Uri is missing");
  91609. }
  91610. buffer._data = this._loadUriAsync(context, buffer.uri);
  91611. return buffer._data;
  91612. };
  91613. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  91614. if (bufferView._data) {
  91615. return bufferView._data;
  91616. }
  91617. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  91618. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  91619. try {
  91620. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  91621. }
  91622. catch (e) {
  91623. throw new Error(context + ": " + e.message);
  91624. }
  91625. });
  91626. return bufferView._data;
  91627. };
  91628. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  91629. var _this = this;
  91630. if (accessor.sparse) {
  91631. throw new Error(context + ": Sparse accessors are not currently supported");
  91632. }
  91633. if (accessor._data) {
  91634. return accessor._data;
  91635. }
  91636. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  91637. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  91638. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  91639. var byteOffset = accessor.byteOffset || 0;
  91640. var byteStride = bufferView.byteStride;
  91641. if (byteStride === 0) {
  91642. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  91643. }
  91644. try {
  91645. switch (accessor.componentType) {
  91646. case 5120 /* BYTE */: {
  91647. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91648. }
  91649. case 5121 /* UNSIGNED_BYTE */: {
  91650. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91651. }
  91652. case 5122 /* SHORT */: {
  91653. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91654. }
  91655. case 5123 /* UNSIGNED_SHORT */: {
  91656. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91657. }
  91658. case 5125 /* UNSIGNED_INT */: {
  91659. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91660. }
  91661. case 5126 /* FLOAT */: {
  91662. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91663. }
  91664. default: {
  91665. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91666. }
  91667. }
  91668. }
  91669. catch (e) {
  91670. throw new Error(context + ": " + e);
  91671. }
  91672. });
  91673. return accessor._data;
  91674. };
  91675. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  91676. byteOffset += data.byteOffset;
  91677. var targetLength = count * numComponents;
  91678. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  91679. return new typedArray(data.buffer, byteOffset, targetLength);
  91680. }
  91681. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  91682. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  91683. var targetBuffer = new typedArray(targetLength);
  91684. var sourceIndex = 0;
  91685. var targetIndex = 0;
  91686. while (targetIndex < targetLength) {
  91687. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  91688. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  91689. targetIndex++;
  91690. }
  91691. sourceIndex += elementStride;
  91692. }
  91693. return targetBuffer;
  91694. };
  91695. GLTFLoader.prototype._getDefaultMaterial = function () {
  91696. var id = "__gltf_default";
  91697. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  91698. if (!babylonMaterial) {
  91699. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  91700. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  91701. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91702. babylonMaterial.metallic = 1;
  91703. babylonMaterial.roughness = 1;
  91704. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91705. }
  91706. return babylonMaterial;
  91707. };
  91708. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  91709. var promises = new Array();
  91710. var babylonMaterial = material._babylonMaterial;
  91711. // Ensure metallic workflow
  91712. babylonMaterial.metallic = 1;
  91713. babylonMaterial.roughness = 1;
  91714. var properties = material.pbrMetallicRoughness;
  91715. if (properties) {
  91716. if (properties.baseColorFactor) {
  91717. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  91718. babylonMaterial.alpha = properties.baseColorFactor[3];
  91719. }
  91720. else {
  91721. babylonMaterial.albedoColor = BABYLON.Color3.White();
  91722. }
  91723. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  91724. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  91725. if (properties.baseColorTexture) {
  91726. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  91727. babylonMaterial.albedoTexture = texture;
  91728. }));
  91729. }
  91730. if (properties.metallicRoughnessTexture) {
  91731. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  91732. babylonMaterial.metallicTexture = texture;
  91733. }));
  91734. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  91735. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  91736. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  91737. }
  91738. }
  91739. this._loadMaterialAlphaProperties(context, material);
  91740. return Promise.all(promises).then(function () { });
  91741. };
  91742. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  91743. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  91744. if (promise) {
  91745. return promise;
  91746. }
  91747. material._babylonMeshes = material._babylonMeshes || [];
  91748. material._babylonMeshes.push(babylonMesh);
  91749. if (material._loaded) {
  91750. babylonMesh.material = material._babylonMaterial;
  91751. return material._loaded;
  91752. }
  91753. var promises = new Array();
  91754. var babylonMaterial = this._createMaterial(material);
  91755. material._babylonMaterial = babylonMaterial;
  91756. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  91757. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  91758. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91759. babylonMesh.material = babylonMaterial;
  91760. return (material._loaded = Promise.all(promises).then(function () { }));
  91761. };
  91762. GLTFLoader.prototype._createMaterial = function (material) {
  91763. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  91764. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91765. return babylonMaterial;
  91766. };
  91767. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  91768. var promises = new Array();
  91769. var babylonMaterial = material._babylonMaterial;
  91770. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  91771. if (material.doubleSided) {
  91772. babylonMaterial.backFaceCulling = false;
  91773. babylonMaterial.twoSidedLighting = true;
  91774. }
  91775. if (material.normalTexture) {
  91776. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  91777. babylonMaterial.bumpTexture = texture;
  91778. }));
  91779. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  91780. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  91781. if (material.normalTexture.scale != undefined) {
  91782. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  91783. }
  91784. }
  91785. if (material.occlusionTexture) {
  91786. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  91787. babylonMaterial.ambientTexture = texture;
  91788. }));
  91789. babylonMaterial.useAmbientInGrayScale = true;
  91790. if (material.occlusionTexture.strength != undefined) {
  91791. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  91792. }
  91793. }
  91794. if (material.emissiveTexture) {
  91795. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  91796. babylonMaterial.emissiveTexture = texture;
  91797. }));
  91798. }
  91799. return Promise.all(promises).then(function () { });
  91800. };
  91801. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  91802. var babylonMaterial = material._babylonMaterial;
  91803. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  91804. switch (alphaMode) {
  91805. case "OPAQUE" /* OPAQUE */: {
  91806. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  91807. break;
  91808. }
  91809. case "MASK" /* MASK */: {
  91810. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  91811. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  91812. if (babylonMaterial.alpha) {
  91813. if (babylonMaterial.alpha === 0) {
  91814. babylonMaterial.alphaCutOff = 1;
  91815. }
  91816. else {
  91817. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  91818. }
  91819. babylonMaterial.alpha = 1;
  91820. }
  91821. if (babylonMaterial.albedoTexture) {
  91822. babylonMaterial.albedoTexture.hasAlpha = true;
  91823. }
  91824. break;
  91825. }
  91826. case "BLEND" /* BLEND */: {
  91827. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  91828. if (babylonMaterial.albedoTexture) {
  91829. babylonMaterial.albedoTexture.hasAlpha = true;
  91830. babylonMaterial.useAlphaFromAlbedoTexture = true;
  91831. }
  91832. break;
  91833. }
  91834. default: {
  91835. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  91836. }
  91837. }
  91838. };
  91839. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  91840. var _this = this;
  91841. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  91842. context = "#/textures/" + textureInfo.index;
  91843. var promises = new Array();
  91844. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  91845. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  91846. var deferred = new BABYLON.Deferred();
  91847. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  91848. if (!_this._disposed) {
  91849. deferred.resolve();
  91850. }
  91851. }, function (message, exception) {
  91852. if (!_this._disposed) {
  91853. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  91854. }
  91855. });
  91856. promises.push(deferred.promise);
  91857. babylonTexture.name = texture.name || "texture" + texture._index;
  91858. babylonTexture.wrapU = samplerData.wrapU;
  91859. babylonTexture.wrapV = samplerData.wrapV;
  91860. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  91861. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  91862. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  91863. babylonTexture.updateURL(objectURL);
  91864. }));
  91865. assign(babylonTexture);
  91866. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  91867. return Promise.all(promises).then(function () { });
  91868. };
  91869. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  91870. if (!sampler._data) {
  91871. sampler._data = {
  91872. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  91873. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  91874. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  91875. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  91876. };
  91877. }
  91878. ;
  91879. return sampler._data;
  91880. };
  91881. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  91882. if (image._objectURL) {
  91883. return image._objectURL;
  91884. }
  91885. var promise;
  91886. if (image.uri) {
  91887. promise = this._loadUriAsync(context, image.uri);
  91888. }
  91889. else {
  91890. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  91891. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  91892. }
  91893. image._objectURL = promise.then(function (data) {
  91894. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  91895. });
  91896. return image._objectURL;
  91897. };
  91898. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  91899. var _this = this;
  91900. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  91901. if (promise) {
  91902. return promise;
  91903. }
  91904. if (!GLTFLoader._ValidateUri(uri)) {
  91905. throw new Error(context + ": Uri '" + uri + "' is invalid");
  91906. }
  91907. if (BABYLON.Tools.IsBase64(uri)) {
  91908. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  91909. }
  91910. return new Promise(function (resolve, reject) {
  91911. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  91912. if (!_this._disposed) {
  91913. resolve(new Uint8Array(data));
  91914. }
  91915. }, function (event) {
  91916. if (!_this._disposed) {
  91917. try {
  91918. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  91919. request._lengthComputable = event.lengthComputable;
  91920. request._loaded = event.loaded;
  91921. request._total = event.total;
  91922. _this._onProgress();
  91923. }
  91924. }
  91925. catch (e) {
  91926. reject(e);
  91927. }
  91928. }
  91929. }, _this._babylonScene.database, true, function (request, exception) {
  91930. if (!_this._disposed) {
  91931. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  91932. }
  91933. });
  91934. _this._requests.push(request);
  91935. });
  91936. };
  91937. GLTFLoader.prototype._onProgress = function () {
  91938. if (!this._progressCallback) {
  91939. return;
  91940. }
  91941. var lengthComputable = true;
  91942. var loaded = 0;
  91943. var total = 0;
  91944. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  91945. var request = _a[_i];
  91946. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  91947. return;
  91948. }
  91949. lengthComputable = lengthComputable && request._lengthComputable;
  91950. loaded += request._loaded;
  91951. total += request._total;
  91952. }
  91953. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  91954. };
  91955. GLTFLoader._GetProperty = function (context, array, index) {
  91956. if (!array || index == undefined || !array[index]) {
  91957. throw new Error(context + ": Failed to find index " + index);
  91958. }
  91959. return array[index];
  91960. };
  91961. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  91962. // Set defaults if undefined
  91963. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  91964. switch (mode) {
  91965. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  91966. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  91967. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91968. default:
  91969. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  91970. return BABYLON.Texture.WRAP_ADDRESSMODE;
  91971. }
  91972. };
  91973. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  91974. // Set defaults if undefined
  91975. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  91976. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  91977. if (magFilter === 9729 /* LINEAR */) {
  91978. switch (minFilter) {
  91979. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  91980. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  91981. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  91982. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  91983. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  91984. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  91985. default:
  91986. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  91987. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  91988. }
  91989. }
  91990. else {
  91991. if (magFilter !== 9728 /* NEAREST */) {
  91992. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  91993. }
  91994. switch (minFilter) {
  91995. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  91996. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  91997. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  91998. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  91999. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  92000. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  92001. default:
  92002. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  92003. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  92004. }
  92005. }
  92006. };
  92007. GLTFLoader._GetNumComponents = function (context, type) {
  92008. switch (type) {
  92009. case "SCALAR": return 1;
  92010. case "VEC2": return 2;
  92011. case "VEC3": return 3;
  92012. case "VEC4": return 4;
  92013. case "MAT2": return 4;
  92014. case "MAT3": return 9;
  92015. case "MAT4": return 16;
  92016. }
  92017. throw new Error(context + ": Invalid type " + type);
  92018. };
  92019. GLTFLoader._ValidateUri = function (uri) {
  92020. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  92021. };
  92022. GLTFLoader.prototype._compileMaterialsAsync = function () {
  92023. var promises = new Array();
  92024. if (this._gltf.materials) {
  92025. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  92026. var material = _a[_i];
  92027. var babylonMaterial = material._babylonMaterial;
  92028. var babylonMeshes = material._babylonMeshes;
  92029. if (babylonMaterial && babylonMeshes) {
  92030. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  92031. var babylonMesh = babylonMeshes_1[_b];
  92032. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  92033. if (this.useClipPlane) {
  92034. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  92035. }
  92036. }
  92037. }
  92038. }
  92039. }
  92040. return Promise.all(promises).then(function () { });
  92041. };
  92042. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  92043. var promises = new Array();
  92044. var lights = this._babylonScene.lights;
  92045. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  92046. var light = lights_1[_i];
  92047. var generator = light.getShadowGenerator();
  92048. if (generator) {
  92049. promises.push(generator.forceCompilationAsync());
  92050. }
  92051. }
  92052. return Promise.all(promises).then(function () { });
  92053. };
  92054. GLTFLoader.prototype._clear = function () {
  92055. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  92056. var request = _a[_i];
  92057. request.abort();
  92058. }
  92059. this._requests.length = 0;
  92060. if (this._gltf && this._gltf.images) {
  92061. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  92062. var image = _c[_b];
  92063. if (image._objectURL) {
  92064. image._objectURL.then(function (value) {
  92065. URL.revokeObjectURL(value);
  92066. });
  92067. image._objectURL = undefined;
  92068. }
  92069. }
  92070. }
  92071. delete this._gltf;
  92072. delete this._babylonScene;
  92073. this._completePromises.length = 0;
  92074. this._extensions = {};
  92075. delete this._rootBabylonMesh;
  92076. delete this._progressCallback;
  92077. this.onMeshLoadedObservable.clear();
  92078. this.onTextureLoadedObservable.clear();
  92079. this.onMaterialLoadedObservable.clear();
  92080. };
  92081. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  92082. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  92083. var name_2 = _a[_i];
  92084. var extension = this._extensions[name_2];
  92085. if (extension.enabled) {
  92086. var promise = actionAsync(extension);
  92087. if (promise) {
  92088. return promise;
  92089. }
  92090. }
  92091. }
  92092. return null;
  92093. };
  92094. GLTFLoader._Names = new Array();
  92095. GLTFLoader._Factories = {};
  92096. return GLTFLoader;
  92097. }());
  92098. GLTF2.GLTFLoader = GLTFLoader;
  92099. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  92100. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92101. })(BABYLON || (BABYLON = {}));
  92102. //# sourceMappingURL=babylon.glTFLoader.js.map
  92103. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92104. var BABYLON;
  92105. (function (BABYLON) {
  92106. var GLTF2;
  92107. (function (GLTF2) {
  92108. var GLTFLoaderExtension = /** @class */ (function () {
  92109. function GLTFLoaderExtension(loader) {
  92110. this.enabled = true;
  92111. this._loader = loader;
  92112. }
  92113. // #region Overridable Methods
  92114. /** Override this method to modify the default behavior for loading scenes. */
  92115. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  92116. /** Override this method to modify the default behavior for loading nodes. */
  92117. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  92118. /** Override this method to modify the default behavior for loading materials. */
  92119. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  92120. /** Override this method to modify the default behavior for loading uris. */
  92121. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  92122. // #endregion
  92123. /** Helper method called by a loader extension to load an glTF extension. */
  92124. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  92125. var _this = this;
  92126. if (!property.extensions) {
  92127. return null;
  92128. }
  92129. var extensions = property.extensions;
  92130. var extension = extensions[this.name];
  92131. if (!extension) {
  92132. return null;
  92133. }
  92134. // Clear out the extension before executing the action to avoid recursing into the same property.
  92135. delete extensions[this.name];
  92136. return actionAsync(context + "/extensions/" + this.name, extension).then(function () {
  92137. // Restore the extension after completing the action.
  92138. extensions[_this.name] = extension;
  92139. });
  92140. };
  92141. /** Helper method called by the loader to allow extensions to override loading scenes. */
  92142. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  92143. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  92144. };
  92145. /** Helper method called by the loader to allow extensions to override loading nodes. */
  92146. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  92147. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  92148. };
  92149. /** Helper method called by the loader to allow extensions to override loading materials. */
  92150. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  92151. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  92152. };
  92153. /** Helper method called by the loader to allow extensions to override loading uris. */
  92154. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  92155. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  92156. };
  92157. return GLTFLoaderExtension;
  92158. }());
  92159. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  92160. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92161. })(BABYLON || (BABYLON = {}));
  92162. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  92163. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92164. var BABYLON;
  92165. (function (BABYLON) {
  92166. var GLTF2;
  92167. (function (GLTF2) {
  92168. var Extensions;
  92169. (function (Extensions) {
  92170. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  92171. var NAME = "MSFT_lod";
  92172. var MSFT_lod = /** @class */ (function (_super) {
  92173. __extends(MSFT_lod, _super);
  92174. function MSFT_lod() {
  92175. var _this = _super !== null && _super.apply(this, arguments) || this;
  92176. _this.name = NAME;
  92177. /**
  92178. * Maximum number of LODs to load, starting from the lowest LOD.
  92179. */
  92180. _this.maxLODsToLoad = Number.MAX_VALUE;
  92181. _this._loadingNodeLOD = null;
  92182. _this._loadNodeSignals = {};
  92183. _this._loadingMaterialLOD = null;
  92184. _this._loadMaterialSignals = {};
  92185. return _this;
  92186. }
  92187. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  92188. var _this = this;
  92189. return this._loadExtensionAsync(context, node, function (context, extension) {
  92190. var firstPromise;
  92191. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  92192. var _loop_1 = function (indexLOD) {
  92193. var nodeLOD = nodeLODs[indexLOD];
  92194. if (indexLOD !== 0) {
  92195. _this._loadingNodeLOD = nodeLOD;
  92196. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  92197. }
  92198. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  92199. if (indexLOD !== 0) {
  92200. var previousNodeLOD = nodeLODs[indexLOD - 1];
  92201. previousNodeLOD._babylonMesh.setEnabled(false);
  92202. }
  92203. if (indexLOD !== nodeLODs.length - 1) {
  92204. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  92205. _this._loadNodeSignals[nodeIndex].resolve();
  92206. delete _this._loadNodeSignals[nodeIndex];
  92207. }
  92208. });
  92209. if (indexLOD === 0) {
  92210. firstPromise = promise;
  92211. }
  92212. else {
  92213. _this._loader._completePromises.push(promise);
  92214. _this._loadingNodeLOD = null;
  92215. }
  92216. };
  92217. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  92218. _loop_1(indexLOD);
  92219. }
  92220. return firstPromise;
  92221. });
  92222. };
  92223. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  92224. var _this = this;
  92225. // Don't load material LODs if already loading a node LOD.
  92226. if (this._loadingNodeLOD) {
  92227. return null;
  92228. }
  92229. return this._loadExtensionAsync(context, material, function (context, extension) {
  92230. var firstPromise;
  92231. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  92232. var _loop_2 = function (indexLOD) {
  92233. var materialLOD = materialLODs[indexLOD];
  92234. if (indexLOD !== 0) {
  92235. _this._loadingMaterialLOD = materialLOD;
  92236. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  92237. }
  92238. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  92239. if (indexLOD !== materialLODs.length - 1) {
  92240. var materialIndex = materialLODs[indexLOD + 1]._index;
  92241. _this._loadMaterialSignals[materialIndex].resolve();
  92242. delete _this._loadMaterialSignals[materialIndex];
  92243. }
  92244. });
  92245. if (indexLOD === 0) {
  92246. firstPromise = promise;
  92247. }
  92248. else {
  92249. _this._loader._completePromises.push(promise);
  92250. _this._loadingMaterialLOD = null;
  92251. }
  92252. };
  92253. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  92254. _loop_2(indexLOD);
  92255. }
  92256. return firstPromise;
  92257. });
  92258. };
  92259. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  92260. var _this = this;
  92261. // Defer the loading of uris if loading a material or node LOD.
  92262. if (this._loadingMaterialLOD) {
  92263. var index = this._loadingMaterialLOD._index;
  92264. return this._loadMaterialSignals[index].promise.then(function () {
  92265. return _this._loader._loadUriAsync(context, uri);
  92266. });
  92267. }
  92268. else if (this._loadingNodeLOD) {
  92269. var index = this._loadingNodeLOD._index;
  92270. return this._loadNodeSignals[index].promise.then(function () {
  92271. return _this._loader._loadUriAsync(context, uri);
  92272. });
  92273. }
  92274. return null;
  92275. };
  92276. /**
  92277. * Gets an array of LOD properties from lowest to highest.
  92278. */
  92279. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  92280. if (this.maxLODsToLoad <= 0) {
  92281. throw new Error("maxLODsToLoad must be greater than zero");
  92282. }
  92283. var properties = new Array();
  92284. for (var i = ids.length - 1; i >= 0; i--) {
  92285. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  92286. if (properties.length === this.maxLODsToLoad) {
  92287. return properties;
  92288. }
  92289. }
  92290. properties.push(property);
  92291. return properties;
  92292. };
  92293. return MSFT_lod;
  92294. }(GLTF2.GLTFLoaderExtension));
  92295. Extensions.MSFT_lod = MSFT_lod;
  92296. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  92297. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92298. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92299. })(BABYLON || (BABYLON = {}));
  92300. //# sourceMappingURL=MSFT_lod.js.map
  92301. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92302. var BABYLON;
  92303. (function (BABYLON) {
  92304. var GLTF2;
  92305. (function (GLTF2) {
  92306. var Extensions;
  92307. (function (Extensions) {
  92308. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  92309. var NAME = "KHR_materials_pbrSpecularGlossiness";
  92310. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  92311. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  92312. function KHR_materials_pbrSpecularGlossiness() {
  92313. var _this = _super !== null && _super.apply(this, arguments) || this;
  92314. _this.name = NAME;
  92315. return _this;
  92316. }
  92317. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  92318. var _this = this;
  92319. return this._loadExtensionAsync(context, material, function (context, extension) {
  92320. material._babylonMeshes = material._babylonMeshes || [];
  92321. material._babylonMeshes.push(babylonMesh);
  92322. if (material._loaded) {
  92323. babylonMesh.material = material._babylonMaterial;
  92324. return material._loaded;
  92325. }
  92326. var promises = new Array();
  92327. var babylonMaterial = _this._loader._createMaterial(material);
  92328. material._babylonMaterial = babylonMaterial;
  92329. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  92330. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  92331. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  92332. babylonMesh.material = babylonMaterial;
  92333. return (material._loaded = Promise.all(promises).then(function () { }));
  92334. });
  92335. };
  92336. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  92337. var promises = new Array();
  92338. var babylonMaterial = material._babylonMaterial;
  92339. if (properties.diffuseFactor) {
  92340. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  92341. babylonMaterial.alpha = properties.diffuseFactor[3];
  92342. }
  92343. else {
  92344. babylonMaterial.albedoColor = BABYLON.Color3.White();
  92345. }
  92346. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  92347. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  92348. if (properties.diffuseTexture) {
  92349. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  92350. babylonMaterial.albedoTexture = texture;
  92351. }));
  92352. }
  92353. if (properties.specularGlossinessTexture) {
  92354. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  92355. babylonMaterial.reflectivityTexture = texture;
  92356. }));
  92357. babylonMaterial.reflectivityTexture.hasAlpha = true;
  92358. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  92359. }
  92360. loader._loadMaterialAlphaProperties(context, material);
  92361. return Promise.all(promises).then(function () { });
  92362. };
  92363. return KHR_materials_pbrSpecularGlossiness;
  92364. }(GLTF2.GLTFLoaderExtension));
  92365. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  92366. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  92367. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92368. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92369. })(BABYLON || (BABYLON = {}));
  92370. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  92371. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92372. var BABYLON;
  92373. (function (BABYLON) {
  92374. var GLTF2;
  92375. (function (GLTF2) {
  92376. var Extensions;
  92377. (function (Extensions) {
  92378. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  92379. var NAME = "KHR_lights";
  92380. var LightType;
  92381. (function (LightType) {
  92382. LightType["AMBIENT"] = "ambient";
  92383. LightType["DIRECTIONAL"] = "directional";
  92384. LightType["POINT"] = "point";
  92385. LightType["SPOT"] = "spot";
  92386. })(LightType || (LightType = {}));
  92387. var KHR_lights = /** @class */ (function (_super) {
  92388. __extends(KHR_lights, _super);
  92389. function KHR_lights() {
  92390. var _this = _super !== null && _super.apply(this, arguments) || this;
  92391. _this.name = NAME;
  92392. return _this;
  92393. }
  92394. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  92395. var _this = this;
  92396. return this._loadExtensionAsync(context, scene, function (context, extension) {
  92397. var promise = _this._loader._loadSceneAsync(context, scene);
  92398. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92399. if (light.type !== LightType.AMBIENT) {
  92400. throw new Error(context + ": Only ambient lights are allowed on a scene");
  92401. }
  92402. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  92403. return promise;
  92404. });
  92405. };
  92406. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  92407. var _this = this;
  92408. return this._loadExtensionAsync(context, node, function (context, extension) {
  92409. var promise = _this._loader._loadNodeAsync(context, node);
  92410. var babylonLight;
  92411. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92412. var name = node._babylonMesh.name;
  92413. switch (light.type) {
  92414. case LightType.AMBIENT: {
  92415. throw new Error(context + ": Ambient lights are not allowed on a node");
  92416. }
  92417. case LightType.DIRECTIONAL: {
  92418. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  92419. break;
  92420. }
  92421. case LightType.POINT: {
  92422. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  92423. break;
  92424. }
  92425. case LightType.SPOT: {
  92426. var spotLight = light;
  92427. // TODO: support inner and outer cone angles
  92428. //const innerConeAngle = spotLight.innerConeAngle || 0;
  92429. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  92430. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  92431. break;
  92432. }
  92433. default: {
  92434. throw new Error(context + ": Invalid light type " + light.type);
  92435. }
  92436. }
  92437. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  92438. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  92439. babylonLight.parent = node._babylonMesh;
  92440. return promise;
  92441. });
  92442. };
  92443. Object.defineProperty(KHR_lights.prototype, "_lights", {
  92444. get: function () {
  92445. var extensions = this._loader._gltf.extensions;
  92446. if (!extensions || !extensions[this.name]) {
  92447. throw new Error("#/extensions: " + this.name + " not found");
  92448. }
  92449. var extension = extensions[this.name];
  92450. return extension.lights;
  92451. },
  92452. enumerable: true,
  92453. configurable: true
  92454. });
  92455. return KHR_lights;
  92456. }(GLTF2.GLTFLoaderExtension));
  92457. Extensions.KHR_lights = KHR_lights;
  92458. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  92459. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92460. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92461. })(BABYLON || (BABYLON = {}));
  92462. //# sourceMappingURL=KHR_lights.js.map
  92463. (function universalModuleDefinition(root, factory) {
  92464. var f = factory();
  92465. if (root && root["BABYLON"]) {
  92466. return;
  92467. }
  92468. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92469. globalObject["BABYLON"] = f;
  92470. if(typeof exports === 'object' && typeof module === 'object')
  92471. module.exports = f;
  92472. else if(typeof define === 'function' && define.amd)
  92473. define(["BABYLON"], factory);
  92474. else if(typeof exports === 'object')
  92475. exports["BABYLON"] = f;
  92476. else {
  92477. root["BABYLON"] = f;
  92478. }
  92479. })(this, function() {
  92480. return BABYLON;
  92481. });