babylon.max.js 4.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. //# sourceMappingURL=babylon.types.js.map
  18. var BABYLON;
  19. (function (BABYLON) {
  20. var KeyboardEventTypes = /** @class */ (function () {
  21. function KeyboardEventTypes() {
  22. }
  23. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  24. get: function () {
  25. return KeyboardEventTypes._KEYDOWN;
  26. },
  27. enumerable: true,
  28. configurable: true
  29. });
  30. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  31. get: function () {
  32. return KeyboardEventTypes._KEYUP;
  33. },
  34. enumerable: true,
  35. configurable: true
  36. });
  37. KeyboardEventTypes._KEYDOWN = 0x01;
  38. KeyboardEventTypes._KEYUP = 0x02;
  39. return KeyboardEventTypes;
  40. }());
  41. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  42. var KeyboardInfo = /** @class */ (function () {
  43. function KeyboardInfo(type, event) {
  44. this.type = type;
  45. this.event = event;
  46. }
  47. return KeyboardInfo;
  48. }());
  49. BABYLON.KeyboardInfo = KeyboardInfo;
  50. /**
  51. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  52. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  53. */
  54. var KeyboardInfoPre = /** @class */ (function (_super) {
  55. __extends(KeyboardInfoPre, _super);
  56. function KeyboardInfoPre(type, event) {
  57. var _this = _super.call(this, type, event) || this;
  58. _this.skipOnPointerObservable = false;
  59. return _this;
  60. }
  61. return KeyboardInfoPre;
  62. }(KeyboardInfo));
  63. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  64. })(BABYLON || (BABYLON = {}));
  65. //# sourceMappingURL=babylon.keyboardEvents.js.map
  66. var BABYLON;
  67. (function (BABYLON) {
  68. var PointerEventTypes = /** @class */ (function () {
  69. function PointerEventTypes() {
  70. }
  71. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  72. get: function () {
  73. return PointerEventTypes._POINTERDOWN;
  74. },
  75. enumerable: true,
  76. configurable: true
  77. });
  78. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  79. get: function () {
  80. return PointerEventTypes._POINTERUP;
  81. },
  82. enumerable: true,
  83. configurable: true
  84. });
  85. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  86. get: function () {
  87. return PointerEventTypes._POINTERMOVE;
  88. },
  89. enumerable: true,
  90. configurable: true
  91. });
  92. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  93. get: function () {
  94. return PointerEventTypes._POINTERWHEEL;
  95. },
  96. enumerable: true,
  97. configurable: true
  98. });
  99. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  100. get: function () {
  101. return PointerEventTypes._POINTERPICK;
  102. },
  103. enumerable: true,
  104. configurable: true
  105. });
  106. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  107. get: function () {
  108. return PointerEventTypes._POINTERTAP;
  109. },
  110. enumerable: true,
  111. configurable: true
  112. });
  113. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  114. get: function () {
  115. return PointerEventTypes._POINTERDOUBLETAP;
  116. },
  117. enumerable: true,
  118. configurable: true
  119. });
  120. PointerEventTypes._POINTERDOWN = 0x01;
  121. PointerEventTypes._POINTERUP = 0x02;
  122. PointerEventTypes._POINTERMOVE = 0x04;
  123. PointerEventTypes._POINTERWHEEL = 0x08;
  124. PointerEventTypes._POINTERPICK = 0x10;
  125. PointerEventTypes._POINTERTAP = 0x20;
  126. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  127. return PointerEventTypes;
  128. }());
  129. BABYLON.PointerEventTypes = PointerEventTypes;
  130. var PointerInfoBase = /** @class */ (function () {
  131. function PointerInfoBase(type, event) {
  132. this.type = type;
  133. this.event = event;
  134. }
  135. return PointerInfoBase;
  136. }());
  137. BABYLON.PointerInfoBase = PointerInfoBase;
  138. /**
  139. * This class is used to store pointer related info for the onPrePointerObservable event.
  140. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  141. */
  142. var PointerInfoPre = /** @class */ (function (_super) {
  143. __extends(PointerInfoPre, _super);
  144. function PointerInfoPre(type, event, localX, localY) {
  145. var _this = _super.call(this, type, event) || this;
  146. _this.skipOnPointerObservable = false;
  147. _this.localPosition = new BABYLON.Vector2(localX, localY);
  148. return _this;
  149. }
  150. return PointerInfoPre;
  151. }(PointerInfoBase));
  152. BABYLON.PointerInfoPre = PointerInfoPre;
  153. /**
  154. * This type contains all the data related to a pointer event in Babylon.js.
  155. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  156. */
  157. var PointerInfo = /** @class */ (function (_super) {
  158. __extends(PointerInfo, _super);
  159. function PointerInfo(type, event, pickInfo) {
  160. var _this = _super.call(this, type, event) || this;
  161. _this.pickInfo = pickInfo;
  162. return _this;
  163. }
  164. return PointerInfo;
  165. }(PointerInfoBase));
  166. BABYLON.PointerInfo = PointerInfo;
  167. })(BABYLON || (BABYLON = {}));
  168. //# sourceMappingURL=babylon.pointerEvents.js.map
  169. var BABYLON;
  170. (function (BABYLON) {
  171. BABYLON.ToGammaSpace = 1 / 2.2;
  172. BABYLON.ToLinearSpace = 2.2;
  173. BABYLON.Epsilon = 0.001;
  174. var Color3 = /** @class */ (function () {
  175. /**
  176. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  177. */
  178. function Color3(r, g, b) {
  179. if (r === void 0) { r = 0; }
  180. if (g === void 0) { g = 0; }
  181. if (b === void 0) { b = 0; }
  182. this.r = r;
  183. this.g = g;
  184. this.b = b;
  185. }
  186. /**
  187. * Returns a string with the Color3 current values.
  188. */
  189. Color3.prototype.toString = function () {
  190. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  191. };
  192. /**
  193. * Returns the string "Color3".
  194. */
  195. Color3.prototype.getClassName = function () {
  196. return "Color3";
  197. };
  198. /**
  199. * Returns the Color3 hash code.
  200. */
  201. Color3.prototype.getHashCode = function () {
  202. var hash = this.r || 0;
  203. hash = (hash * 397) ^ (this.g || 0);
  204. hash = (hash * 397) ^ (this.b || 0);
  205. return hash;
  206. };
  207. // Operators
  208. /**
  209. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  210. * Returns the Color3.
  211. */
  212. Color3.prototype.toArray = function (array, index) {
  213. if (index === undefined) {
  214. index = 0;
  215. }
  216. array[index] = this.r;
  217. array[index + 1] = this.g;
  218. array[index + 2] = this.b;
  219. return this;
  220. };
  221. /**
  222. * Returns a new Color4 object from the current Color3 and the passed alpha.
  223. */
  224. Color3.prototype.toColor4 = function (alpha) {
  225. if (alpha === void 0) { alpha = 1; }
  226. return new Color4(this.r, this.g, this.b, alpha);
  227. };
  228. /**
  229. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  230. */
  231. Color3.prototype.asArray = function () {
  232. var result = new Array();
  233. this.toArray(result, 0);
  234. return result;
  235. };
  236. /**
  237. * Returns the luminance value (float).
  238. */
  239. Color3.prototype.toLuminance = function () {
  240. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  241. };
  242. /**
  243. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  244. * Returns this new object.
  245. */
  246. Color3.prototype.multiply = function (otherColor) {
  247. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  248. };
  249. /**
  250. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  251. * Returns the current Color3.
  252. */
  253. Color3.prototype.multiplyToRef = function (otherColor, result) {
  254. result.r = this.r * otherColor.r;
  255. result.g = this.g * otherColor.g;
  256. result.b = this.b * otherColor.b;
  257. return this;
  258. };
  259. /**
  260. * Boolean : True if the rgb values are equal to the passed ones.
  261. */
  262. Color3.prototype.equals = function (otherColor) {
  263. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  264. };
  265. /**
  266. * Boolean : True if the rgb values are equal to the passed ones.
  267. */
  268. Color3.prototype.equalsFloats = function (r, g, b) {
  269. return this.r === r && this.g === g && this.b === b;
  270. };
  271. /**
  272. * Multiplies in place each rgb value by scale.
  273. * Returns the updated Color3.
  274. */
  275. Color3.prototype.scale = function (scale) {
  276. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  277. };
  278. /**
  279. * Multiplies the rgb values by scale and stores the result into "result".
  280. * Returns the unmodified current Color3.
  281. */
  282. Color3.prototype.scaleToRef = function (scale, result) {
  283. result.r = this.r * scale;
  284. result.g = this.g * scale;
  285. result.b = this.b * scale;
  286. return this;
  287. };
  288. /**
  289. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  290. */
  291. Color3.prototype.add = function (otherColor) {
  292. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  293. };
  294. /**
  295. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  296. * Returns the unmodified current Color3.
  297. */
  298. Color3.prototype.addToRef = function (otherColor, result) {
  299. result.r = this.r + otherColor.r;
  300. result.g = this.g + otherColor.g;
  301. result.b = this.b + otherColor.b;
  302. return this;
  303. };
  304. /**
  305. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  306. */
  307. Color3.prototype.subtract = function (otherColor) {
  308. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  309. };
  310. /**
  311. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  312. * Returns the unmodified current Color3.
  313. */
  314. Color3.prototype.subtractToRef = function (otherColor, result) {
  315. result.r = this.r - otherColor.r;
  316. result.g = this.g - otherColor.g;
  317. result.b = this.b - otherColor.b;
  318. return this;
  319. };
  320. /**
  321. * Returns a new Color3 copied the current one.
  322. */
  323. Color3.prototype.clone = function () {
  324. return new Color3(this.r, this.g, this.b);
  325. };
  326. /**
  327. * Copies the rgb values from the source in the current Color3.
  328. * Returns the updated Color3.
  329. */
  330. Color3.prototype.copyFrom = function (source) {
  331. this.r = source.r;
  332. this.g = source.g;
  333. this.b = source.b;
  334. return this;
  335. };
  336. /**
  337. * Updates the Color3 rgb values from the passed floats.
  338. * Returns the Color3.
  339. */
  340. Color3.prototype.copyFromFloats = function (r, g, b) {
  341. this.r = r;
  342. this.g = g;
  343. this.b = b;
  344. return this;
  345. };
  346. /**
  347. * Updates the Color3 rgb values from the passed floats.
  348. * Returns the Color3.
  349. */
  350. Color3.prototype.set = function (r, g, b) {
  351. return this.copyFromFloats(r, g, b);
  352. };
  353. /**
  354. * Returns the Color3 hexadecimal code as a string.
  355. */
  356. Color3.prototype.toHexString = function () {
  357. var intR = (this.r * 255) | 0;
  358. var intG = (this.g * 255) | 0;
  359. var intB = (this.b * 255) | 0;
  360. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  361. };
  362. /**
  363. * Returns a new Color3 converted to linear space.
  364. */
  365. Color3.prototype.toLinearSpace = function () {
  366. var convertedColor = new Color3();
  367. this.toLinearSpaceToRef(convertedColor);
  368. return convertedColor;
  369. };
  370. /**
  371. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  372. * Returns the unmodified Color3.
  373. */
  374. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  375. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  376. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  377. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  378. return this;
  379. };
  380. /**
  381. * Returns a new Color3 converted to gamma space.
  382. */
  383. Color3.prototype.toGammaSpace = function () {
  384. var convertedColor = new Color3();
  385. this.toGammaSpaceToRef(convertedColor);
  386. return convertedColor;
  387. };
  388. /**
  389. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  390. * Returns the unmodified Color3.
  391. */
  392. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  393. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  394. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  395. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  396. return this;
  397. };
  398. // Statics
  399. /**
  400. * Creates a new Color3 from the string containing valid hexadecimal values.
  401. */
  402. Color3.FromHexString = function (hex) {
  403. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  404. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  405. return new Color3(0, 0, 0);
  406. }
  407. var r = parseInt(hex.substring(1, 3), 16);
  408. var g = parseInt(hex.substring(3, 5), 16);
  409. var b = parseInt(hex.substring(5, 7), 16);
  410. return Color3.FromInts(r, g, b);
  411. };
  412. /**
  413. * Creates a new Vector3 from the startind index of the passed array.
  414. */
  415. Color3.FromArray = function (array, offset) {
  416. if (offset === void 0) { offset = 0; }
  417. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  418. };
  419. /**
  420. * Creates a new Color3 from integer values ( < 256).
  421. */
  422. Color3.FromInts = function (r, g, b) {
  423. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  424. };
  425. /**
  426. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  427. */
  428. Color3.Lerp = function (start, end, amount) {
  429. var r = start.r + ((end.r - start.r) * amount);
  430. var g = start.g + ((end.g - start.g) * amount);
  431. var b = start.b + ((end.b - start.b) * amount);
  432. return new Color3(r, g, b);
  433. };
  434. Color3.Red = function () { return new Color3(1, 0, 0); };
  435. Color3.Green = function () { return new Color3(0, 1, 0); };
  436. Color3.Blue = function () { return new Color3(0, 0, 1); };
  437. Color3.Black = function () { return new Color3(0, 0, 0); };
  438. Color3.White = function () { return new Color3(1, 1, 1); };
  439. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  440. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  441. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  442. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  443. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  444. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  445. return Color3;
  446. }());
  447. BABYLON.Color3 = Color3;
  448. var Color4 = /** @class */ (function () {
  449. /**
  450. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  451. */
  452. function Color4(r, g, b, a) {
  453. if (r === void 0) { r = 0; }
  454. if (g === void 0) { g = 0; }
  455. if (b === void 0) { b = 0; }
  456. if (a === void 0) { a = 1; }
  457. this.r = r;
  458. this.g = g;
  459. this.b = b;
  460. this.a = a;
  461. }
  462. // Operators
  463. /**
  464. * Adds in place the passed Color4 values to the current Color4.
  465. * Returns the updated Color4.
  466. */
  467. Color4.prototype.addInPlace = function (right) {
  468. this.r += right.r;
  469. this.g += right.g;
  470. this.b += right.b;
  471. this.a += right.a;
  472. return this;
  473. };
  474. /**
  475. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  476. */
  477. Color4.prototype.asArray = function () {
  478. var result = new Array();
  479. this.toArray(result, 0);
  480. return result;
  481. };
  482. /**
  483. * Stores from the starting index in the passed array the Color4 successive values.
  484. * Returns the Color4.
  485. */
  486. Color4.prototype.toArray = function (array, index) {
  487. if (index === undefined) {
  488. index = 0;
  489. }
  490. array[index] = this.r;
  491. array[index + 1] = this.g;
  492. array[index + 2] = this.b;
  493. array[index + 3] = this.a;
  494. return this;
  495. };
  496. /**
  497. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  498. */
  499. Color4.prototype.add = function (right) {
  500. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  501. };
  502. /**
  503. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  504. */
  505. Color4.prototype.subtract = function (right) {
  506. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  507. };
  508. /**
  509. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  510. * Returns the Color4.
  511. */
  512. Color4.prototype.subtractToRef = function (right, result) {
  513. result.r = this.r - right.r;
  514. result.g = this.g - right.g;
  515. result.b = this.b - right.b;
  516. result.a = this.a - right.a;
  517. return this;
  518. };
  519. /**
  520. * Creates a new Color4 with the current Color4 values multiplied by scale.
  521. */
  522. Color4.prototype.scale = function (scale) {
  523. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  524. };
  525. /**
  526. * Multiplies the current Color4 values by scale and stores the result in "result".
  527. * Returns the Color4.
  528. */
  529. Color4.prototype.scaleToRef = function (scale, result) {
  530. result.r = this.r * scale;
  531. result.g = this.g * scale;
  532. result.b = this.b * scale;
  533. result.a = this.a * scale;
  534. return this;
  535. };
  536. /**
  537. * Multipy an RGBA Color4 value by another and return a new Color4 object
  538. * @param color The Color4 (RGBA) value to multiply by
  539. * @returns A new Color4.
  540. */
  541. Color4.prototype.multiply = function (color) {
  542. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  543. };
  544. /**
  545. * Multipy an RGBA Color4 value by another and push the result in a reference value
  546. * @param color The Color4 (RGBA) value to multiply by
  547. * @param result The Color4 (RGBA) to fill the result in
  548. * @returns the result Color4.
  549. */
  550. Color4.prototype.multiplyToRef = function (color, result) {
  551. result.r = this.r * color.r;
  552. result.g = this.g * color.g;
  553. result.b = this.b * color.b;
  554. result.a = this.a * color.a;
  555. return result;
  556. };
  557. /**
  558. * Returns a string with the Color4 values.
  559. */
  560. Color4.prototype.toString = function () {
  561. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  562. };
  563. /**
  564. * Returns the string "Color4"
  565. */
  566. Color4.prototype.getClassName = function () {
  567. return "Color4";
  568. };
  569. /**
  570. * Return the Color4 hash code as a number.
  571. */
  572. Color4.prototype.getHashCode = function () {
  573. var hash = this.r || 0;
  574. hash = (hash * 397) ^ (this.g || 0);
  575. hash = (hash * 397) ^ (this.b || 0);
  576. hash = (hash * 397) ^ (this.a || 0);
  577. return hash;
  578. };
  579. /**
  580. * Creates a new Color4 copied from the current one.
  581. */
  582. Color4.prototype.clone = function () {
  583. return new Color4(this.r, this.g, this.b, this.a);
  584. };
  585. /**
  586. * Copies the passed Color4 values into the current one.
  587. * Returns the updated Color4.
  588. */
  589. Color4.prototype.copyFrom = function (source) {
  590. this.r = source.r;
  591. this.g = source.g;
  592. this.b = source.b;
  593. this.a = source.a;
  594. return this;
  595. };
  596. /**
  597. * Copies the passed float values into the current one.
  598. * Returns the updated Color4.
  599. */
  600. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  601. this.r = r;
  602. this.g = g;
  603. this.b = b;
  604. this.a = a;
  605. return this;
  606. };
  607. /**
  608. * Copies the passed float values into the current one.
  609. * Returns the updated Color4.
  610. */
  611. Color4.prototype.set = function (r, g, b, a) {
  612. return this.copyFromFloats(r, g, b, a);
  613. };
  614. /**
  615. * Returns a string containing the hexadecimal Color4 code.
  616. */
  617. Color4.prototype.toHexString = function () {
  618. var intR = (this.r * 255) | 0;
  619. var intG = (this.g * 255) | 0;
  620. var intB = (this.b * 255) | 0;
  621. var intA = (this.a * 255) | 0;
  622. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  623. };
  624. /**
  625. * Returns a new Color4 converted to linear space.
  626. */
  627. Color4.prototype.toLinearSpace = function () {
  628. var convertedColor = new Color4();
  629. this.toLinearSpaceToRef(convertedColor);
  630. return convertedColor;
  631. };
  632. /**
  633. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  634. * Returns the unmodified Color4.
  635. */
  636. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  637. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  638. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  639. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  640. convertedColor.a = this.a;
  641. return this;
  642. };
  643. /**
  644. * Returns a new Color4 converted to gamma space.
  645. */
  646. Color4.prototype.toGammaSpace = function () {
  647. var convertedColor = new Color4();
  648. this.toGammaSpaceToRef(convertedColor);
  649. return convertedColor;
  650. };
  651. /**
  652. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  653. * Returns the unmodified Color4.
  654. */
  655. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  656. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  657. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  658. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  659. convertedColor.a = this.a;
  660. return this;
  661. };
  662. // Statics
  663. /**
  664. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  665. */
  666. Color4.FromHexString = function (hex) {
  667. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  668. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  669. return new Color4(0.0, 0.0, 0.0, 0.0);
  670. }
  671. var r = parseInt(hex.substring(1, 3), 16);
  672. var g = parseInt(hex.substring(3, 5), 16);
  673. var b = parseInt(hex.substring(5, 7), 16);
  674. var a = parseInt(hex.substring(7, 9), 16);
  675. return Color4.FromInts(r, g, b, a);
  676. };
  677. /**
  678. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  679. */
  680. Color4.Lerp = function (left, right, amount) {
  681. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  682. Color4.LerpToRef(left, right, amount, result);
  683. return result;
  684. };
  685. /**
  686. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  687. */
  688. Color4.LerpToRef = function (left, right, amount, result) {
  689. result.r = left.r + (right.r - left.r) * amount;
  690. result.g = left.g + (right.g - left.g) * amount;
  691. result.b = left.b + (right.b - left.b) * amount;
  692. result.a = left.a + (right.a - left.a) * amount;
  693. };
  694. /**
  695. * Creates a new Color4 from the starting index element of the passed array.
  696. */
  697. Color4.FromArray = function (array, offset) {
  698. if (offset === void 0) { offset = 0; }
  699. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  700. };
  701. /**
  702. * Creates a new Color4 from the passed integers ( < 256 ).
  703. */
  704. Color4.FromInts = function (r, g, b, a) {
  705. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  706. };
  707. Color4.CheckColors4 = function (colors, count) {
  708. // Check if color3 was used
  709. if (colors.length === count * 3) {
  710. var colors4 = [];
  711. for (var index = 0; index < colors.length; index += 3) {
  712. var newIndex = (index / 3) * 4;
  713. colors4[newIndex] = colors[index];
  714. colors4[newIndex + 1] = colors[index + 1];
  715. colors4[newIndex + 2] = colors[index + 2];
  716. colors4[newIndex + 3] = 1.0;
  717. }
  718. return colors4;
  719. }
  720. return colors;
  721. };
  722. return Color4;
  723. }());
  724. BABYLON.Color4 = Color4;
  725. var Vector2 = /** @class */ (function () {
  726. /**
  727. * Creates a new Vector2 from the passed x and y coordinates.
  728. */
  729. function Vector2(x, y) {
  730. this.x = x;
  731. this.y = y;
  732. }
  733. /**
  734. * Returns a string with the Vector2 coordinates.
  735. */
  736. Vector2.prototype.toString = function () {
  737. return "{X: " + this.x + " Y:" + this.y + "}";
  738. };
  739. /**
  740. * Returns the string "Vector2"
  741. */
  742. Vector2.prototype.getClassName = function () {
  743. return "Vector2";
  744. };
  745. /**
  746. * Returns the Vector2 hash code as a number.
  747. */
  748. Vector2.prototype.getHashCode = function () {
  749. var hash = this.x || 0;
  750. hash = (hash * 397) ^ (this.y || 0);
  751. return hash;
  752. };
  753. // Operators
  754. /**
  755. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  756. * Returns the Vector2.
  757. */
  758. Vector2.prototype.toArray = function (array, index) {
  759. if (index === void 0) { index = 0; }
  760. array[index] = this.x;
  761. array[index + 1] = this.y;
  762. return this;
  763. };
  764. /**
  765. * Returns a new array with 2 elements : the Vector2 coordinates.
  766. */
  767. Vector2.prototype.asArray = function () {
  768. var result = new Array();
  769. this.toArray(result, 0);
  770. return result;
  771. };
  772. /**
  773. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  774. * Returns the updated Vector2.
  775. */
  776. Vector2.prototype.copyFrom = function (source) {
  777. this.x = source.x;
  778. this.y = source.y;
  779. return this;
  780. };
  781. /**
  782. * Sets the Vector2 coordinates with the passed floats.
  783. * Returns the updated Vector2.
  784. */
  785. Vector2.prototype.copyFromFloats = function (x, y) {
  786. this.x = x;
  787. this.y = y;
  788. return this;
  789. };
  790. /**
  791. * Sets the Vector2 coordinates with the passed floats.
  792. * Returns the updated Vector2.
  793. */
  794. Vector2.prototype.set = function (x, y) {
  795. return this.copyFromFloats(x, y);
  796. };
  797. /**
  798. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  799. */
  800. Vector2.prototype.add = function (otherVector) {
  801. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  802. };
  803. /**
  804. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  805. * Returns the Vector2.
  806. */
  807. Vector2.prototype.addToRef = function (otherVector, result) {
  808. result.x = this.x + otherVector.x;
  809. result.y = this.y + otherVector.y;
  810. return this;
  811. };
  812. /**
  813. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  814. * Returns the updated Vector2.
  815. */
  816. Vector2.prototype.addInPlace = function (otherVector) {
  817. this.x += otherVector.x;
  818. this.y += otherVector.y;
  819. return this;
  820. };
  821. /**
  822. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  823. */
  824. Vector2.prototype.addVector3 = function (otherVector) {
  825. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  826. };
  827. /**
  828. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  829. */
  830. Vector2.prototype.subtract = function (otherVector) {
  831. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  832. };
  833. /**
  834. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  835. * Returns the Vector2.
  836. */
  837. Vector2.prototype.subtractToRef = function (otherVector, result) {
  838. result.x = this.x - otherVector.x;
  839. result.y = this.y - otherVector.y;
  840. return this;
  841. };
  842. /**
  843. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  844. * Returns the updated Vector2.
  845. */
  846. Vector2.prototype.subtractInPlace = function (otherVector) {
  847. this.x -= otherVector.x;
  848. this.y -= otherVector.y;
  849. return this;
  850. };
  851. /**
  852. * Multiplies in place the current Vector2 coordinates by the passed ones.
  853. * Returns the updated Vector2.
  854. */
  855. Vector2.prototype.multiplyInPlace = function (otherVector) {
  856. this.x *= otherVector.x;
  857. this.y *= otherVector.y;
  858. return this;
  859. };
  860. /**
  861. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  862. */
  863. Vector2.prototype.multiply = function (otherVector) {
  864. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  865. };
  866. /**
  867. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  868. * Returns the Vector2.
  869. */
  870. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  871. result.x = this.x * otherVector.x;
  872. result.y = this.y * otherVector.y;
  873. return this;
  874. };
  875. /**
  876. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  877. */
  878. Vector2.prototype.multiplyByFloats = function (x, y) {
  879. return new Vector2(this.x * x, this.y * y);
  880. };
  881. /**
  882. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  883. */
  884. Vector2.prototype.divide = function (otherVector) {
  885. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  886. };
  887. /**
  888. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  889. * Returns the Vector2.
  890. */
  891. Vector2.prototype.divideToRef = function (otherVector, result) {
  892. result.x = this.x / otherVector.x;
  893. result.y = this.y / otherVector.y;
  894. return this;
  895. };
  896. /**
  897. * Returns a new Vector2 with current Vector2 negated coordinates.
  898. */
  899. Vector2.prototype.negate = function () {
  900. return new Vector2(-this.x, -this.y);
  901. };
  902. /**
  903. * Multiply the Vector2 coordinates by scale.
  904. * Returns the updated Vector2.
  905. */
  906. Vector2.prototype.scaleInPlace = function (scale) {
  907. this.x *= scale;
  908. this.y *= scale;
  909. return this;
  910. };
  911. /**
  912. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  913. */
  914. Vector2.prototype.scale = function (scale) {
  915. return new Vector2(this.x * scale, this.y * scale);
  916. };
  917. /**
  918. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  919. */
  920. Vector2.prototype.equals = function (otherVector) {
  921. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  922. };
  923. /**
  924. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  925. */
  926. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  927. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  928. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  929. };
  930. // Properties
  931. /**
  932. * Returns the vector length (float).
  933. */
  934. Vector2.prototype.length = function () {
  935. return Math.sqrt(this.x * this.x + this.y * this.y);
  936. };
  937. /**
  938. * Returns the vector squared length (float);
  939. */
  940. Vector2.prototype.lengthSquared = function () {
  941. return (this.x * this.x + this.y * this.y);
  942. };
  943. // Methods
  944. /**
  945. * Normalize the vector.
  946. * Returns the updated Vector2.
  947. */
  948. Vector2.prototype.normalize = function () {
  949. var len = this.length();
  950. if (len === 0)
  951. return this;
  952. var num = 1.0 / len;
  953. this.x *= num;
  954. this.y *= num;
  955. return this;
  956. };
  957. /**
  958. * Returns a new Vector2 copied from the Vector2.
  959. */
  960. Vector2.prototype.clone = function () {
  961. return new Vector2(this.x, this.y);
  962. };
  963. // Statics
  964. /**
  965. * Returns a new Vector2(0, 0)
  966. */
  967. Vector2.Zero = function () {
  968. return new Vector2(0, 0);
  969. };
  970. /**
  971. * Returns a new Vector2(1, 1)
  972. */
  973. Vector2.One = function () {
  974. return new Vector2(1, 1);
  975. };
  976. /**
  977. * Returns a new Vector2 set from the passed index element of the passed array.
  978. */
  979. Vector2.FromArray = function (array, offset) {
  980. if (offset === void 0) { offset = 0; }
  981. return new Vector2(array[offset], array[offset + 1]);
  982. };
  983. /**
  984. * Sets "result" from the passed index element of the passed array.
  985. */
  986. Vector2.FromArrayToRef = function (array, offset, result) {
  987. result.x = array[offset];
  988. result.y = array[offset + 1];
  989. };
  990. /**
  991. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  992. */
  993. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  994. var squared = amount * amount;
  995. var cubed = amount * squared;
  996. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  997. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  998. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  999. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1000. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1001. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1002. return new Vector2(x, y);
  1003. };
  1004. /**
  1005. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1006. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1007. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1008. */
  1009. Vector2.Clamp = function (value, min, max) {
  1010. var x = value.x;
  1011. x = (x > max.x) ? max.x : x;
  1012. x = (x < min.x) ? min.x : x;
  1013. var y = value.y;
  1014. y = (y > max.y) ? max.y : y;
  1015. y = (y < min.y) ? min.y : y;
  1016. return new Vector2(x, y);
  1017. };
  1018. /**
  1019. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1020. */
  1021. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1022. var squared = amount * amount;
  1023. var cubed = amount * squared;
  1024. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1025. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1026. var part3 = (cubed - (2.0 * squared)) + amount;
  1027. var part4 = cubed - squared;
  1028. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1029. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1030. return new Vector2(x, y);
  1031. };
  1032. /**
  1033. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1034. */
  1035. Vector2.Lerp = function (start, end, amount) {
  1036. var x = start.x + ((end.x - start.x) * amount);
  1037. var y = start.y + ((end.y - start.y) * amount);
  1038. return new Vector2(x, y);
  1039. };
  1040. /**
  1041. * Returns the dot product (float) of the vector "left" and the vector "right".
  1042. */
  1043. Vector2.Dot = function (left, right) {
  1044. return left.x * right.x + left.y * right.y;
  1045. };
  1046. /**
  1047. * Returns a new Vector2 equal to the normalized passed vector.
  1048. */
  1049. Vector2.Normalize = function (vector) {
  1050. var newVector = vector.clone();
  1051. newVector.normalize();
  1052. return newVector;
  1053. };
  1054. /**
  1055. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1056. */
  1057. Vector2.Minimize = function (left, right) {
  1058. var x = (left.x < right.x) ? left.x : right.x;
  1059. var y = (left.y < right.y) ? left.y : right.y;
  1060. return new Vector2(x, y);
  1061. };
  1062. /**
  1063. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1064. */
  1065. Vector2.Maximize = function (left, right) {
  1066. var x = (left.x > right.x) ? left.x : right.x;
  1067. var y = (left.y > right.y) ? left.y : right.y;
  1068. return new Vector2(x, y);
  1069. };
  1070. /**
  1071. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1072. */
  1073. Vector2.Transform = function (vector, transformation) {
  1074. var r = Vector2.Zero();
  1075. Vector2.TransformToRef(vector, transformation, r);
  1076. return r;
  1077. };
  1078. /**
  1079. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1080. */
  1081. Vector2.TransformToRef = function (vector, transformation, result) {
  1082. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1083. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1084. result.x = x;
  1085. result.y = y;
  1086. };
  1087. /**
  1088. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1089. */
  1090. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1091. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1092. var sign = a < 0 ? -1 : 1;
  1093. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1094. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1095. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1096. };
  1097. /**
  1098. * Returns the distance (float) between the vectors "value1" and "value2".
  1099. */
  1100. Vector2.Distance = function (value1, value2) {
  1101. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1102. };
  1103. /**
  1104. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1105. */
  1106. Vector2.DistanceSquared = function (value1, value2) {
  1107. var x = value1.x - value2.x;
  1108. var y = value1.y - value2.y;
  1109. return (x * x) + (y * y);
  1110. };
  1111. /**
  1112. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1113. */
  1114. Vector2.Center = function (value1, value2) {
  1115. var center = value1.add(value2);
  1116. center.scaleInPlace(0.5);
  1117. return center;
  1118. };
  1119. /**
  1120. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1121. */
  1122. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1123. var l2 = Vector2.DistanceSquared(segA, segB);
  1124. if (l2 === 0.0) {
  1125. return Vector2.Distance(p, segA);
  1126. }
  1127. var v = segB.subtract(segA);
  1128. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1129. var proj = segA.add(v.multiplyByFloats(t, t));
  1130. return Vector2.Distance(p, proj);
  1131. };
  1132. return Vector2;
  1133. }());
  1134. BABYLON.Vector2 = Vector2;
  1135. var Vector3 = /** @class */ (function () {
  1136. /**
  1137. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1138. * A Vector3 is the main object used in 3D geometry.
  1139. * It can represent etiher the coordinates of a point the space, either a direction.
  1140. */
  1141. function Vector3(x, y, z) {
  1142. this.x = x;
  1143. this.y = y;
  1144. this.z = z;
  1145. }
  1146. /**
  1147. * Returns a string with the Vector3 coordinates.
  1148. */
  1149. Vector3.prototype.toString = function () {
  1150. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1151. };
  1152. /**
  1153. * Returns the string "Vector3"
  1154. */
  1155. Vector3.prototype.getClassName = function () {
  1156. return "Vector3";
  1157. };
  1158. /**
  1159. * Returns the Vector hash code.
  1160. */
  1161. Vector3.prototype.getHashCode = function () {
  1162. var hash = this.x || 0;
  1163. hash = (hash * 397) ^ (this.y || 0);
  1164. hash = (hash * 397) ^ (this.z || 0);
  1165. return hash;
  1166. };
  1167. // Operators
  1168. /**
  1169. * Returns a new array with three elements : the coordinates the Vector3.
  1170. */
  1171. Vector3.prototype.asArray = function () {
  1172. var result = [];
  1173. this.toArray(result, 0);
  1174. return result;
  1175. };
  1176. /**
  1177. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1178. * Returns the Vector3.
  1179. */
  1180. Vector3.prototype.toArray = function (array, index) {
  1181. if (index === void 0) { index = 0; }
  1182. array[index] = this.x;
  1183. array[index + 1] = this.y;
  1184. array[index + 2] = this.z;
  1185. return this;
  1186. };
  1187. /**
  1188. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1189. */
  1190. Vector3.prototype.toQuaternion = function () {
  1191. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1192. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1193. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1194. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1195. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1196. var cosy = Math.cos(this.y * 0.5);
  1197. var siny = Math.sin(this.y * 0.5);
  1198. result.x = coszMinusx * siny;
  1199. result.y = -sinzMinusx * siny;
  1200. result.z = sinxPlusz * cosy;
  1201. result.w = cosxPlusz * cosy;
  1202. return result;
  1203. };
  1204. /**
  1205. * Adds the passed vector to the current Vector3.
  1206. * Returns the updated Vector3.
  1207. */
  1208. Vector3.prototype.addInPlace = function (otherVector) {
  1209. this.x += otherVector.x;
  1210. this.y += otherVector.y;
  1211. this.z += otherVector.z;
  1212. return this;
  1213. };
  1214. /**
  1215. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1216. */
  1217. Vector3.prototype.add = function (otherVector) {
  1218. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1219. };
  1220. /**
  1221. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1222. * Returns the current Vector3.
  1223. */
  1224. Vector3.prototype.addToRef = function (otherVector, result) {
  1225. result.x = this.x + otherVector.x;
  1226. result.y = this.y + otherVector.y;
  1227. result.z = this.z + otherVector.z;
  1228. return this;
  1229. };
  1230. /**
  1231. * Subtract the passed vector from the current Vector3.
  1232. * Returns the updated Vector3.
  1233. */
  1234. Vector3.prototype.subtractInPlace = function (otherVector) {
  1235. this.x -= otherVector.x;
  1236. this.y -= otherVector.y;
  1237. this.z -= otherVector.z;
  1238. return this;
  1239. };
  1240. /**
  1241. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1242. */
  1243. Vector3.prototype.subtract = function (otherVector) {
  1244. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1245. };
  1246. /**
  1247. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1248. * Returns the current Vector3.
  1249. */
  1250. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1251. result.x = this.x - otherVector.x;
  1252. result.y = this.y - otherVector.y;
  1253. result.z = this.z - otherVector.z;
  1254. return this;
  1255. };
  1256. /**
  1257. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1258. */
  1259. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1260. return new Vector3(this.x - x, this.y - y, this.z - z);
  1261. };
  1262. /**
  1263. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1264. * Returns the current Vector3.
  1265. */
  1266. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1267. result.x = this.x - x;
  1268. result.y = this.y - y;
  1269. result.z = this.z - z;
  1270. return this;
  1271. };
  1272. /**
  1273. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1274. */
  1275. Vector3.prototype.negate = function () {
  1276. return new Vector3(-this.x, -this.y, -this.z);
  1277. };
  1278. /**
  1279. * Multiplies the Vector3 coordinates by the float "scale".
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.scaleInPlace = function (scale) {
  1283. this.x *= scale;
  1284. this.y *= scale;
  1285. this.z *= scale;
  1286. return this;
  1287. };
  1288. /**
  1289. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1290. */
  1291. Vector3.prototype.scale = function (scale) {
  1292. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1293. };
  1294. /**
  1295. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1296. * Returns the current Vector3.
  1297. */
  1298. Vector3.prototype.scaleToRef = function (scale, result) {
  1299. result.x = this.x * scale;
  1300. result.y = this.y * scale;
  1301. result.z = this.z * scale;
  1302. return this;
  1303. };
  1304. /**
  1305. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1306. */
  1307. Vector3.prototype.equals = function (otherVector) {
  1308. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1309. };
  1310. /**
  1311. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1312. */
  1313. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1314. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1315. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1316. };
  1317. /**
  1318. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1319. */
  1320. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1321. return this.x === x && this.y === y && this.z === z;
  1322. };
  1323. /**
  1324. * Muliplies the current Vector3 coordinates by the passed ones.
  1325. * Returns the updated Vector3.
  1326. */
  1327. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1328. this.x *= otherVector.x;
  1329. this.y *= otherVector.y;
  1330. this.z *= otherVector.z;
  1331. return this;
  1332. };
  1333. /**
  1334. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1335. */
  1336. Vector3.prototype.multiply = function (otherVector) {
  1337. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1338. };
  1339. /**
  1340. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1341. * Returns the current Vector3.
  1342. */
  1343. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1344. result.x = this.x * otherVector.x;
  1345. result.y = this.y * otherVector.y;
  1346. result.z = this.z * otherVector.z;
  1347. return this;
  1348. };
  1349. /**
  1350. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1351. */
  1352. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1353. return new Vector3(this.x * x, this.y * y, this.z * z);
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1357. */
  1358. Vector3.prototype.divide = function (otherVector) {
  1359. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1360. };
  1361. /**
  1362. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1363. * Returns the current Vector3.
  1364. */
  1365. Vector3.prototype.divideToRef = function (otherVector, result) {
  1366. result.x = this.x / otherVector.x;
  1367. result.y = this.y / otherVector.y;
  1368. result.z = this.z / otherVector.z;
  1369. return this;
  1370. };
  1371. /**
  1372. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1373. * Returns the updated Vector3.
  1374. */
  1375. Vector3.prototype.MinimizeInPlace = function (other) {
  1376. if (other.x < this.x)
  1377. this.x = other.x;
  1378. if (other.y < this.y)
  1379. this.y = other.y;
  1380. if (other.z < this.z)
  1381. this.z = other.z;
  1382. return this;
  1383. };
  1384. /**
  1385. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1386. * Returns the updated Vector3.
  1387. */
  1388. Vector3.prototype.MaximizeInPlace = function (other) {
  1389. if (other.x > this.x)
  1390. this.x = other.x;
  1391. if (other.y > this.y)
  1392. this.y = other.y;
  1393. if (other.z > this.z)
  1394. this.z = other.z;
  1395. return this;
  1396. };
  1397. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  1398. /**
  1399. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  1400. */
  1401. get: function () {
  1402. var absX = Math.abs(this.x);
  1403. var absY = Math.abs(this.y);
  1404. if (absX !== absY) {
  1405. return true;
  1406. }
  1407. var absZ = Math.abs(this.z);
  1408. if (absX !== absZ) {
  1409. return true;
  1410. }
  1411. if (absY !== absZ) {
  1412. return true;
  1413. }
  1414. return false;
  1415. },
  1416. enumerable: true,
  1417. configurable: true
  1418. });
  1419. // Properties
  1420. /**
  1421. * Returns the length of the Vector3 (float).
  1422. */
  1423. Vector3.prototype.length = function () {
  1424. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1425. };
  1426. /**
  1427. * Returns the squared length of the Vector3 (float).
  1428. */
  1429. Vector3.prototype.lengthSquared = function () {
  1430. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1431. };
  1432. // Methods
  1433. /**
  1434. * Normalize the current Vector3.
  1435. * Returns the updated Vector3.
  1436. */
  1437. Vector3.prototype.normalize = function () {
  1438. var len = this.length();
  1439. if (len === 0 || len === 1.0)
  1440. return this;
  1441. var num = 1.0 / len;
  1442. this.x *= num;
  1443. this.y *= num;
  1444. this.z *= num;
  1445. return this;
  1446. };
  1447. /**
  1448. * Returns a new Vector3 copied from the current Vector3.
  1449. */
  1450. Vector3.prototype.clone = function () {
  1451. return new Vector3(this.x, this.y, this.z);
  1452. };
  1453. /**
  1454. * Copies the passed vector coordinates to the current Vector3 ones.
  1455. * Returns the updated Vector3.
  1456. */
  1457. Vector3.prototype.copyFrom = function (source) {
  1458. this.x = source.x;
  1459. this.y = source.y;
  1460. this.z = source.z;
  1461. return this;
  1462. };
  1463. /**
  1464. * Copies the passed floats to the current Vector3 coordinates.
  1465. * Returns the updated Vector3.
  1466. */
  1467. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1468. this.x = x;
  1469. this.y = y;
  1470. this.z = z;
  1471. return this;
  1472. };
  1473. /**
  1474. * Copies the passed floats to the current Vector3 coordinates.
  1475. * Returns the updated Vector3.
  1476. */
  1477. Vector3.prototype.set = function (x, y, z) {
  1478. return this.copyFromFloats(x, y, z);
  1479. };
  1480. // Statics
  1481. /**
  1482. *
  1483. */
  1484. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1485. var d0 = Vector3.Dot(vector0, axis) - size;
  1486. var d1 = Vector3.Dot(vector1, axis) - size;
  1487. var s = d0 / (d0 - d1);
  1488. return s;
  1489. };
  1490. /**
  1491. * Returns a new Vector3 set from the index "offset" of the passed array.
  1492. */
  1493. Vector3.FromArray = function (array, offset) {
  1494. if (!offset) {
  1495. offset = 0;
  1496. }
  1497. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1498. };
  1499. /**
  1500. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1501. * This function is deprecated. Use FromArray instead.
  1502. */
  1503. Vector3.FromFloatArray = function (array, offset) {
  1504. return Vector3.FromArray(array, offset);
  1505. };
  1506. /**
  1507. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1508. */
  1509. Vector3.FromArrayToRef = function (array, offset, result) {
  1510. result.x = array[offset];
  1511. result.y = array[offset + 1];
  1512. result.z = array[offset + 2];
  1513. };
  1514. /**
  1515. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1516. * This function is deprecated. Use FromArrayToRef instead.
  1517. */
  1518. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1519. return Vector3.FromArrayToRef(array, offset, result);
  1520. };
  1521. /**
  1522. * Sets the passed vector "result" with the passed floats.
  1523. */
  1524. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1525. result.x = x;
  1526. result.y = y;
  1527. result.z = z;
  1528. };
  1529. /**
  1530. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1531. */
  1532. Vector3.Zero = function () {
  1533. return new Vector3(0.0, 0.0, 0.0);
  1534. };
  1535. /**
  1536. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1537. */
  1538. Vector3.One = function () {
  1539. return new Vector3(1.0, 1.0, 1.0);
  1540. };
  1541. /**
  1542. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1543. */
  1544. Vector3.Up = function () {
  1545. return new Vector3(0.0, 1.0, 0.0);
  1546. };
  1547. /**
  1548. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1549. */
  1550. Vector3.Forward = function () {
  1551. return new Vector3(0.0, 0.0, 1.0);
  1552. };
  1553. /**
  1554. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1555. */
  1556. Vector3.Right = function () {
  1557. return new Vector3(1.0, 0.0, 0.0);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1561. */
  1562. Vector3.Left = function () {
  1563. return new Vector3(-1.0, 0.0, 0.0);
  1564. };
  1565. /**
  1566. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1567. * This method computes tranformed coordinates only, not transformed direction vectors.
  1568. */
  1569. Vector3.TransformCoordinates = function (vector, transformation) {
  1570. var result = Vector3.Zero();
  1571. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1572. return result;
  1573. };
  1574. /**
  1575. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1576. * This method computes tranformed coordinates only, not transformed direction vectors.
  1577. */
  1578. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1579. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1580. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1581. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1582. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1583. result.x = x / w;
  1584. result.y = y / w;
  1585. result.z = z / w;
  1586. };
  1587. /**
  1588. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1589. * This method computes tranformed coordinates only, not transformed direction vectors.
  1590. */
  1591. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1592. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1593. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1594. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1595. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1596. result.x = rx / rw;
  1597. result.y = ry / rw;
  1598. result.z = rz / rw;
  1599. };
  1600. /**
  1601. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1602. * This methods computes transformed normalized direction vectors only.
  1603. */
  1604. Vector3.TransformNormal = function (vector, transformation) {
  1605. var result = Vector3.Zero();
  1606. Vector3.TransformNormalToRef(vector, transformation, result);
  1607. return result;
  1608. };
  1609. /**
  1610. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1611. * This methods computes transformed normalized direction vectors only.
  1612. */
  1613. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1614. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1615. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1616. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1617. result.x = x;
  1618. result.y = y;
  1619. result.z = z;
  1620. };
  1621. /**
  1622. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1623. * This methods computes transformed normalized direction vectors only.
  1624. */
  1625. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1626. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1627. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1628. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1629. };
  1630. /**
  1631. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1632. */
  1633. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1634. var squared = amount * amount;
  1635. var cubed = amount * squared;
  1636. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1637. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1638. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1639. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1640. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1641. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1642. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1643. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1644. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1645. return new Vector3(x, y, z);
  1646. };
  1647. /**
  1648. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1649. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1650. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1651. */
  1652. Vector3.Clamp = function (value, min, max) {
  1653. var x = value.x;
  1654. x = (x > max.x) ? max.x : x;
  1655. x = (x < min.x) ? min.x : x;
  1656. var y = value.y;
  1657. y = (y > max.y) ? max.y : y;
  1658. y = (y < min.y) ? min.y : y;
  1659. var z = value.z;
  1660. z = (z > max.z) ? max.z : z;
  1661. z = (z < min.z) ? min.z : z;
  1662. return new Vector3(x, y, z);
  1663. };
  1664. /**
  1665. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1666. */
  1667. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1668. var squared = amount * amount;
  1669. var cubed = amount * squared;
  1670. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1671. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1672. var part3 = (cubed - (2.0 * squared)) + amount;
  1673. var part4 = cubed - squared;
  1674. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1675. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1676. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1677. return new Vector3(x, y, z);
  1678. };
  1679. /**
  1680. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1681. */
  1682. Vector3.Lerp = function (start, end, amount) {
  1683. var result = new Vector3(0, 0, 0);
  1684. Vector3.LerpToRef(start, end, amount, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1689. */
  1690. Vector3.LerpToRef = function (start, end, amount, result) {
  1691. result.x = start.x + ((end.x - start.x) * amount);
  1692. result.y = start.y + ((end.y - start.y) * amount);
  1693. result.z = start.z + ((end.z - start.z) * amount);
  1694. };
  1695. /**
  1696. * Returns the dot product (float) between the vectors "left" and "right".
  1697. */
  1698. Vector3.Dot = function (left, right) {
  1699. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1700. };
  1701. /**
  1702. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1703. * The cross product is then orthogonal to both "left" and "right".
  1704. */
  1705. Vector3.Cross = function (left, right) {
  1706. var result = Vector3.Zero();
  1707. Vector3.CrossToRef(left, right, result);
  1708. return result;
  1709. };
  1710. /**
  1711. * Sets the passed vector "result" with the cross product of "left" and "right".
  1712. * The cross product is then orthogonal to both "left" and "right".
  1713. */
  1714. Vector3.CrossToRef = function (left, right, result) {
  1715. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1716. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1717. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1718. result.copyFrom(MathTmp.Vector3[0]);
  1719. };
  1720. /**
  1721. * Returns a new Vector3 as the normalization of the passed vector.
  1722. */
  1723. Vector3.Normalize = function (vector) {
  1724. var result = Vector3.Zero();
  1725. Vector3.NormalizeToRef(vector, result);
  1726. return result;
  1727. };
  1728. /**
  1729. * Sets the passed vector "result" with the normalization of the passed first vector.
  1730. */
  1731. Vector3.NormalizeToRef = function (vector, result) {
  1732. result.copyFrom(vector);
  1733. result.normalize();
  1734. };
  1735. Vector3.Project = function (vector, world, transform, viewport) {
  1736. var cw = viewport.width;
  1737. var ch = viewport.height;
  1738. var cx = viewport.x;
  1739. var cy = viewport.y;
  1740. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1741. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1742. var matrix = MathTmp.Matrix[0];
  1743. world.multiplyToRef(transform, matrix);
  1744. matrix.multiplyToRef(viewportMatrix, matrix);
  1745. return Vector3.TransformCoordinates(vector, matrix);
  1746. };
  1747. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1748. var matrix = MathTmp.Matrix[0];
  1749. world.multiplyToRef(transform, matrix);
  1750. matrix.invert();
  1751. source.x = source.x / viewportWidth * 2 - 1;
  1752. source.y = -(source.y / viewportHeight * 2 - 1);
  1753. var vector = Vector3.TransformCoordinates(source, matrix);
  1754. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1755. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1756. vector = vector.scale(1.0 / num);
  1757. }
  1758. return vector;
  1759. };
  1760. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1761. var result = Vector3.Zero();
  1762. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  1763. return result;
  1764. };
  1765. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  1766. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  1767. };
  1768. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  1769. var matrix = MathTmp.Matrix[0];
  1770. world.multiplyToRef(view, matrix);
  1771. matrix.multiplyToRef(projection, matrix);
  1772. matrix.invert();
  1773. var screenSource = MathTmp.Vector3[0];
  1774. screenSource.x = sourceX / viewportWidth * 2 - 1;
  1775. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  1776. screenSource.z = 2 * sourceZ - 1.0;
  1777. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  1778. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1779. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1780. result.scaleInPlace(1.0 / num);
  1781. }
  1782. };
  1783. Vector3.Minimize = function (left, right) {
  1784. var min = left.clone();
  1785. min.MinimizeInPlace(right);
  1786. return min;
  1787. };
  1788. Vector3.Maximize = function (left, right) {
  1789. var max = left.clone();
  1790. max.MaximizeInPlace(right);
  1791. return max;
  1792. };
  1793. /**
  1794. * Returns the distance (float) between the vectors "value1" and "value2".
  1795. */
  1796. Vector3.Distance = function (value1, value2) {
  1797. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1798. };
  1799. /**
  1800. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1801. */
  1802. Vector3.DistanceSquared = function (value1, value2) {
  1803. var x = value1.x - value2.x;
  1804. var y = value1.y - value2.y;
  1805. var z = value1.z - value2.z;
  1806. return (x * x) + (y * y) + (z * z);
  1807. };
  1808. /**
  1809. * Returns a new Vector3 located at the center between "value1" and "value2".
  1810. */
  1811. Vector3.Center = function (value1, value2) {
  1812. var center = value1.add(value2);
  1813. center.scaleInPlace(0.5);
  1814. return center;
  1815. };
  1816. /**
  1817. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1818. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1819. * to something in order to rotate it from its local system to the given target system.
  1820. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1821. * Returns a new Vector3.
  1822. */
  1823. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1824. var rotation = Vector3.Zero();
  1825. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1826. return rotation;
  1827. };
  1828. /**
  1829. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1830. */
  1831. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1832. var quat = MathTmp.Quaternion[0];
  1833. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1834. quat.toEulerAnglesToRef(ref);
  1835. };
  1836. return Vector3;
  1837. }());
  1838. BABYLON.Vector3 = Vector3;
  1839. //Vector4 class created for EulerAngle class conversion to Quaternion
  1840. var Vector4 = /** @class */ (function () {
  1841. /**
  1842. * Creates a Vector4 object from the passed floats.
  1843. */
  1844. function Vector4(x, y, z, w) {
  1845. this.x = x;
  1846. this.y = y;
  1847. this.z = z;
  1848. this.w = w;
  1849. }
  1850. /**
  1851. * Returns the string with the Vector4 coordinates.
  1852. */
  1853. Vector4.prototype.toString = function () {
  1854. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1855. };
  1856. /**
  1857. * Returns the string "Vector4".
  1858. */
  1859. Vector4.prototype.getClassName = function () {
  1860. return "Vector4";
  1861. };
  1862. /**
  1863. * Returns the Vector4 hash code.
  1864. */
  1865. Vector4.prototype.getHashCode = function () {
  1866. var hash = this.x || 0;
  1867. hash = (hash * 397) ^ (this.y || 0);
  1868. hash = (hash * 397) ^ (this.z || 0);
  1869. hash = (hash * 397) ^ (this.w || 0);
  1870. return hash;
  1871. };
  1872. // Operators
  1873. /**
  1874. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1875. */
  1876. Vector4.prototype.asArray = function () {
  1877. var result = new Array();
  1878. this.toArray(result, 0);
  1879. return result;
  1880. };
  1881. /**
  1882. * Populates the passed array from the passed index with the Vector4 coordinates.
  1883. * Returns the Vector4.
  1884. */
  1885. Vector4.prototype.toArray = function (array, index) {
  1886. if (index === undefined) {
  1887. index = 0;
  1888. }
  1889. array[index] = this.x;
  1890. array[index + 1] = this.y;
  1891. array[index + 2] = this.z;
  1892. array[index + 3] = this.w;
  1893. return this;
  1894. };
  1895. /**
  1896. * Adds the passed vector to the current Vector4.
  1897. * Returns the updated Vector4.
  1898. */
  1899. Vector4.prototype.addInPlace = function (otherVector) {
  1900. this.x += otherVector.x;
  1901. this.y += otherVector.y;
  1902. this.z += otherVector.z;
  1903. this.w += otherVector.w;
  1904. return this;
  1905. };
  1906. /**
  1907. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1908. */
  1909. Vector4.prototype.add = function (otherVector) {
  1910. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1911. };
  1912. /**
  1913. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1914. * Returns the current Vector4.
  1915. */
  1916. Vector4.prototype.addToRef = function (otherVector, result) {
  1917. result.x = this.x + otherVector.x;
  1918. result.y = this.y + otherVector.y;
  1919. result.z = this.z + otherVector.z;
  1920. result.w = this.w + otherVector.w;
  1921. return this;
  1922. };
  1923. /**
  1924. * Subtract in place the passed vector from the current Vector4.
  1925. * Returns the updated Vector4.
  1926. */
  1927. Vector4.prototype.subtractInPlace = function (otherVector) {
  1928. this.x -= otherVector.x;
  1929. this.y -= otherVector.y;
  1930. this.z -= otherVector.z;
  1931. this.w -= otherVector.w;
  1932. return this;
  1933. };
  1934. /**
  1935. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1936. */
  1937. Vector4.prototype.subtract = function (otherVector) {
  1938. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1939. };
  1940. /**
  1941. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1942. * Returns the current Vector4.
  1943. */
  1944. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1945. result.x = this.x - otherVector.x;
  1946. result.y = this.y - otherVector.y;
  1947. result.z = this.z - otherVector.z;
  1948. result.w = this.w - otherVector.w;
  1949. return this;
  1950. };
  1951. /**
  1952. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1953. */
  1954. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1955. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1956. };
  1957. /**
  1958. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1959. * Returns the current Vector4.
  1960. */
  1961. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1962. result.x = this.x - x;
  1963. result.y = this.y - y;
  1964. result.z = this.z - z;
  1965. result.w = this.w - w;
  1966. return this;
  1967. };
  1968. /**
  1969. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1970. */
  1971. Vector4.prototype.negate = function () {
  1972. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1973. };
  1974. /**
  1975. * Multiplies the current Vector4 coordinates by scale (float).
  1976. * Returns the updated Vector4.
  1977. */
  1978. Vector4.prototype.scaleInPlace = function (scale) {
  1979. this.x *= scale;
  1980. this.y *= scale;
  1981. this.z *= scale;
  1982. this.w *= scale;
  1983. return this;
  1984. };
  1985. /**
  1986. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1987. */
  1988. Vector4.prototype.scale = function (scale) {
  1989. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1990. };
  1991. /**
  1992. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1993. * Returns the current Vector4.
  1994. */
  1995. Vector4.prototype.scaleToRef = function (scale, result) {
  1996. result.x = this.x * scale;
  1997. result.y = this.y * scale;
  1998. result.z = this.z * scale;
  1999. result.w = this.w * scale;
  2000. return this;
  2001. };
  2002. /**
  2003. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2004. */
  2005. Vector4.prototype.equals = function (otherVector) {
  2006. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2007. };
  2008. /**
  2009. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2010. */
  2011. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2012. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2013. return otherVector
  2014. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2015. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2016. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2017. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2018. };
  2019. /**
  2020. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2021. */
  2022. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2023. return this.x === x && this.y === y && this.z === z && this.w === w;
  2024. };
  2025. /**
  2026. * Multiplies in place the current Vector4 by the passed one.
  2027. * Returns the updated Vector4.
  2028. */
  2029. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2030. this.x *= otherVector.x;
  2031. this.y *= otherVector.y;
  2032. this.z *= otherVector.z;
  2033. this.w *= otherVector.w;
  2034. return this;
  2035. };
  2036. /**
  2037. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2038. */
  2039. Vector4.prototype.multiply = function (otherVector) {
  2040. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2041. };
  2042. /**
  2043. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2044. * Returns the current Vector4.
  2045. */
  2046. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2047. result.x = this.x * otherVector.x;
  2048. result.y = this.y * otherVector.y;
  2049. result.z = this.z * otherVector.z;
  2050. result.w = this.w * otherVector.w;
  2051. return this;
  2052. };
  2053. /**
  2054. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2055. */
  2056. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2057. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2058. };
  2059. /**
  2060. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2061. */
  2062. Vector4.prototype.divide = function (otherVector) {
  2063. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2064. };
  2065. /**
  2066. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2067. * Returns the current Vector4.
  2068. */
  2069. Vector4.prototype.divideToRef = function (otherVector, result) {
  2070. result.x = this.x / otherVector.x;
  2071. result.y = this.y / otherVector.y;
  2072. result.z = this.z / otherVector.z;
  2073. result.w = this.w / otherVector.w;
  2074. return this;
  2075. };
  2076. /**
  2077. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2078. */
  2079. Vector4.prototype.MinimizeInPlace = function (other) {
  2080. if (other.x < this.x)
  2081. this.x = other.x;
  2082. if (other.y < this.y)
  2083. this.y = other.y;
  2084. if (other.z < this.z)
  2085. this.z = other.z;
  2086. if (other.w < this.w)
  2087. this.w = other.w;
  2088. return this;
  2089. };
  2090. /**
  2091. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2092. */
  2093. Vector4.prototype.MaximizeInPlace = function (other) {
  2094. if (other.x > this.x)
  2095. this.x = other.x;
  2096. if (other.y > this.y)
  2097. this.y = other.y;
  2098. if (other.z > this.z)
  2099. this.z = other.z;
  2100. if (other.w > this.w)
  2101. this.w = other.w;
  2102. return this;
  2103. };
  2104. // Properties
  2105. /**
  2106. * Returns the Vector4 length (float).
  2107. */
  2108. Vector4.prototype.length = function () {
  2109. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2110. };
  2111. /**
  2112. * Returns the Vector4 squared length (float).
  2113. */
  2114. Vector4.prototype.lengthSquared = function () {
  2115. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2116. };
  2117. // Methods
  2118. /**
  2119. * Normalizes in place the Vector4.
  2120. * Returns the updated Vector4.
  2121. */
  2122. Vector4.prototype.normalize = function () {
  2123. var len = this.length();
  2124. if (len === 0)
  2125. return this;
  2126. var num = 1.0 / len;
  2127. this.x *= num;
  2128. this.y *= num;
  2129. this.z *= num;
  2130. this.w *= num;
  2131. return this;
  2132. };
  2133. /**
  2134. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2135. */
  2136. Vector4.prototype.toVector3 = function () {
  2137. return new Vector3(this.x, this.y, this.z);
  2138. };
  2139. /**
  2140. * Returns a new Vector4 copied from the current one.
  2141. */
  2142. Vector4.prototype.clone = function () {
  2143. return new Vector4(this.x, this.y, this.z, this.w);
  2144. };
  2145. /**
  2146. * Updates the current Vector4 with the passed one coordinates.
  2147. * Returns the updated Vector4.
  2148. */
  2149. Vector4.prototype.copyFrom = function (source) {
  2150. this.x = source.x;
  2151. this.y = source.y;
  2152. this.z = source.z;
  2153. this.w = source.w;
  2154. return this;
  2155. };
  2156. /**
  2157. * Updates the current Vector4 coordinates with the passed floats.
  2158. * Returns the updated Vector4.
  2159. */
  2160. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2161. this.x = x;
  2162. this.y = y;
  2163. this.z = z;
  2164. this.w = w;
  2165. return this;
  2166. };
  2167. /**
  2168. * Updates the current Vector4 coordinates with the passed floats.
  2169. * Returns the updated Vector4.
  2170. */
  2171. Vector4.prototype.set = function (x, y, z, w) {
  2172. return this.copyFromFloats(x, y, z, w);
  2173. };
  2174. // Statics
  2175. /**
  2176. * Returns a new Vector4 set from the starting index of the passed array.
  2177. */
  2178. Vector4.FromArray = function (array, offset) {
  2179. if (!offset) {
  2180. offset = 0;
  2181. }
  2182. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2183. };
  2184. /**
  2185. * Updates the passed vector "result" from the starting index of the passed array.
  2186. */
  2187. Vector4.FromArrayToRef = function (array, offset, result) {
  2188. result.x = array[offset];
  2189. result.y = array[offset + 1];
  2190. result.z = array[offset + 2];
  2191. result.w = array[offset + 3];
  2192. };
  2193. /**
  2194. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2195. */
  2196. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2197. Vector4.FromArrayToRef(array, offset, result);
  2198. };
  2199. /**
  2200. * Updates the passed vector "result" coordinates from the passed floats.
  2201. */
  2202. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2203. result.x = x;
  2204. result.y = y;
  2205. result.z = z;
  2206. result.w = w;
  2207. };
  2208. /**
  2209. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2210. */
  2211. Vector4.Zero = function () {
  2212. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2213. };
  2214. /**
  2215. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2216. */
  2217. Vector4.One = function () {
  2218. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2219. };
  2220. /**
  2221. * Returns a new normalized Vector4 from the passed one.
  2222. */
  2223. Vector4.Normalize = function (vector) {
  2224. var result = Vector4.Zero();
  2225. Vector4.NormalizeToRef(vector, result);
  2226. return result;
  2227. };
  2228. /**
  2229. * Updates the passed vector "result" from the normalization of the passed one.
  2230. */
  2231. Vector4.NormalizeToRef = function (vector, result) {
  2232. result.copyFrom(vector);
  2233. result.normalize();
  2234. };
  2235. Vector4.Minimize = function (left, right) {
  2236. var min = left.clone();
  2237. min.MinimizeInPlace(right);
  2238. return min;
  2239. };
  2240. Vector4.Maximize = function (left, right) {
  2241. var max = left.clone();
  2242. max.MaximizeInPlace(right);
  2243. return max;
  2244. };
  2245. /**
  2246. * Returns the distance (float) between the vectors "value1" and "value2".
  2247. */
  2248. Vector4.Distance = function (value1, value2) {
  2249. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2250. };
  2251. /**
  2252. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2253. */
  2254. Vector4.DistanceSquared = function (value1, value2) {
  2255. var x = value1.x - value2.x;
  2256. var y = value1.y - value2.y;
  2257. var z = value1.z - value2.z;
  2258. var w = value1.w - value2.w;
  2259. return (x * x) + (y * y) + (z * z) + (w * w);
  2260. };
  2261. /**
  2262. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2263. */
  2264. Vector4.Center = function (value1, value2) {
  2265. var center = value1.add(value2);
  2266. center.scaleInPlace(0.5);
  2267. return center;
  2268. };
  2269. /**
  2270. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2271. * This methods computes transformed normalized direction vectors only.
  2272. */
  2273. Vector4.TransformNormal = function (vector, transformation) {
  2274. var result = Vector4.Zero();
  2275. Vector4.TransformNormalToRef(vector, transformation, result);
  2276. return result;
  2277. };
  2278. /**
  2279. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2280. * This methods computes transformed normalized direction vectors only.
  2281. */
  2282. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2283. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2284. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2285. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2286. result.x = x;
  2287. result.y = y;
  2288. result.z = z;
  2289. result.w = vector.w;
  2290. };
  2291. /**
  2292. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2293. * This methods computes transformed normalized direction vectors only.
  2294. */
  2295. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2296. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2297. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2298. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2299. result.w = w;
  2300. };
  2301. return Vector4;
  2302. }());
  2303. BABYLON.Vector4 = Vector4;
  2304. var Size = /** @class */ (function () {
  2305. /**
  2306. * Creates a Size object from the passed width and height (floats).
  2307. */
  2308. function Size(width, height) {
  2309. this.width = width;
  2310. this.height = height;
  2311. }
  2312. // Returns a string with the Size width and height.
  2313. Size.prototype.toString = function () {
  2314. return "{W: " + this.width + ", H: " + this.height + "}";
  2315. };
  2316. /**
  2317. * Returns the string "Size"
  2318. */
  2319. Size.prototype.getClassName = function () {
  2320. return "Size";
  2321. };
  2322. /**
  2323. * Returns the Size hash code.
  2324. */
  2325. Size.prototype.getHashCode = function () {
  2326. var hash = this.width || 0;
  2327. hash = (hash * 397) ^ (this.height || 0);
  2328. return hash;
  2329. };
  2330. /**
  2331. * Updates the current size from the passed one.
  2332. * Returns the updated Size.
  2333. */
  2334. Size.prototype.copyFrom = function (src) {
  2335. this.width = src.width;
  2336. this.height = src.height;
  2337. };
  2338. /**
  2339. * Updates in place the current Size from the passed floats.
  2340. * Returns the updated Size.
  2341. */
  2342. Size.prototype.copyFromFloats = function (width, height) {
  2343. this.width = width;
  2344. this.height = height;
  2345. return this;
  2346. };
  2347. /**
  2348. * Updates in place the current Size from the passed floats.
  2349. * Returns the updated Size.
  2350. */
  2351. Size.prototype.set = function (width, height) {
  2352. return this.copyFromFloats(width, height);
  2353. };
  2354. /**
  2355. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2356. */
  2357. Size.prototype.multiplyByFloats = function (w, h) {
  2358. return new Size(this.width * w, this.height * h);
  2359. };
  2360. /**
  2361. * Returns a new Size copied from the passed one.
  2362. */
  2363. Size.prototype.clone = function () {
  2364. return new Size(this.width, this.height);
  2365. };
  2366. /**
  2367. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2368. */
  2369. Size.prototype.equals = function (other) {
  2370. if (!other) {
  2371. return false;
  2372. }
  2373. return (this.width === other.width) && (this.height === other.height);
  2374. };
  2375. Object.defineProperty(Size.prototype, "surface", {
  2376. /**
  2377. * Returns the surface of the Size : width * height (float).
  2378. */
  2379. get: function () {
  2380. return this.width * this.height;
  2381. },
  2382. enumerable: true,
  2383. configurable: true
  2384. });
  2385. /**
  2386. * Returns a new Size set to (0.0, 0.0)
  2387. */
  2388. Size.Zero = function () {
  2389. return new Size(0.0, 0.0);
  2390. };
  2391. /**
  2392. * Returns a new Size set as the addition result of the current Size and the passed one.
  2393. */
  2394. Size.prototype.add = function (otherSize) {
  2395. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2396. return r;
  2397. };
  2398. /**
  2399. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2400. */
  2401. Size.prototype.subtract = function (otherSize) {
  2402. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2403. return r;
  2404. };
  2405. /**
  2406. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2407. */
  2408. Size.Lerp = function (start, end, amount) {
  2409. var w = start.width + ((end.width - start.width) * amount);
  2410. var h = start.height + ((end.height - start.height) * amount);
  2411. return new Size(w, h);
  2412. };
  2413. return Size;
  2414. }());
  2415. BABYLON.Size = Size;
  2416. var Quaternion = /** @class */ (function () {
  2417. /**
  2418. * Creates a new Quaternion from the passed floats.
  2419. */
  2420. function Quaternion(x, y, z, w) {
  2421. if (x === void 0) { x = 0.0; }
  2422. if (y === void 0) { y = 0.0; }
  2423. if (z === void 0) { z = 0.0; }
  2424. if (w === void 0) { w = 1.0; }
  2425. this.x = x;
  2426. this.y = y;
  2427. this.z = z;
  2428. this.w = w;
  2429. }
  2430. /**
  2431. * Returns a string with the Quaternion coordinates.
  2432. */
  2433. Quaternion.prototype.toString = function () {
  2434. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2435. };
  2436. /**
  2437. * Returns the string "Quaternion".
  2438. */
  2439. Quaternion.prototype.getClassName = function () {
  2440. return "Quaternion";
  2441. };
  2442. /**
  2443. * Returns the Quaternion hash code.
  2444. */
  2445. Quaternion.prototype.getHashCode = function () {
  2446. var hash = this.x || 0;
  2447. hash = (hash * 397) ^ (this.y || 0);
  2448. hash = (hash * 397) ^ (this.z || 0);
  2449. hash = (hash * 397) ^ (this.w || 0);
  2450. return hash;
  2451. };
  2452. /**
  2453. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2454. */
  2455. Quaternion.prototype.asArray = function () {
  2456. return [this.x, this.y, this.z, this.w];
  2457. };
  2458. /**
  2459. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2460. */
  2461. Quaternion.prototype.equals = function (otherQuaternion) {
  2462. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2463. };
  2464. /**
  2465. * Returns a new Quaternion copied from the current one.
  2466. */
  2467. Quaternion.prototype.clone = function () {
  2468. return new Quaternion(this.x, this.y, this.z, this.w);
  2469. };
  2470. /**
  2471. * Updates the current Quaternion from the passed one coordinates.
  2472. * Returns the updated Quaterion.
  2473. */
  2474. Quaternion.prototype.copyFrom = function (other) {
  2475. this.x = other.x;
  2476. this.y = other.y;
  2477. this.z = other.z;
  2478. this.w = other.w;
  2479. return this;
  2480. };
  2481. /**
  2482. * Updates the current Quaternion from the passed float coordinates.
  2483. * Returns the updated Quaterion.
  2484. */
  2485. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2486. this.x = x;
  2487. this.y = y;
  2488. this.z = z;
  2489. this.w = w;
  2490. return this;
  2491. };
  2492. /**
  2493. * Updates the current Quaternion from the passed float coordinates.
  2494. * Returns the updated Quaterion.
  2495. */
  2496. Quaternion.prototype.set = function (x, y, z, w) {
  2497. return this.copyFromFloats(x, y, z, w);
  2498. };
  2499. /**
  2500. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2501. */
  2502. Quaternion.prototype.add = function (other) {
  2503. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2504. };
  2505. /**
  2506. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2507. */
  2508. Quaternion.prototype.subtract = function (other) {
  2509. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2510. };
  2511. /**
  2512. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2513. */
  2514. Quaternion.prototype.scale = function (value) {
  2515. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2516. };
  2517. /**
  2518. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2519. */
  2520. Quaternion.prototype.multiply = function (q1) {
  2521. var result = new Quaternion(0, 0, 0, 1.0);
  2522. this.multiplyToRef(q1, result);
  2523. return result;
  2524. };
  2525. /**
  2526. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2527. * Returns the current Quaternion.
  2528. */
  2529. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2530. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2531. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2532. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2533. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2534. result.copyFromFloats(x, y, z, w);
  2535. return this;
  2536. };
  2537. /**
  2538. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2539. * Returns the updated Quaternion.
  2540. */
  2541. Quaternion.prototype.multiplyInPlace = function (q1) {
  2542. this.multiplyToRef(q1, this);
  2543. return this;
  2544. };
  2545. /**
  2546. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2547. * Returns the current Quaternion.
  2548. */
  2549. Quaternion.prototype.conjugateToRef = function (ref) {
  2550. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2551. return this;
  2552. };
  2553. /**
  2554. * Conjugates in place the current Quaternion.
  2555. * Returns the updated Quaternion.
  2556. */
  2557. Quaternion.prototype.conjugateInPlace = function () {
  2558. this.x *= -1;
  2559. this.y *= -1;
  2560. this.z *= -1;
  2561. return this;
  2562. };
  2563. /**
  2564. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2565. */
  2566. Quaternion.prototype.conjugate = function () {
  2567. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2568. return result;
  2569. };
  2570. /**
  2571. * Returns the Quaternion length (float).
  2572. */
  2573. Quaternion.prototype.length = function () {
  2574. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2575. };
  2576. /**
  2577. * Normalize in place the current Quaternion.
  2578. * Returns the updated Quaternion.
  2579. */
  2580. Quaternion.prototype.normalize = function () {
  2581. var length = 1.0 / this.length();
  2582. this.x *= length;
  2583. this.y *= length;
  2584. this.z *= length;
  2585. this.w *= length;
  2586. return this;
  2587. };
  2588. /**
  2589. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2590. */
  2591. Quaternion.prototype.toEulerAngles = function (order) {
  2592. if (order === void 0) { order = "YZX"; }
  2593. var result = Vector3.Zero();
  2594. this.toEulerAnglesToRef(result, order);
  2595. return result;
  2596. };
  2597. /**
  2598. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2599. * Returns the current Quaternion.
  2600. */
  2601. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2602. if (order === void 0) { order = "YZX"; }
  2603. var qz = this.z;
  2604. var qx = this.x;
  2605. var qy = this.y;
  2606. var qw = this.w;
  2607. var sqw = qw * qw;
  2608. var sqz = qz * qz;
  2609. var sqx = qx * qx;
  2610. var sqy = qy * qy;
  2611. var zAxisY = qy * qz - qx * qw;
  2612. var limit = .4999999;
  2613. if (zAxisY < -limit) {
  2614. result.y = 2 * Math.atan2(qy, qw);
  2615. result.x = Math.PI / 2;
  2616. result.z = 0;
  2617. }
  2618. else if (zAxisY > limit) {
  2619. result.y = 2 * Math.atan2(qy, qw);
  2620. result.x = -Math.PI / 2;
  2621. result.z = 0;
  2622. }
  2623. else {
  2624. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2625. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2626. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2627. }
  2628. return this;
  2629. };
  2630. /**
  2631. * Updates the passed rotation matrix with the current Quaternion values.
  2632. * Returns the current Quaternion.
  2633. */
  2634. Quaternion.prototype.toRotationMatrix = function (result) {
  2635. var xx = this.x * this.x;
  2636. var yy = this.y * this.y;
  2637. var zz = this.z * this.z;
  2638. var xy = this.x * this.y;
  2639. var zw = this.z * this.w;
  2640. var zx = this.z * this.x;
  2641. var yw = this.y * this.w;
  2642. var yz = this.y * this.z;
  2643. var xw = this.x * this.w;
  2644. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2645. result.m[1] = 2.0 * (xy + zw);
  2646. result.m[2] = 2.0 * (zx - yw);
  2647. result.m[3] = 0;
  2648. result.m[4] = 2.0 * (xy - zw);
  2649. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2650. result.m[6] = 2.0 * (yz + xw);
  2651. result.m[7] = 0;
  2652. result.m[8] = 2.0 * (zx + yw);
  2653. result.m[9] = 2.0 * (yz - xw);
  2654. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2655. result.m[11] = 0;
  2656. result.m[12] = 0;
  2657. result.m[13] = 0;
  2658. result.m[14] = 0;
  2659. result.m[15] = 1.0;
  2660. result._markAsUpdated();
  2661. return this;
  2662. };
  2663. /**
  2664. * Updates the current Quaternion from the passed rotation matrix values.
  2665. * Returns the updated Quaternion.
  2666. */
  2667. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2668. Quaternion.FromRotationMatrixToRef(matrix, this);
  2669. return this;
  2670. };
  2671. // Statics
  2672. /**
  2673. * Returns a new Quaternion set from the passed rotation matrix values.
  2674. */
  2675. Quaternion.FromRotationMatrix = function (matrix) {
  2676. var result = new Quaternion();
  2677. Quaternion.FromRotationMatrixToRef(matrix, result);
  2678. return result;
  2679. };
  2680. /**
  2681. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2682. */
  2683. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2684. var data = matrix.m;
  2685. var m11 = data[0], m12 = data[4], m13 = data[8];
  2686. var m21 = data[1], m22 = data[5], m23 = data[9];
  2687. var m31 = data[2], m32 = data[6], m33 = data[10];
  2688. var trace = m11 + m22 + m33;
  2689. var s;
  2690. if (trace > 0) {
  2691. s = 0.5 / Math.sqrt(trace + 1.0);
  2692. result.w = 0.25 / s;
  2693. result.x = (m32 - m23) * s;
  2694. result.y = (m13 - m31) * s;
  2695. result.z = (m21 - m12) * s;
  2696. }
  2697. else if (m11 > m22 && m11 > m33) {
  2698. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2699. result.w = (m32 - m23) / s;
  2700. result.x = 0.25 * s;
  2701. result.y = (m12 + m21) / s;
  2702. result.z = (m13 + m31) / s;
  2703. }
  2704. else if (m22 > m33) {
  2705. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2706. result.w = (m13 - m31) / s;
  2707. result.x = (m12 + m21) / s;
  2708. result.y = 0.25 * s;
  2709. result.z = (m23 + m32) / s;
  2710. }
  2711. else {
  2712. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2713. result.w = (m21 - m12) / s;
  2714. result.x = (m13 + m31) / s;
  2715. result.y = (m23 + m32) / s;
  2716. result.z = 0.25 * s;
  2717. }
  2718. };
  2719. /**
  2720. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2721. */
  2722. Quaternion.Zero = function () {
  2723. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2724. };
  2725. /**
  2726. * Returns a new Quaternion as the inverted current Quaternion.
  2727. */
  2728. Quaternion.Inverse = function (q) {
  2729. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2730. };
  2731. /**
  2732. * Returns the identity Quaternion.
  2733. */
  2734. Quaternion.Identity = function () {
  2735. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2736. };
  2737. Quaternion.IsIdentity = function (quaternion) {
  2738. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2739. };
  2740. /**
  2741. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2742. */
  2743. Quaternion.RotationAxis = function (axis, angle) {
  2744. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2745. };
  2746. /**
  2747. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2748. */
  2749. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2750. var sin = Math.sin(angle / 2);
  2751. axis.normalize();
  2752. result.w = Math.cos(angle / 2);
  2753. result.x = axis.x * sin;
  2754. result.y = axis.y * sin;
  2755. result.z = axis.z * sin;
  2756. return result;
  2757. };
  2758. /**
  2759. * Retuns a new Quaternion set from the starting index of the passed array.
  2760. */
  2761. Quaternion.FromArray = function (array, offset) {
  2762. if (!offset) {
  2763. offset = 0;
  2764. }
  2765. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2766. };
  2767. /**
  2768. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2769. */
  2770. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2771. var q = new Quaternion();
  2772. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2773. return q;
  2774. };
  2775. /**
  2776. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2777. */
  2778. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2779. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2780. var halfRoll = roll * 0.5;
  2781. var halfPitch = pitch * 0.5;
  2782. var halfYaw = yaw * 0.5;
  2783. var sinRoll = Math.sin(halfRoll);
  2784. var cosRoll = Math.cos(halfRoll);
  2785. var sinPitch = Math.sin(halfPitch);
  2786. var cosPitch = Math.cos(halfPitch);
  2787. var sinYaw = Math.sin(halfYaw);
  2788. var cosYaw = Math.cos(halfYaw);
  2789. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2790. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2791. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2792. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2793. };
  2794. /**
  2795. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2796. */
  2797. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2798. var result = new Quaternion();
  2799. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2800. return result;
  2801. };
  2802. /**
  2803. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2804. */
  2805. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2806. // Produces a quaternion from Euler angles in the z-x-z orientation
  2807. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2808. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2809. var halfBeta = beta * 0.5;
  2810. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2811. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2812. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2813. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2814. };
  2815. /**
  2816. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2817. * cf to Vector3.RotationFromAxis() documentation.
  2818. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2819. */
  2820. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2821. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2822. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2823. return quat;
  2824. };
  2825. /**
  2826. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2827. * cf to Vector3.RotationFromAxis() documentation.
  2828. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2829. */
  2830. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2831. var rotMat = MathTmp.Matrix[0];
  2832. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2833. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2834. };
  2835. Quaternion.Slerp = function (left, right, amount) {
  2836. var result = Quaternion.Identity();
  2837. Quaternion.SlerpToRef(left, right, amount, result);
  2838. return result;
  2839. };
  2840. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2841. var num2;
  2842. var num3;
  2843. var num = amount;
  2844. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2845. var flag = false;
  2846. if (num4 < 0) {
  2847. flag = true;
  2848. num4 = -num4;
  2849. }
  2850. if (num4 > 0.999999) {
  2851. num3 = 1 - num;
  2852. num2 = flag ? -num : num;
  2853. }
  2854. else {
  2855. var num5 = Math.acos(num4);
  2856. var num6 = (1.0 / Math.sin(num5));
  2857. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2858. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2859. }
  2860. result.x = (num3 * left.x) + (num2 * right.x);
  2861. result.y = (num3 * left.y) + (num2 * right.y);
  2862. result.z = (num3 * left.z) + (num2 * right.z);
  2863. result.w = (num3 * left.w) + (num2 * right.w);
  2864. };
  2865. /**
  2866. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2867. */
  2868. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2869. var squared = amount * amount;
  2870. var cubed = amount * squared;
  2871. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2872. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2873. var part3 = (cubed - (2.0 * squared)) + amount;
  2874. var part4 = cubed - squared;
  2875. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2876. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2877. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2878. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2879. return new Quaternion(x, y, z, w);
  2880. };
  2881. return Quaternion;
  2882. }());
  2883. BABYLON.Quaternion = Quaternion;
  2884. var Matrix = /** @class */ (function () {
  2885. function Matrix() {
  2886. this._isIdentity = false;
  2887. this._isIdentityDirty = true;
  2888. this.m = new Float32Array(16);
  2889. this._markAsUpdated();
  2890. }
  2891. Matrix.prototype._markAsUpdated = function () {
  2892. this.updateFlag = Matrix._updateFlagSeed++;
  2893. this._isIdentityDirty = true;
  2894. };
  2895. // Properties
  2896. /**
  2897. * Boolean : True is the matrix is the identity matrix
  2898. */
  2899. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2900. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2901. if (this._isIdentityDirty) {
  2902. this._isIdentityDirty = false;
  2903. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2904. this._isIdentity = false;
  2905. }
  2906. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2907. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2908. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2909. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2910. this._isIdentity = false;
  2911. }
  2912. else {
  2913. this._isIdentity = true;
  2914. }
  2915. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2916. this._isIdentity = false;
  2917. }
  2918. }
  2919. return this._isIdentity;
  2920. };
  2921. /**
  2922. * Returns the matrix determinant (float).
  2923. */
  2924. Matrix.prototype.determinant = function () {
  2925. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2926. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2927. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2928. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2929. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2930. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2931. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2932. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2933. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2934. };
  2935. // Methods
  2936. /**
  2937. * Returns the matrix underlying array.
  2938. */
  2939. Matrix.prototype.toArray = function () {
  2940. return this.m;
  2941. };
  2942. /**
  2943. * Returns the matrix underlying array.
  2944. */
  2945. Matrix.prototype.asArray = function () {
  2946. return this.toArray();
  2947. };
  2948. /**
  2949. * Inverts in place the Matrix.
  2950. * Returns the Matrix inverted.
  2951. */
  2952. Matrix.prototype.invert = function () {
  2953. this.invertToRef(this);
  2954. return this;
  2955. };
  2956. /**
  2957. * Sets all the matrix elements to zero.
  2958. * Returns the Matrix.
  2959. */
  2960. Matrix.prototype.reset = function () {
  2961. for (var index = 0; index < 16; index++) {
  2962. this.m[index] = 0.0;
  2963. }
  2964. this._markAsUpdated();
  2965. return this;
  2966. };
  2967. /**
  2968. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2969. */
  2970. Matrix.prototype.add = function (other) {
  2971. var result = new Matrix();
  2972. this.addToRef(other, result);
  2973. return result;
  2974. };
  2975. /**
  2976. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2977. * Returns the Matrix.
  2978. */
  2979. Matrix.prototype.addToRef = function (other, result) {
  2980. for (var index = 0; index < 16; index++) {
  2981. result.m[index] = this.m[index] + other.m[index];
  2982. }
  2983. result._markAsUpdated();
  2984. return this;
  2985. };
  2986. /**
  2987. * Adds in place the passed matrix to the current Matrix.
  2988. * Returns the updated Matrix.
  2989. */
  2990. Matrix.prototype.addToSelf = function (other) {
  2991. for (var index = 0; index < 16; index++) {
  2992. this.m[index] += other.m[index];
  2993. }
  2994. this._markAsUpdated();
  2995. return this;
  2996. };
  2997. /**
  2998. * Sets the passed matrix with the current inverted Matrix.
  2999. * Returns the unmodified current Matrix.
  3000. */
  3001. Matrix.prototype.invertToRef = function (other) {
  3002. var l1 = this.m[0];
  3003. var l2 = this.m[1];
  3004. var l3 = this.m[2];
  3005. var l4 = this.m[3];
  3006. var l5 = this.m[4];
  3007. var l6 = this.m[5];
  3008. var l7 = this.m[6];
  3009. var l8 = this.m[7];
  3010. var l9 = this.m[8];
  3011. var l10 = this.m[9];
  3012. var l11 = this.m[10];
  3013. var l12 = this.m[11];
  3014. var l13 = this.m[12];
  3015. var l14 = this.m[13];
  3016. var l15 = this.m[14];
  3017. var l16 = this.m[15];
  3018. var l17 = (l11 * l16) - (l12 * l15);
  3019. var l18 = (l10 * l16) - (l12 * l14);
  3020. var l19 = (l10 * l15) - (l11 * l14);
  3021. var l20 = (l9 * l16) - (l12 * l13);
  3022. var l21 = (l9 * l15) - (l11 * l13);
  3023. var l22 = (l9 * l14) - (l10 * l13);
  3024. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3025. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3026. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3027. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3028. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3029. var l28 = (l7 * l16) - (l8 * l15);
  3030. var l29 = (l6 * l16) - (l8 * l14);
  3031. var l30 = (l6 * l15) - (l7 * l14);
  3032. var l31 = (l5 * l16) - (l8 * l13);
  3033. var l32 = (l5 * l15) - (l7 * l13);
  3034. var l33 = (l5 * l14) - (l6 * l13);
  3035. var l34 = (l7 * l12) - (l8 * l11);
  3036. var l35 = (l6 * l12) - (l8 * l10);
  3037. var l36 = (l6 * l11) - (l7 * l10);
  3038. var l37 = (l5 * l12) - (l8 * l9);
  3039. var l38 = (l5 * l11) - (l7 * l9);
  3040. var l39 = (l5 * l10) - (l6 * l9);
  3041. other.m[0] = l23 * l27;
  3042. other.m[4] = l24 * l27;
  3043. other.m[8] = l25 * l27;
  3044. other.m[12] = l26 * l27;
  3045. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3046. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3047. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3048. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3049. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3050. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3051. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3052. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3053. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3054. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3055. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3056. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3057. other._markAsUpdated();
  3058. return this;
  3059. };
  3060. /**
  3061. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3062. * Returns the updated Matrix.
  3063. */
  3064. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3065. this.m[12] = x;
  3066. this.m[13] = y;
  3067. this.m[14] = z;
  3068. this._markAsUpdated();
  3069. return this;
  3070. };
  3071. /**
  3072. * Inserts the translation vector in the current Matrix.
  3073. * Returns the updated Matrix.
  3074. */
  3075. Matrix.prototype.setTranslation = function (vector3) {
  3076. this.m[12] = vector3.x;
  3077. this.m[13] = vector3.y;
  3078. this.m[14] = vector3.z;
  3079. this._markAsUpdated();
  3080. return this;
  3081. };
  3082. /**
  3083. * Returns a new Vector3 as the extracted translation from the Matrix.
  3084. */
  3085. Matrix.prototype.getTranslation = function () {
  3086. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3087. };
  3088. /**
  3089. * Fill a Vector3 with the extracted translation from the Matrix.
  3090. */
  3091. Matrix.prototype.getTranslationToRef = function (result) {
  3092. result.x = this.m[12];
  3093. result.y = this.m[13];
  3094. result.z = this.m[14];
  3095. return this;
  3096. };
  3097. /**
  3098. * Remove rotation and scaling part from the Matrix.
  3099. * Returns the updated Matrix.
  3100. */
  3101. Matrix.prototype.removeRotationAndScaling = function () {
  3102. this.setRowFromFloats(0, 1, 0, 0, 0);
  3103. this.setRowFromFloats(1, 0, 1, 0, 0);
  3104. this.setRowFromFloats(2, 0, 0, 1, 0);
  3105. return this;
  3106. };
  3107. /**
  3108. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3109. */
  3110. Matrix.prototype.multiply = function (other) {
  3111. var result = new Matrix();
  3112. this.multiplyToRef(other, result);
  3113. return result;
  3114. };
  3115. /**
  3116. * Updates the current Matrix from the passed one values.
  3117. * Returns the updated Matrix.
  3118. */
  3119. Matrix.prototype.copyFrom = function (other) {
  3120. for (var index = 0; index < 16; index++) {
  3121. this.m[index] = other.m[index];
  3122. }
  3123. this._markAsUpdated();
  3124. return this;
  3125. };
  3126. /**
  3127. * Populates the passed array from the starting index with the Matrix values.
  3128. * Returns the Matrix.
  3129. */
  3130. Matrix.prototype.copyToArray = function (array, offset) {
  3131. if (offset === void 0) { offset = 0; }
  3132. for (var index = 0; index < 16; index++) {
  3133. array[offset + index] = this.m[index];
  3134. }
  3135. return this;
  3136. };
  3137. /**
  3138. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3139. */
  3140. Matrix.prototype.multiplyToRef = function (other, result) {
  3141. this.multiplyToArray(other, result.m, 0);
  3142. result._markAsUpdated();
  3143. return this;
  3144. };
  3145. /**
  3146. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3147. */
  3148. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3149. var tm0 = this.m[0];
  3150. var tm1 = this.m[1];
  3151. var tm2 = this.m[2];
  3152. var tm3 = this.m[3];
  3153. var tm4 = this.m[4];
  3154. var tm5 = this.m[5];
  3155. var tm6 = this.m[6];
  3156. var tm7 = this.m[7];
  3157. var tm8 = this.m[8];
  3158. var tm9 = this.m[9];
  3159. var tm10 = this.m[10];
  3160. var tm11 = this.m[11];
  3161. var tm12 = this.m[12];
  3162. var tm13 = this.m[13];
  3163. var tm14 = this.m[14];
  3164. var tm15 = this.m[15];
  3165. var om0 = other.m[0];
  3166. var om1 = other.m[1];
  3167. var om2 = other.m[2];
  3168. var om3 = other.m[3];
  3169. var om4 = other.m[4];
  3170. var om5 = other.m[5];
  3171. var om6 = other.m[6];
  3172. var om7 = other.m[7];
  3173. var om8 = other.m[8];
  3174. var om9 = other.m[9];
  3175. var om10 = other.m[10];
  3176. var om11 = other.m[11];
  3177. var om12 = other.m[12];
  3178. var om13 = other.m[13];
  3179. var om14 = other.m[14];
  3180. var om15 = other.m[15];
  3181. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3182. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3183. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3184. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3185. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3186. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3187. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3188. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3189. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3190. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3191. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3192. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3193. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3194. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3195. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3196. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3197. return this;
  3198. };
  3199. /**
  3200. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3201. */
  3202. Matrix.prototype.equals = function (value) {
  3203. return value &&
  3204. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3205. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3206. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3207. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3208. };
  3209. /**
  3210. * Returns a new Matrix from the current Matrix.
  3211. */
  3212. Matrix.prototype.clone = function () {
  3213. 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]);
  3214. };
  3215. /**
  3216. * Returns the string "Matrix"
  3217. */
  3218. Matrix.prototype.getClassName = function () {
  3219. return "Matrix";
  3220. };
  3221. /**
  3222. * Returns the Matrix hash code.
  3223. */
  3224. Matrix.prototype.getHashCode = function () {
  3225. var hash = this.m[0] || 0;
  3226. for (var i = 1; i < 16; i++) {
  3227. hash = (hash * 397) ^ (this.m[i] || 0);
  3228. }
  3229. return hash;
  3230. };
  3231. /**
  3232. * Decomposes the current Matrix into :
  3233. * - a scale vector3 passed as a reference to update,
  3234. * - a rotation quaternion passed as a reference to update,
  3235. * - a translation vector3 passed as a reference to update.
  3236. * Returns the boolean `true`.
  3237. */
  3238. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3239. translation.x = this.m[12];
  3240. translation.y = this.m[13];
  3241. translation.z = this.m[14];
  3242. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3243. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3244. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3245. if (this.determinant() <= 0) {
  3246. scale.y *= -1;
  3247. }
  3248. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3249. rotation.x = 0;
  3250. rotation.y = 0;
  3251. rotation.z = 0;
  3252. rotation.w = 1;
  3253. return false;
  3254. }
  3255. 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]);
  3256. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3257. return true;
  3258. };
  3259. /**
  3260. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3261. */
  3262. Matrix.prototype.getRotationMatrix = function () {
  3263. var result = Matrix.Identity();
  3264. this.getRotationMatrixToRef(result);
  3265. return result;
  3266. };
  3267. /**
  3268. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3269. * Returns the current Matrix.
  3270. */
  3271. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3272. var m = this.m;
  3273. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3274. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3275. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3276. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3277. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3278. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3279. 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);
  3280. return this;
  3281. };
  3282. // Statics
  3283. /**
  3284. * Returns a new Matrix set from the starting index of the passed array.
  3285. */
  3286. Matrix.FromArray = function (array, offset) {
  3287. var result = new Matrix();
  3288. if (!offset) {
  3289. offset = 0;
  3290. }
  3291. Matrix.FromArrayToRef(array, offset, result);
  3292. return result;
  3293. };
  3294. /**
  3295. * Sets the passed "result" matrix from the starting index of the passed array.
  3296. */
  3297. Matrix.FromArrayToRef = function (array, offset, result) {
  3298. for (var index = 0; index < 16; index++) {
  3299. result.m[index] = array[index + offset];
  3300. }
  3301. result._markAsUpdated();
  3302. };
  3303. /**
  3304. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3305. */
  3306. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3307. for (var index = 0; index < 16; index++) {
  3308. result.m[index] = array[index + offset] * scale;
  3309. }
  3310. result._markAsUpdated();
  3311. };
  3312. /**
  3313. * Sets the passed matrix "result" with the 16 passed floats.
  3314. */
  3315. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3316. result.m[0] = initialM11;
  3317. result.m[1] = initialM12;
  3318. result.m[2] = initialM13;
  3319. result.m[3] = initialM14;
  3320. result.m[4] = initialM21;
  3321. result.m[5] = initialM22;
  3322. result.m[6] = initialM23;
  3323. result.m[7] = initialM24;
  3324. result.m[8] = initialM31;
  3325. result.m[9] = initialM32;
  3326. result.m[10] = initialM33;
  3327. result.m[11] = initialM34;
  3328. result.m[12] = initialM41;
  3329. result.m[13] = initialM42;
  3330. result.m[14] = initialM43;
  3331. result.m[15] = initialM44;
  3332. result._markAsUpdated();
  3333. };
  3334. /**
  3335. * Returns the index-th row of the current matrix as a new Vector4.
  3336. */
  3337. Matrix.prototype.getRow = function (index) {
  3338. if (index < 0 || index > 3) {
  3339. return null;
  3340. }
  3341. var i = index * 4;
  3342. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3343. };
  3344. /**
  3345. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3346. * Returns the updated Matrix.
  3347. */
  3348. Matrix.prototype.setRow = function (index, row) {
  3349. if (index < 0 || index > 3) {
  3350. return this;
  3351. }
  3352. var i = index * 4;
  3353. this.m[i + 0] = row.x;
  3354. this.m[i + 1] = row.y;
  3355. this.m[i + 2] = row.z;
  3356. this.m[i + 3] = row.w;
  3357. this._markAsUpdated();
  3358. return this;
  3359. };
  3360. /**
  3361. * Compute the transpose of the matrix.
  3362. * Returns a new Matrix.
  3363. */
  3364. Matrix.prototype.transpose = function () {
  3365. return Matrix.Transpose(this);
  3366. };
  3367. /**
  3368. * Compute the transpose of the matrix.
  3369. * Returns the current matrix.
  3370. */
  3371. Matrix.prototype.transposeToRef = function (result) {
  3372. Matrix.TransposeToRef(this, result);
  3373. return this;
  3374. };
  3375. /**
  3376. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3377. * Returns the updated Matrix.
  3378. */
  3379. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3380. if (index < 0 || index > 3) {
  3381. return this;
  3382. }
  3383. var i = index * 4;
  3384. this.m[i + 0] = x;
  3385. this.m[i + 1] = y;
  3386. this.m[i + 2] = z;
  3387. this.m[i + 3] = w;
  3388. this._markAsUpdated();
  3389. return this;
  3390. };
  3391. Object.defineProperty(Matrix, "IdentityReadOnly", {
  3392. /**
  3393. * Static identity matrix to be used as readonly matrix
  3394. * Must not be updated.
  3395. */
  3396. get: function () {
  3397. return Matrix._identityReadOnly;
  3398. },
  3399. enumerable: true,
  3400. configurable: true
  3401. });
  3402. /**
  3403. * Returns a new Matrix set from the 16 passed floats.
  3404. */
  3405. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3406. var result = new Matrix();
  3407. result.m[0] = initialM11;
  3408. result.m[1] = initialM12;
  3409. result.m[2] = initialM13;
  3410. result.m[3] = initialM14;
  3411. result.m[4] = initialM21;
  3412. result.m[5] = initialM22;
  3413. result.m[6] = initialM23;
  3414. result.m[7] = initialM24;
  3415. result.m[8] = initialM31;
  3416. result.m[9] = initialM32;
  3417. result.m[10] = initialM33;
  3418. result.m[11] = initialM34;
  3419. result.m[12] = initialM41;
  3420. result.m[13] = initialM42;
  3421. result.m[14] = initialM43;
  3422. result.m[15] = initialM44;
  3423. return result;
  3424. };
  3425. /**
  3426. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3427. */
  3428. Matrix.Compose = function (scale, rotation, translation) {
  3429. var result = Matrix.Identity();
  3430. Matrix.ComposeToRef(scale, rotation, translation, result);
  3431. return result;
  3432. };
  3433. /**
  3434. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3435. */
  3436. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3437. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3438. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3439. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3440. result.setTranslation(translation);
  3441. };
  3442. /**
  3443. * Returns a new indentity Matrix.
  3444. */
  3445. Matrix.Identity = function () {
  3446. 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);
  3447. };
  3448. /**
  3449. * Sets the passed "result" as an identity matrix.
  3450. */
  3451. Matrix.IdentityToRef = function (result) {
  3452. 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);
  3453. };
  3454. /**
  3455. * Returns a new zero Matrix.
  3456. */
  3457. Matrix.Zero = function () {
  3458. 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);
  3459. };
  3460. /**
  3461. * Returns a new rotation matrix for "angle" radians around the X axis.
  3462. */
  3463. Matrix.RotationX = function (angle) {
  3464. var result = new Matrix();
  3465. Matrix.RotationXToRef(angle, result);
  3466. return result;
  3467. };
  3468. /**
  3469. * Returns a new Matrix as the passed inverted one.
  3470. */
  3471. Matrix.Invert = function (source) {
  3472. var result = new Matrix();
  3473. source.invertToRef(result);
  3474. return result;
  3475. };
  3476. /**
  3477. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3478. */
  3479. Matrix.RotationXToRef = function (angle, result) {
  3480. var s = Math.sin(angle);
  3481. var c = Math.cos(angle);
  3482. result.m[0] = 1.0;
  3483. result.m[15] = 1.0;
  3484. result.m[5] = c;
  3485. result.m[10] = c;
  3486. result.m[9] = -s;
  3487. result.m[6] = s;
  3488. result.m[1] = 0.0;
  3489. result.m[2] = 0.0;
  3490. result.m[3] = 0.0;
  3491. result.m[4] = 0.0;
  3492. result.m[7] = 0.0;
  3493. result.m[8] = 0.0;
  3494. result.m[11] = 0.0;
  3495. result.m[12] = 0.0;
  3496. result.m[13] = 0.0;
  3497. result.m[14] = 0.0;
  3498. result._markAsUpdated();
  3499. };
  3500. /**
  3501. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3502. */
  3503. Matrix.RotationY = function (angle) {
  3504. var result = new Matrix();
  3505. Matrix.RotationYToRef(angle, result);
  3506. return result;
  3507. };
  3508. /**
  3509. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3510. */
  3511. Matrix.RotationYToRef = function (angle, result) {
  3512. var s = Math.sin(angle);
  3513. var c = Math.cos(angle);
  3514. result.m[5] = 1.0;
  3515. result.m[15] = 1.0;
  3516. result.m[0] = c;
  3517. result.m[2] = -s;
  3518. result.m[8] = s;
  3519. result.m[10] = c;
  3520. result.m[1] = 0.0;
  3521. result.m[3] = 0.0;
  3522. result.m[4] = 0.0;
  3523. result.m[6] = 0.0;
  3524. result.m[7] = 0.0;
  3525. result.m[9] = 0.0;
  3526. result.m[11] = 0.0;
  3527. result.m[12] = 0.0;
  3528. result.m[13] = 0.0;
  3529. result.m[14] = 0.0;
  3530. result._markAsUpdated();
  3531. };
  3532. /**
  3533. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3534. */
  3535. Matrix.RotationZ = function (angle) {
  3536. var result = new Matrix();
  3537. Matrix.RotationZToRef(angle, result);
  3538. return result;
  3539. };
  3540. /**
  3541. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3542. */
  3543. Matrix.RotationZToRef = function (angle, result) {
  3544. var s = Math.sin(angle);
  3545. var c = Math.cos(angle);
  3546. result.m[10] = 1.0;
  3547. result.m[15] = 1.0;
  3548. result.m[0] = c;
  3549. result.m[1] = s;
  3550. result.m[4] = -s;
  3551. result.m[5] = c;
  3552. result.m[2] = 0.0;
  3553. result.m[3] = 0.0;
  3554. result.m[6] = 0.0;
  3555. result.m[7] = 0.0;
  3556. result.m[8] = 0.0;
  3557. result.m[9] = 0.0;
  3558. result.m[11] = 0.0;
  3559. result.m[12] = 0.0;
  3560. result.m[13] = 0.0;
  3561. result.m[14] = 0.0;
  3562. result._markAsUpdated();
  3563. };
  3564. /**
  3565. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3566. */
  3567. Matrix.RotationAxis = function (axis, angle) {
  3568. var result = Matrix.Zero();
  3569. Matrix.RotationAxisToRef(axis, angle, result);
  3570. return result;
  3571. };
  3572. /**
  3573. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3574. */
  3575. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3576. var s = Math.sin(-angle);
  3577. var c = Math.cos(-angle);
  3578. var c1 = 1 - c;
  3579. axis.normalize();
  3580. result.m[0] = (axis.x * axis.x) * c1 + c;
  3581. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3582. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3583. result.m[3] = 0.0;
  3584. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3585. result.m[5] = (axis.y * axis.y) * c1 + c;
  3586. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3587. result.m[7] = 0.0;
  3588. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3589. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3590. result.m[10] = (axis.z * axis.z) * c1 + c;
  3591. result.m[11] = 0.0;
  3592. result.m[15] = 1.0;
  3593. result._markAsUpdated();
  3594. };
  3595. /**
  3596. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3597. */
  3598. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3599. var result = new Matrix();
  3600. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3601. return result;
  3602. };
  3603. /**
  3604. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3605. */
  3606. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3607. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3608. this._tempQuaternion.toRotationMatrix(result);
  3609. };
  3610. /**
  3611. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3612. */
  3613. Matrix.Scaling = function (x, y, z) {
  3614. var result = Matrix.Zero();
  3615. Matrix.ScalingToRef(x, y, z, result);
  3616. return result;
  3617. };
  3618. /**
  3619. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3620. */
  3621. Matrix.ScalingToRef = function (x, y, z, result) {
  3622. result.m[0] = x;
  3623. result.m[1] = 0.0;
  3624. result.m[2] = 0.0;
  3625. result.m[3] = 0.0;
  3626. result.m[4] = 0.0;
  3627. result.m[5] = y;
  3628. result.m[6] = 0.0;
  3629. result.m[7] = 0.0;
  3630. result.m[8] = 0.0;
  3631. result.m[9] = 0.0;
  3632. result.m[10] = z;
  3633. result.m[11] = 0.0;
  3634. result.m[12] = 0.0;
  3635. result.m[13] = 0.0;
  3636. result.m[14] = 0.0;
  3637. result.m[15] = 1.0;
  3638. result._markAsUpdated();
  3639. };
  3640. /**
  3641. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3642. */
  3643. Matrix.Translation = function (x, y, z) {
  3644. var result = Matrix.Identity();
  3645. Matrix.TranslationToRef(x, y, z, result);
  3646. return result;
  3647. };
  3648. /**
  3649. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3650. */
  3651. Matrix.TranslationToRef = function (x, y, z, result) {
  3652. 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);
  3653. };
  3654. /**
  3655. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3656. */
  3657. Matrix.Lerp = function (startValue, endValue, gradient) {
  3658. var result = Matrix.Zero();
  3659. for (var index = 0; index < 16; index++) {
  3660. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3661. }
  3662. result._markAsUpdated();
  3663. return result;
  3664. };
  3665. /**
  3666. * Returns a new Matrix whose values are computed by :
  3667. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3668. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3669. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3670. */
  3671. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3672. var startScale = new Vector3(0, 0, 0);
  3673. var startRotation = new Quaternion();
  3674. var startTranslation = new Vector3(0, 0, 0);
  3675. startValue.decompose(startScale, startRotation, startTranslation);
  3676. var endScale = new Vector3(0, 0, 0);
  3677. var endRotation = new Quaternion();
  3678. var endTranslation = new Vector3(0, 0, 0);
  3679. endValue.decompose(endScale, endRotation, endTranslation);
  3680. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3681. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3682. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3683. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3684. };
  3685. /**
  3686. * 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".
  3687. * This methods works for a Left-Handed system.
  3688. */
  3689. Matrix.LookAtLH = function (eye, target, up) {
  3690. var result = Matrix.Zero();
  3691. Matrix.LookAtLHToRef(eye, target, up, result);
  3692. return result;
  3693. };
  3694. /**
  3695. * 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".
  3696. * This methods works for a Left-Handed system.
  3697. */
  3698. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3699. // Z axis
  3700. target.subtractToRef(eye, this._zAxis);
  3701. this._zAxis.normalize();
  3702. // X axis
  3703. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3704. if (this._xAxis.lengthSquared() === 0) {
  3705. this._xAxis.x = 1.0;
  3706. }
  3707. else {
  3708. this._xAxis.normalize();
  3709. }
  3710. // Y axis
  3711. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3712. this._yAxis.normalize();
  3713. // Eye angles
  3714. var ex = -Vector3.Dot(this._xAxis, eye);
  3715. var ey = -Vector3.Dot(this._yAxis, eye);
  3716. var ez = -Vector3.Dot(this._zAxis, eye);
  3717. 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);
  3718. };
  3719. /**
  3720. * 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".
  3721. * This methods works for a Right-Handed system.
  3722. */
  3723. Matrix.LookAtRH = function (eye, target, up) {
  3724. var result = Matrix.Zero();
  3725. Matrix.LookAtRHToRef(eye, target, up, result);
  3726. return result;
  3727. };
  3728. /**
  3729. * 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".
  3730. * This methods works for a Left-Handed system.
  3731. */
  3732. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3733. // Z axis
  3734. eye.subtractToRef(target, this._zAxis);
  3735. this._zAxis.normalize();
  3736. // X axis
  3737. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3738. if (this._xAxis.lengthSquared() === 0) {
  3739. this._xAxis.x = 1.0;
  3740. }
  3741. else {
  3742. this._xAxis.normalize();
  3743. }
  3744. // Y axis
  3745. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3746. this._yAxis.normalize();
  3747. // Eye angles
  3748. var ex = -Vector3.Dot(this._xAxis, eye);
  3749. var ey = -Vector3.Dot(this._yAxis, eye);
  3750. var ez = -Vector3.Dot(this._zAxis, eye);
  3751. 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);
  3752. };
  3753. /**
  3754. * 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.
  3755. */
  3756. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3757. var matrix = Matrix.Zero();
  3758. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3759. return matrix;
  3760. };
  3761. /**
  3762. * 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.
  3763. */
  3764. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3765. var n = znear;
  3766. var f = zfar;
  3767. var a = 2.0 / width;
  3768. var b = 2.0 / height;
  3769. var c = 2.0 / (f - n);
  3770. var d = -(f + n) / (f - n);
  3771. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3772. };
  3773. /**
  3774. * 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.
  3775. */
  3776. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3777. var matrix = Matrix.Zero();
  3778. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3779. return matrix;
  3780. };
  3781. /**
  3782. * 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.
  3783. */
  3784. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3785. var n = znear;
  3786. var f = zfar;
  3787. var a = 2.0 / (right - left);
  3788. var b = 2.0 / (top - bottom);
  3789. var c = 2.0 / (f - n);
  3790. var d = -(f + n) / (f - n);
  3791. var i0 = (left + right) / (left - right);
  3792. var i1 = (top + bottom) / (bottom - top);
  3793. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3794. };
  3795. /**
  3796. * 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.
  3797. */
  3798. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3799. var matrix = Matrix.Zero();
  3800. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3801. return matrix;
  3802. };
  3803. /**
  3804. * 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.
  3805. */
  3806. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3807. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3808. result.m[10] *= -1.0;
  3809. };
  3810. /**
  3811. * 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.
  3812. */
  3813. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3814. var matrix = Matrix.Zero();
  3815. var n = znear;
  3816. var f = zfar;
  3817. var a = 2.0 * n / width;
  3818. var b = 2.0 * n / height;
  3819. var c = (f + n) / (f - n);
  3820. var d = -2.0 * f * n / (f - n);
  3821. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3822. return matrix;
  3823. };
  3824. /**
  3825. * 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.
  3826. */
  3827. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3828. var matrix = Matrix.Zero();
  3829. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3830. return matrix;
  3831. };
  3832. /**
  3833. * 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.
  3834. */
  3835. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3836. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3837. var n = znear;
  3838. var f = zfar;
  3839. var t = 1.0 / (Math.tan(fov * 0.5));
  3840. var a = isVerticalFovFixed ? (t / aspect) : t;
  3841. var b = isVerticalFovFixed ? t : (t * aspect);
  3842. var c = (f + n) / (f - n);
  3843. var d = -2.0 * f * n / (f - n);
  3844. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3845. };
  3846. /**
  3847. * 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.
  3848. */
  3849. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3850. var matrix = Matrix.Zero();
  3851. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3852. return matrix;
  3853. };
  3854. /**
  3855. * 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.
  3856. */
  3857. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3858. //alternatively this could be expressed as:
  3859. // m = PerspectiveFovLHToRef
  3860. // m[10] *= -1.0;
  3861. // m[11] *= -1.0;
  3862. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3863. var n = znear;
  3864. var f = zfar;
  3865. var t = 1.0 / (Math.tan(fov * 0.5));
  3866. var a = isVerticalFovFixed ? (t / aspect) : t;
  3867. var b = isVerticalFovFixed ? t : (t * aspect);
  3868. var c = -(f + n) / (f - n);
  3869. var d = -2 * f * n / (f - n);
  3870. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3871. };
  3872. /**
  3873. * 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.
  3874. */
  3875. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3876. if (rightHanded === void 0) { rightHanded = false; }
  3877. var rightHandedFactor = rightHanded ? -1 : 1;
  3878. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3879. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3880. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3881. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3882. var xScale = 2.0 / (leftTan + rightTan);
  3883. var yScale = 2.0 / (upTan + downTan);
  3884. result.m[0] = xScale;
  3885. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3886. result.m[5] = yScale;
  3887. result.m[6] = result.m[7] = 0.0;
  3888. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3889. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3890. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3891. result.m[10] = -zfar / (znear - zfar);
  3892. result.m[11] = 1.0 * rightHandedFactor;
  3893. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3894. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3895. // result.m[14] = (znear * zfar) / (znear - zfar);
  3896. result._markAsUpdated();
  3897. };
  3898. /**
  3899. * Returns the final transformation matrix : world * view * projection * viewport
  3900. */
  3901. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3902. var cw = viewport.width;
  3903. var ch = viewport.height;
  3904. var cx = viewport.x;
  3905. var cy = viewport.y;
  3906. 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);
  3907. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3908. };
  3909. /**
  3910. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3911. */
  3912. Matrix.GetAsMatrix2x2 = function (matrix) {
  3913. return new Float32Array([
  3914. matrix.m[0], matrix.m[1],
  3915. matrix.m[4], matrix.m[5]
  3916. ]);
  3917. };
  3918. /**
  3919. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3920. */
  3921. Matrix.GetAsMatrix3x3 = function (matrix) {
  3922. return new Float32Array([
  3923. matrix.m[0], matrix.m[1], matrix.m[2],
  3924. matrix.m[4], matrix.m[5], matrix.m[6],
  3925. matrix.m[8], matrix.m[9], matrix.m[10]
  3926. ]);
  3927. };
  3928. /**
  3929. * Compute the transpose of the passed Matrix.
  3930. * Returns a new Matrix.
  3931. */
  3932. Matrix.Transpose = function (matrix) {
  3933. var result = new Matrix();
  3934. Matrix.TransposeToRef(matrix, result);
  3935. return result;
  3936. };
  3937. /**
  3938. * Compute the transpose of the passed Matrix and store it in the result matrix.
  3939. */
  3940. Matrix.TransposeToRef = function (matrix, result) {
  3941. result.m[0] = matrix.m[0];
  3942. result.m[1] = matrix.m[4];
  3943. result.m[2] = matrix.m[8];
  3944. result.m[3] = matrix.m[12];
  3945. result.m[4] = matrix.m[1];
  3946. result.m[5] = matrix.m[5];
  3947. result.m[6] = matrix.m[9];
  3948. result.m[7] = matrix.m[13];
  3949. result.m[8] = matrix.m[2];
  3950. result.m[9] = matrix.m[6];
  3951. result.m[10] = matrix.m[10];
  3952. result.m[11] = matrix.m[14];
  3953. result.m[12] = matrix.m[3];
  3954. result.m[13] = matrix.m[7];
  3955. result.m[14] = matrix.m[11];
  3956. result.m[15] = matrix.m[15];
  3957. };
  3958. /**
  3959. * Returns a new Matrix as the reflection matrix across the passed plane.
  3960. */
  3961. Matrix.Reflection = function (plane) {
  3962. var matrix = new Matrix();
  3963. Matrix.ReflectionToRef(plane, matrix);
  3964. return matrix;
  3965. };
  3966. /**
  3967. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3968. */
  3969. Matrix.ReflectionToRef = function (plane, result) {
  3970. plane.normalize();
  3971. var x = plane.normal.x;
  3972. var y = plane.normal.y;
  3973. var z = plane.normal.z;
  3974. var temp = -2 * x;
  3975. var temp2 = -2 * y;
  3976. var temp3 = -2 * z;
  3977. result.m[0] = (temp * x) + 1;
  3978. result.m[1] = temp2 * x;
  3979. result.m[2] = temp3 * x;
  3980. result.m[3] = 0.0;
  3981. result.m[4] = temp * y;
  3982. result.m[5] = (temp2 * y) + 1;
  3983. result.m[6] = temp3 * y;
  3984. result.m[7] = 0.0;
  3985. result.m[8] = temp * z;
  3986. result.m[9] = temp2 * z;
  3987. result.m[10] = (temp3 * z) + 1;
  3988. result.m[11] = 0.0;
  3989. result.m[12] = temp * plane.d;
  3990. result.m[13] = temp2 * plane.d;
  3991. result.m[14] = temp3 * plane.d;
  3992. result.m[15] = 1.0;
  3993. result._markAsUpdated();
  3994. };
  3995. /**
  3996. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3997. */
  3998. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3999. result.m[0] = xaxis.x;
  4000. result.m[1] = xaxis.y;
  4001. result.m[2] = xaxis.z;
  4002. result.m[3] = 0.0;
  4003. result.m[4] = yaxis.x;
  4004. result.m[5] = yaxis.y;
  4005. result.m[6] = yaxis.z;
  4006. result.m[7] = 0.0;
  4007. result.m[8] = zaxis.x;
  4008. result.m[9] = zaxis.y;
  4009. result.m[10] = zaxis.z;
  4010. result.m[11] = 0.0;
  4011. result.m[12] = 0.0;
  4012. result.m[13] = 0.0;
  4013. result.m[14] = 0.0;
  4014. result.m[15] = 1.0;
  4015. result._markAsUpdated();
  4016. };
  4017. /**
  4018. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4019. */
  4020. Matrix.FromQuaternionToRef = function (quat, result) {
  4021. var xx = quat.x * quat.x;
  4022. var yy = quat.y * quat.y;
  4023. var zz = quat.z * quat.z;
  4024. var xy = quat.x * quat.y;
  4025. var zw = quat.z * quat.w;
  4026. var zx = quat.z * quat.x;
  4027. var yw = quat.y * quat.w;
  4028. var yz = quat.y * quat.z;
  4029. var xw = quat.x * quat.w;
  4030. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4031. result.m[1] = 2.0 * (xy + zw);
  4032. result.m[2] = 2.0 * (zx - yw);
  4033. result.m[3] = 0.0;
  4034. result.m[4] = 2.0 * (xy - zw);
  4035. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4036. result.m[6] = 2.0 * (yz + xw);
  4037. result.m[7] = 0.0;
  4038. result.m[8] = 2.0 * (zx + yw);
  4039. result.m[9] = 2.0 * (yz - xw);
  4040. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4041. result.m[11] = 0.0;
  4042. result.m[12] = 0.0;
  4043. result.m[13] = 0.0;
  4044. result.m[14] = 0.0;
  4045. result.m[15] = 1.0;
  4046. result._markAsUpdated();
  4047. };
  4048. Matrix._tempQuaternion = new Quaternion();
  4049. Matrix._xAxis = Vector3.Zero();
  4050. Matrix._yAxis = Vector3.Zero();
  4051. Matrix._zAxis = Vector3.Zero();
  4052. Matrix._updateFlagSeed = 0;
  4053. Matrix._identityReadOnly = Matrix.Identity();
  4054. return Matrix;
  4055. }());
  4056. BABYLON.Matrix = Matrix;
  4057. var Plane = /** @class */ (function () {
  4058. /**
  4059. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4060. */
  4061. function Plane(a, b, c, d) {
  4062. this.normal = new Vector3(a, b, c);
  4063. this.d = d;
  4064. }
  4065. /**
  4066. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4067. */
  4068. Plane.prototype.asArray = function () {
  4069. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4070. };
  4071. // Methods
  4072. /**
  4073. * Returns a new plane copied from the current Plane.
  4074. */
  4075. Plane.prototype.clone = function () {
  4076. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4077. };
  4078. /**
  4079. * Returns the string "Plane".
  4080. */
  4081. Plane.prototype.getClassName = function () {
  4082. return "Plane";
  4083. };
  4084. /**
  4085. * Returns the Plane hash code.
  4086. */
  4087. Plane.prototype.getHashCode = function () {
  4088. var hash = this.normal.getHashCode();
  4089. hash = (hash * 397) ^ (this.d || 0);
  4090. return hash;
  4091. };
  4092. /**
  4093. * Normalize the current Plane in place.
  4094. * Returns the updated Plane.
  4095. */
  4096. Plane.prototype.normalize = function () {
  4097. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4098. var magnitude = 0.0;
  4099. if (norm !== 0) {
  4100. magnitude = 1.0 / norm;
  4101. }
  4102. this.normal.x *= magnitude;
  4103. this.normal.y *= magnitude;
  4104. this.normal.z *= magnitude;
  4105. this.d *= magnitude;
  4106. return this;
  4107. };
  4108. /**
  4109. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4110. */
  4111. Plane.prototype.transform = function (transformation) {
  4112. var transposedMatrix = Matrix.Transpose(transformation);
  4113. var x = this.normal.x;
  4114. var y = this.normal.y;
  4115. var z = this.normal.z;
  4116. var d = this.d;
  4117. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4118. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4119. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4120. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4121. return new Plane(normalX, normalY, normalZ, finalD);
  4122. };
  4123. /**
  4124. * Returns the dot product (float) of the point coordinates and the plane normal.
  4125. */
  4126. Plane.prototype.dotCoordinate = function (point) {
  4127. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4128. };
  4129. /**
  4130. * Updates the current Plane from the plane defined by the three passed points.
  4131. * Returns the updated Plane.
  4132. */
  4133. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4134. var x1 = point2.x - point1.x;
  4135. var y1 = point2.y - point1.y;
  4136. var z1 = point2.z - point1.z;
  4137. var x2 = point3.x - point1.x;
  4138. var y2 = point3.y - point1.y;
  4139. var z2 = point3.z - point1.z;
  4140. var yz = (y1 * z2) - (z1 * y2);
  4141. var xz = (z1 * x2) - (x1 * z2);
  4142. var xy = (x1 * y2) - (y1 * x2);
  4143. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4144. var invPyth;
  4145. if (pyth !== 0) {
  4146. invPyth = 1.0 / pyth;
  4147. }
  4148. else {
  4149. invPyth = 0.0;
  4150. }
  4151. this.normal.x = yz * invPyth;
  4152. this.normal.y = xz * invPyth;
  4153. this.normal.z = xy * invPyth;
  4154. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4155. return this;
  4156. };
  4157. /**
  4158. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4159. */
  4160. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4161. var dot = Vector3.Dot(this.normal, direction);
  4162. return (dot <= epsilon);
  4163. };
  4164. /**
  4165. * Returns the signed distance (float) from the passed point to the Plane.
  4166. */
  4167. Plane.prototype.signedDistanceTo = function (point) {
  4168. return Vector3.Dot(point, this.normal) + this.d;
  4169. };
  4170. // Statics
  4171. /**
  4172. * Returns a new Plane from the passed array.
  4173. */
  4174. Plane.FromArray = function (array) {
  4175. return new Plane(array[0], array[1], array[2], array[3]);
  4176. };
  4177. /**
  4178. * Returns a new Plane defined by the three passed points.
  4179. */
  4180. Plane.FromPoints = function (point1, point2, point3) {
  4181. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4182. result.copyFromPoints(point1, point2, point3);
  4183. return result;
  4184. };
  4185. /**
  4186. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4187. * Note : the vector "normal" is updated because normalized.
  4188. */
  4189. Plane.FromPositionAndNormal = function (origin, normal) {
  4190. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4191. normal.normalize();
  4192. result.normal = normal;
  4193. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4194. return result;
  4195. };
  4196. /**
  4197. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4198. */
  4199. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4200. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4201. return Vector3.Dot(point, normal) + d;
  4202. };
  4203. return Plane;
  4204. }());
  4205. BABYLON.Plane = Plane;
  4206. var Viewport = /** @class */ (function () {
  4207. /**
  4208. * Creates a Viewport object located at (x, y) and sized (width, height).
  4209. */
  4210. function Viewport(x, y, width, height) {
  4211. this.x = x;
  4212. this.y = y;
  4213. this.width = width;
  4214. this.height = height;
  4215. }
  4216. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4217. if (renderWidthOrEngine.getRenderWidth) {
  4218. var engine = renderWidthOrEngine;
  4219. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4220. }
  4221. var renderWidth = renderWidthOrEngine;
  4222. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4223. };
  4224. /**
  4225. * Returns a new Viewport copied from the current one.
  4226. */
  4227. Viewport.prototype.clone = function () {
  4228. return new Viewport(this.x, this.y, this.width, this.height);
  4229. };
  4230. return Viewport;
  4231. }());
  4232. BABYLON.Viewport = Viewport;
  4233. var Frustum = /** @class */ (function () {
  4234. function Frustum() {
  4235. }
  4236. /**
  4237. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4238. */
  4239. Frustum.GetPlanes = function (transform) {
  4240. var frustumPlanes = [];
  4241. for (var index = 0; index < 6; index++) {
  4242. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4243. }
  4244. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4245. return frustumPlanes;
  4246. };
  4247. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4248. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4249. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4250. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4251. frustumPlane.d = transform.m[15] + transform.m[14];
  4252. frustumPlane.normalize();
  4253. };
  4254. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4255. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4256. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4257. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4258. frustumPlane.d = transform.m[15] - transform.m[14];
  4259. frustumPlane.normalize();
  4260. };
  4261. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4262. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4263. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4264. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4265. frustumPlane.d = transform.m[15] + transform.m[12];
  4266. frustumPlane.normalize();
  4267. };
  4268. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4269. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4270. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4271. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4272. frustumPlane.d = transform.m[15] - transform.m[12];
  4273. frustumPlane.normalize();
  4274. };
  4275. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4276. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4277. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4278. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4279. frustumPlane.d = transform.m[15] - transform.m[13];
  4280. frustumPlane.normalize();
  4281. };
  4282. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4283. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4284. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4285. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4286. frustumPlane.d = transform.m[15] + transform.m[13];
  4287. frustumPlane.normalize();
  4288. };
  4289. /**
  4290. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4291. */
  4292. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4293. // Near
  4294. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4295. // Far
  4296. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4297. // Left
  4298. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4299. // Right
  4300. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4301. // Top
  4302. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4303. // Bottom
  4304. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4305. };
  4306. return Frustum;
  4307. }());
  4308. BABYLON.Frustum = Frustum;
  4309. var Space;
  4310. (function (Space) {
  4311. Space[Space["LOCAL"] = 0] = "LOCAL";
  4312. Space[Space["WORLD"] = 1] = "WORLD";
  4313. Space[Space["BONE"] = 2] = "BONE";
  4314. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4315. var Axis = /** @class */ (function () {
  4316. function Axis() {
  4317. }
  4318. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4319. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4320. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4321. return Axis;
  4322. }());
  4323. BABYLON.Axis = Axis;
  4324. ;
  4325. var BezierCurve = /** @class */ (function () {
  4326. function BezierCurve() {
  4327. }
  4328. /**
  4329. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4330. */
  4331. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4332. // Extract X (which is equal to time here)
  4333. var f0 = 1 - 3 * x2 + 3 * x1;
  4334. var f1 = 3 * x2 - 6 * x1;
  4335. var f2 = 3 * x1;
  4336. var refinedT = t;
  4337. for (var i = 0; i < 5; i++) {
  4338. var refinedT2 = refinedT * refinedT;
  4339. var refinedT3 = refinedT2 * refinedT;
  4340. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4341. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4342. refinedT -= (x - t) * slope;
  4343. refinedT = Math.min(1, Math.max(0, refinedT));
  4344. }
  4345. // Resolve cubic bezier for the given x
  4346. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4347. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4348. Math.pow(refinedT, 3);
  4349. };
  4350. return BezierCurve;
  4351. }());
  4352. BABYLON.BezierCurve = BezierCurve;
  4353. var Orientation;
  4354. (function (Orientation) {
  4355. Orientation[Orientation["CW"] = 0] = "CW";
  4356. Orientation[Orientation["CCW"] = 1] = "CCW";
  4357. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4358. var Angle = /** @class */ (function () {
  4359. /**
  4360. * Creates an Angle object of "radians" radians (float).
  4361. */
  4362. function Angle(radians) {
  4363. var _this = this;
  4364. /**
  4365. * Returns the Angle value in degrees (float).
  4366. */
  4367. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4368. /**
  4369. * Returns the Angle value in radians (float).
  4370. */
  4371. this.radians = function () { return _this._radians; };
  4372. this._radians = radians;
  4373. if (this._radians < 0.0)
  4374. this._radians += (2.0 * Math.PI);
  4375. }
  4376. /**
  4377. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4378. */
  4379. Angle.BetweenTwoPoints = function (a, b) {
  4380. var delta = b.subtract(a);
  4381. var theta = Math.atan2(delta.y, delta.x);
  4382. return new Angle(theta);
  4383. };
  4384. /**
  4385. * Returns a new Angle object from the passed float in radians.
  4386. */
  4387. Angle.FromRadians = function (radians) {
  4388. return new Angle(radians);
  4389. };
  4390. /**
  4391. * Returns a new Angle object from the passed float in degrees.
  4392. */
  4393. Angle.FromDegrees = function (degrees) {
  4394. return new Angle(degrees * Math.PI / 180.0);
  4395. };
  4396. return Angle;
  4397. }());
  4398. BABYLON.Angle = Angle;
  4399. var Arc2 = /** @class */ (function () {
  4400. /**
  4401. * Creates an Arc object from the three passed points : start, middle and end.
  4402. */
  4403. function Arc2(startPoint, midPoint, endPoint) {
  4404. this.startPoint = startPoint;
  4405. this.midPoint = midPoint;
  4406. this.endPoint = endPoint;
  4407. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4408. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4409. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4410. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4411. 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);
  4412. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4413. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4414. var a1 = this.startAngle.degrees();
  4415. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4416. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4417. // angles correction
  4418. if (a2 - a1 > +180.0)
  4419. a2 -= 360.0;
  4420. if (a2 - a1 < -180.0)
  4421. a2 += 360.0;
  4422. if (a3 - a2 > +180.0)
  4423. a3 -= 360.0;
  4424. if (a3 - a2 < -180.0)
  4425. a3 += 360.0;
  4426. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4427. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4428. }
  4429. return Arc2;
  4430. }());
  4431. BABYLON.Arc2 = Arc2;
  4432. var Path2 = /** @class */ (function () {
  4433. /**
  4434. * Creates a Path2 object from the starting 2D coordinates x and y.
  4435. */
  4436. function Path2(x, y) {
  4437. this._points = new Array();
  4438. this._length = 0.0;
  4439. this.closed = false;
  4440. this._points.push(new Vector2(x, y));
  4441. }
  4442. /**
  4443. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4444. * Returns the updated Path2.
  4445. */
  4446. Path2.prototype.addLineTo = function (x, y) {
  4447. if (this.closed) {
  4448. //Tools.Error("cannot add lines to closed paths");
  4449. return this;
  4450. }
  4451. var newPoint = new Vector2(x, y);
  4452. var previousPoint = this._points[this._points.length - 1];
  4453. this._points.push(newPoint);
  4454. this._length += newPoint.subtract(previousPoint).length();
  4455. return this;
  4456. };
  4457. /**
  4458. * 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.
  4459. * Returns the updated Path2.
  4460. */
  4461. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4462. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4463. if (this.closed) {
  4464. //Tools.Error("cannot add arcs to closed paths");
  4465. return this;
  4466. }
  4467. var startPoint = this._points[this._points.length - 1];
  4468. var midPoint = new Vector2(midX, midY);
  4469. var endPoint = new Vector2(endX, endY);
  4470. var arc = new Arc2(startPoint, midPoint, endPoint);
  4471. var increment = arc.angle.radians() / numberOfSegments;
  4472. if (arc.orientation === Orientation.CW)
  4473. increment *= -1;
  4474. var currentAngle = arc.startAngle.radians() + increment;
  4475. for (var i = 0; i < numberOfSegments; i++) {
  4476. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4477. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4478. this.addLineTo(x, y);
  4479. currentAngle += increment;
  4480. }
  4481. return this;
  4482. };
  4483. /**
  4484. * Closes the Path2.
  4485. * Returns the Path2.
  4486. */
  4487. Path2.prototype.close = function () {
  4488. this.closed = true;
  4489. return this;
  4490. };
  4491. /**
  4492. * Returns the Path2 total length (float).
  4493. */
  4494. Path2.prototype.length = function () {
  4495. var result = this._length;
  4496. if (!this.closed) {
  4497. var lastPoint = this._points[this._points.length - 1];
  4498. var firstPoint = this._points[0];
  4499. result += (firstPoint.subtract(lastPoint).length());
  4500. }
  4501. return result;
  4502. };
  4503. /**
  4504. * Returns the Path2 internal array of points.
  4505. */
  4506. Path2.prototype.getPoints = function () {
  4507. return this._points;
  4508. };
  4509. /**
  4510. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4511. */
  4512. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4513. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4514. //Tools.Error("normalized length position should be between 0 and 1.");
  4515. return Vector2.Zero();
  4516. }
  4517. var lengthPosition = normalizedLengthPosition * this.length();
  4518. var previousOffset = 0;
  4519. for (var i = 0; i < this._points.length; i++) {
  4520. var j = (i + 1) % this._points.length;
  4521. var a = this._points[i];
  4522. var b = this._points[j];
  4523. var bToA = b.subtract(a);
  4524. var nextOffset = (bToA.length() + previousOffset);
  4525. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4526. var dir = bToA.normalize();
  4527. var localOffset = lengthPosition - previousOffset;
  4528. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4529. }
  4530. previousOffset = nextOffset;
  4531. }
  4532. //Tools.Error("internal error");
  4533. return Vector2.Zero();
  4534. };
  4535. /**
  4536. * Returns a new Path2 starting at the coordinates (x, y).
  4537. */
  4538. Path2.StartingAt = function (x, y) {
  4539. return new Path2(x, y);
  4540. };
  4541. return Path2;
  4542. }());
  4543. BABYLON.Path2 = Path2;
  4544. var Path3D = /** @class */ (function () {
  4545. /**
  4546. * new Path3D(path, normal, raw)
  4547. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4548. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4549. * path : an array of Vector3, the curve axis of the Path3D
  4550. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4551. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4552. */
  4553. function Path3D(path, firstNormal, raw) {
  4554. if (firstNormal === void 0) { firstNormal = null; }
  4555. this.path = path;
  4556. this._curve = new Array();
  4557. this._distances = new Array();
  4558. this._tangents = new Array();
  4559. this._normals = new Array();
  4560. this._binormals = new Array();
  4561. for (var p = 0; p < path.length; p++) {
  4562. this._curve[p] = path[p].clone(); // hard copy
  4563. }
  4564. this._raw = raw || false;
  4565. this._compute(firstNormal);
  4566. }
  4567. /**
  4568. * Returns the Path3D array of successive Vector3 designing its curve.
  4569. */
  4570. Path3D.prototype.getCurve = function () {
  4571. return this._curve;
  4572. };
  4573. /**
  4574. * Returns an array populated with tangent vectors on each Path3D curve point.
  4575. */
  4576. Path3D.prototype.getTangents = function () {
  4577. return this._tangents;
  4578. };
  4579. /**
  4580. * Returns an array populated with normal vectors on each Path3D curve point.
  4581. */
  4582. Path3D.prototype.getNormals = function () {
  4583. return this._normals;
  4584. };
  4585. /**
  4586. * Returns an array populated with binormal vectors on each Path3D curve point.
  4587. */
  4588. Path3D.prototype.getBinormals = function () {
  4589. return this._binormals;
  4590. };
  4591. /**
  4592. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4593. */
  4594. Path3D.prototype.getDistances = function () {
  4595. return this._distances;
  4596. };
  4597. /**
  4598. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4599. * Returns the same object updated.
  4600. */
  4601. Path3D.prototype.update = function (path, firstNormal) {
  4602. if (firstNormal === void 0) { firstNormal = null; }
  4603. for (var p = 0; p < path.length; p++) {
  4604. this._curve[p].x = path[p].x;
  4605. this._curve[p].y = path[p].y;
  4606. this._curve[p].z = path[p].z;
  4607. }
  4608. this._compute(firstNormal);
  4609. return this;
  4610. };
  4611. // private function compute() : computes tangents, normals and binormals
  4612. Path3D.prototype._compute = function (firstNormal) {
  4613. var l = this._curve.length;
  4614. // first and last tangents
  4615. this._tangents[0] = this._getFirstNonNullVector(0);
  4616. if (!this._raw) {
  4617. this._tangents[0].normalize();
  4618. }
  4619. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4620. if (!this._raw) {
  4621. this._tangents[l - 1].normalize();
  4622. }
  4623. // normals and binormals at first point : arbitrary vector with _normalVector()
  4624. var tg0 = this._tangents[0];
  4625. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4626. this._normals[0] = pp0;
  4627. if (!this._raw) {
  4628. this._normals[0].normalize();
  4629. }
  4630. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4631. if (!this._raw) {
  4632. this._binormals[0].normalize();
  4633. }
  4634. this._distances[0] = 0.0;
  4635. // normals and binormals : next points
  4636. var prev; // previous vector (segment)
  4637. var cur; // current vector (segment)
  4638. var curTang; // current tangent
  4639. // previous normal
  4640. var prevBinor; // previous binormal
  4641. for (var i = 1; i < l; i++) {
  4642. // tangents
  4643. prev = this._getLastNonNullVector(i);
  4644. if (i < l - 1) {
  4645. cur = this._getFirstNonNullVector(i);
  4646. this._tangents[i] = prev.add(cur);
  4647. this._tangents[i].normalize();
  4648. }
  4649. this._distances[i] = this._distances[i - 1] + prev.length();
  4650. // normals and binormals
  4651. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4652. curTang = this._tangents[i];
  4653. prevBinor = this._binormals[i - 1];
  4654. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4655. if (!this._raw) {
  4656. this._normals[i].normalize();
  4657. }
  4658. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4659. if (!this._raw) {
  4660. this._binormals[i].normalize();
  4661. }
  4662. }
  4663. };
  4664. // private function getFirstNonNullVector(index)
  4665. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4666. Path3D.prototype._getFirstNonNullVector = function (index) {
  4667. var i = 1;
  4668. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4669. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4670. i++;
  4671. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4672. }
  4673. return nNVector;
  4674. };
  4675. // private function getLastNonNullVector(index)
  4676. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4677. Path3D.prototype._getLastNonNullVector = function (index) {
  4678. var i = 1;
  4679. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4680. while (nLVector.length() === 0 && index > i + 1) {
  4681. i++;
  4682. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4683. }
  4684. return nLVector;
  4685. };
  4686. // private function normalVector(v0, vt, va) :
  4687. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4688. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4689. Path3D.prototype._normalVector = function (v0, vt, va) {
  4690. var normal0;
  4691. var tgl = vt.length();
  4692. if (tgl === 0.0) {
  4693. tgl = 1.0;
  4694. }
  4695. if (va === undefined || va === null) {
  4696. var point;
  4697. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4698. point = new Vector3(0.0, -1.0, 0.0);
  4699. }
  4700. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4701. point = new Vector3(1.0, 0.0, 0.0);
  4702. }
  4703. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4704. point = new Vector3(0.0, 0.0, 1.0);
  4705. }
  4706. else {
  4707. point = Vector3.Zero();
  4708. }
  4709. normal0 = Vector3.Cross(vt, point);
  4710. }
  4711. else {
  4712. normal0 = Vector3.Cross(vt, va);
  4713. Vector3.CrossToRef(normal0, vt, normal0);
  4714. }
  4715. normal0.normalize();
  4716. return normal0;
  4717. };
  4718. return Path3D;
  4719. }());
  4720. BABYLON.Path3D = Path3D;
  4721. var Curve3 = /** @class */ (function () {
  4722. /**
  4723. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4724. * A Curve3 is designed from a series of successive Vector3.
  4725. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4726. */
  4727. function Curve3(points) {
  4728. this._length = 0.0;
  4729. this._points = points;
  4730. this._length = this._computeLength(points);
  4731. }
  4732. /**
  4733. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4734. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4735. * @param v1 (Vector3) the control point
  4736. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4737. * @param nbPoints (integer) the wanted number of points in the curve
  4738. */
  4739. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4740. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4741. var bez = new Array();
  4742. var equation = function (t, val0, val1, val2) {
  4743. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4744. return res;
  4745. };
  4746. for (var i = 0; i <= nbPoints; i++) {
  4747. 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)));
  4748. }
  4749. return new Curve3(bez);
  4750. };
  4751. /**
  4752. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4753. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4754. * @param v1 (Vector3) the first control point
  4755. * @param v2 (Vector3) the second control point
  4756. * @param v3 (Vector3) the end point of the Cubic Bezier
  4757. * @param nbPoints (integer) the wanted number of points in the curve
  4758. */
  4759. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4760. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4761. var bez = new Array();
  4762. var equation = function (t, val0, val1, val2, val3) {
  4763. 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;
  4764. return res;
  4765. };
  4766. for (var i = 0; i <= nbPoints; i++) {
  4767. 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)));
  4768. }
  4769. return new Curve3(bez);
  4770. };
  4771. /**
  4772. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4773. * @param p1 (Vector3) the origin point of the Hermite Spline
  4774. * @param t1 (Vector3) the tangent vector at the origin point
  4775. * @param p2 (Vector3) the end point of the Hermite Spline
  4776. * @param t2 (Vector3) the tangent vector at the end point
  4777. * @param nbPoints (integer) the wanted number of points in the curve
  4778. */
  4779. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4780. var hermite = new Array();
  4781. var step = 1.0 / nbPoints;
  4782. for (var i = 0; i <= nbPoints; i++) {
  4783. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4784. }
  4785. return new Curve3(hermite);
  4786. };
  4787. /**
  4788. * Returns a Curve3 object along a CatmullRom Spline curve :
  4789. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4790. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4791. */
  4792. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4793. var totalPoints = new Array();
  4794. totalPoints.push(points[0].clone());
  4795. Array.prototype.push.apply(totalPoints, points);
  4796. totalPoints.push(points[points.length - 1].clone());
  4797. var catmullRom = new Array();
  4798. var step = 1.0 / nbPoints;
  4799. var amount = 0.0;
  4800. for (var i = 0; i < totalPoints.length - 3; i++) {
  4801. amount = 0;
  4802. for (var c = 0; c < nbPoints; c++) {
  4803. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4804. amount += step;
  4805. }
  4806. }
  4807. i--;
  4808. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4809. return new Curve3(catmullRom);
  4810. };
  4811. /**
  4812. * Returns the Curve3 stored array of successive Vector3
  4813. */
  4814. Curve3.prototype.getPoints = function () {
  4815. return this._points;
  4816. };
  4817. /**
  4818. * Returns the computed length (float) of the curve.
  4819. */
  4820. Curve3.prototype.length = function () {
  4821. return this._length;
  4822. };
  4823. /**
  4824. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4825. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4826. * curveA and curveB keep unchanged.
  4827. */
  4828. Curve3.prototype.continue = function (curve) {
  4829. var lastPoint = this._points[this._points.length - 1];
  4830. var continuedPoints = this._points.slice();
  4831. var curvePoints = curve.getPoints();
  4832. for (var i = 1; i < curvePoints.length; i++) {
  4833. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4834. }
  4835. var continuedCurve = new Curve3(continuedPoints);
  4836. return continuedCurve;
  4837. };
  4838. Curve3.prototype._computeLength = function (path) {
  4839. var l = 0;
  4840. for (var i = 1; i < path.length; i++) {
  4841. l += (path[i].subtract(path[i - 1])).length();
  4842. }
  4843. return l;
  4844. };
  4845. return Curve3;
  4846. }());
  4847. BABYLON.Curve3 = Curve3;
  4848. // Vertex formats
  4849. var PositionNormalVertex = /** @class */ (function () {
  4850. function PositionNormalVertex(position, normal) {
  4851. if (position === void 0) { position = Vector3.Zero(); }
  4852. if (normal === void 0) { normal = Vector3.Up(); }
  4853. this.position = position;
  4854. this.normal = normal;
  4855. }
  4856. PositionNormalVertex.prototype.clone = function () {
  4857. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4858. };
  4859. return PositionNormalVertex;
  4860. }());
  4861. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4862. var PositionNormalTextureVertex = /** @class */ (function () {
  4863. function PositionNormalTextureVertex(position, normal, uv) {
  4864. if (position === void 0) { position = Vector3.Zero(); }
  4865. if (normal === void 0) { normal = Vector3.Up(); }
  4866. if (uv === void 0) { uv = Vector2.Zero(); }
  4867. this.position = position;
  4868. this.normal = normal;
  4869. this.uv = uv;
  4870. }
  4871. PositionNormalTextureVertex.prototype.clone = function () {
  4872. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4873. };
  4874. return PositionNormalTextureVertex;
  4875. }());
  4876. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4877. // Temporary pre-allocated objects for engine internal use
  4878. // usage in any internal function :
  4879. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4880. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4881. var Tmp = /** @class */ (function () {
  4882. function Tmp() {
  4883. }
  4884. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4885. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4886. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4887. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4888. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4889. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4890. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4891. Matrix.Zero(), Matrix.Zero(),
  4892. Matrix.Zero(), Matrix.Zero(),
  4893. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4894. return Tmp;
  4895. }());
  4896. BABYLON.Tmp = Tmp;
  4897. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4898. var MathTmp = /** @class */ (function () {
  4899. function MathTmp() {
  4900. }
  4901. MathTmp.Vector3 = [Vector3.Zero()];
  4902. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4903. MathTmp.Quaternion = [Quaternion.Zero()];
  4904. return MathTmp;
  4905. }());
  4906. })(BABYLON || (BABYLON = {}));
  4907. //# sourceMappingURL=babylon.math.js.map
  4908. var BABYLON;
  4909. (function (BABYLON) {
  4910. var Scalar = /** @class */ (function () {
  4911. function Scalar() {
  4912. }
  4913. /**
  4914. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4915. */
  4916. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4917. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4918. var num = a - b;
  4919. return -epsilon <= num && num <= epsilon;
  4920. };
  4921. /**
  4922. * Returns a string : the upper case translation of the number i to hexadecimal.
  4923. */
  4924. Scalar.ToHex = function (i) {
  4925. var str = i.toString(16);
  4926. if (i <= 15) {
  4927. return ("0" + str).toUpperCase();
  4928. }
  4929. return str.toUpperCase();
  4930. };
  4931. /**
  4932. * Returns -1 if value is negative and +1 is value is positive.
  4933. * Returns the value itself if it's equal to zero.
  4934. */
  4935. Scalar.Sign = function (value) {
  4936. value = +value; // convert to a number
  4937. if (value === 0 || isNaN(value))
  4938. return value;
  4939. return value > 0 ? 1 : -1;
  4940. };
  4941. /**
  4942. * Returns the value itself if it's between min and max.
  4943. * Returns min if the value is lower than min.
  4944. * Returns max if the value is greater than max.
  4945. */
  4946. Scalar.Clamp = function (value, min, max) {
  4947. if (min === void 0) { min = 0; }
  4948. if (max === void 0) { max = 1; }
  4949. return Math.min(max, Math.max(min, value));
  4950. };
  4951. /**
  4952. * Returns the log2 of value.
  4953. */
  4954. Scalar.Log2 = function (value) {
  4955. return Math.log(value) * Math.LOG2E;
  4956. };
  4957. /**
  4958. * Loops the value, so that it is never larger than length and never smaller than 0.
  4959. *
  4960. * This is similar to the modulo operator but it works with floating point numbers.
  4961. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4962. * With t = 5 and length = 2.5, the result would be 0.0.
  4963. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4964. */
  4965. Scalar.Repeat = function (value, length) {
  4966. return value - Math.floor(value / length) * length;
  4967. };
  4968. /**
  4969. * Normalize the value between 0.0 and 1.0 using min and max values
  4970. */
  4971. Scalar.Normalize = function (value, min, max) {
  4972. return (value - min) / (max - min);
  4973. };
  4974. /**
  4975. * Denormalize the value from 0.0 and 1.0 using min and max values
  4976. */
  4977. Scalar.Denormalize = function (normalized, min, max) {
  4978. return (normalized * (max - min) + min);
  4979. };
  4980. /**
  4981. * Calculates the shortest difference between two given angles given in degrees.
  4982. */
  4983. Scalar.DeltaAngle = function (current, target) {
  4984. var num = Scalar.Repeat(target - current, 360.0);
  4985. if (num > 180.0) {
  4986. num -= 360.0;
  4987. }
  4988. return num;
  4989. };
  4990. /**
  4991. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4992. *
  4993. * The returned value will move back and forth between 0 and length
  4994. */
  4995. Scalar.PingPong = function (tx, length) {
  4996. var t = Scalar.Repeat(tx, length * 2.0);
  4997. return length - Math.abs(t - length);
  4998. };
  4999. /**
  5000. * Interpolates between min and max with smoothing at the limits.
  5001. *
  5002. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5003. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5004. */
  5005. Scalar.SmoothStep = function (from, to, tx) {
  5006. var t = Scalar.Clamp(tx);
  5007. t = -2.0 * t * t * t + 3.0 * t * t;
  5008. return to * t + from * (1.0 - t);
  5009. };
  5010. /**
  5011. * Moves a value current towards target.
  5012. *
  5013. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5014. * Negative values of maxDelta pushes the value away from target.
  5015. */
  5016. Scalar.MoveTowards = function (current, target, maxDelta) {
  5017. var result = 0;
  5018. if (Math.abs(target - current) <= maxDelta) {
  5019. result = target;
  5020. }
  5021. else {
  5022. result = current + Scalar.Sign(target - current) * maxDelta;
  5023. }
  5024. return result;
  5025. };
  5026. /**
  5027. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5028. *
  5029. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5030. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5031. */
  5032. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5033. var num = Scalar.DeltaAngle(current, target);
  5034. var result = 0;
  5035. if (-maxDelta < num && num < maxDelta) {
  5036. result = target;
  5037. }
  5038. else {
  5039. target = current + num;
  5040. result = Scalar.MoveTowards(current, target, maxDelta);
  5041. }
  5042. return result;
  5043. };
  5044. /**
  5045. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5046. */
  5047. Scalar.Lerp = function (start, end, amount) {
  5048. return start + ((end - start) * amount);
  5049. };
  5050. /**
  5051. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5052. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5053. */
  5054. Scalar.LerpAngle = function (start, end, amount) {
  5055. var num = Scalar.Repeat(end - start, 360.0);
  5056. if (num > 180.0) {
  5057. num -= 360.0;
  5058. }
  5059. return start + num * Scalar.Clamp(amount);
  5060. };
  5061. /**
  5062. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5063. */
  5064. Scalar.InverseLerp = function (a, b, value) {
  5065. var result = 0;
  5066. if (a != b) {
  5067. result = Scalar.Clamp((value - a) / (b - a));
  5068. }
  5069. else {
  5070. result = 0.0;
  5071. }
  5072. return result;
  5073. };
  5074. /**
  5075. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5076. */
  5077. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5078. var squared = amount * amount;
  5079. var cubed = amount * squared;
  5080. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5081. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5082. var part3 = (cubed - (2.0 * squared)) + amount;
  5083. var part4 = cubed - squared;
  5084. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5085. };
  5086. /**
  5087. * Returns a random float number between and min and max values
  5088. */
  5089. Scalar.RandomRange = function (min, max) {
  5090. if (min === max)
  5091. return min;
  5092. return ((Math.random() * (max - min)) + min);
  5093. };
  5094. /**
  5095. * This function returns percentage of a number in a given range.
  5096. *
  5097. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5098. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5099. */
  5100. Scalar.RangeToPercent = function (number, min, max) {
  5101. return ((number - min) / (max - min));
  5102. };
  5103. /**
  5104. * This function returns number that corresponds to the percentage in a given range.
  5105. *
  5106. * PercentToRange(0.34,0,100) will return 34.
  5107. */
  5108. Scalar.PercentToRange = function (percent, min, max) {
  5109. return ((max - min) * percent + min);
  5110. };
  5111. /**
  5112. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5113. * @param angle The angle to normalize in radian.
  5114. * @return The converted angle.
  5115. */
  5116. Scalar.NormalizeRadians = function (angle) {
  5117. // More precise but slower version kept for reference.
  5118. // angle = angle % Tools.TwoPi;
  5119. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5120. //if (angle > Math.PI) {
  5121. // angle -= Tools.TwoPi;
  5122. //}
  5123. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5124. return angle;
  5125. };
  5126. /**
  5127. * Two pi constants convenient for computation.
  5128. */
  5129. Scalar.TwoPi = Math.PI * 2;
  5130. return Scalar;
  5131. }());
  5132. BABYLON.Scalar = Scalar;
  5133. })(BABYLON || (BABYLON = {}));
  5134. //# sourceMappingURL=babylon.math.scalar.js.map
  5135. //# sourceMappingURL=babylon.mixins.js.map
  5136. var BABYLON;
  5137. (function (BABYLON) {
  5138. var __decoratorInitialStore = {};
  5139. var __mergedStore = {};
  5140. var _copySource = function (creationFunction, source, instanciate) {
  5141. var destination = creationFunction();
  5142. // Tags
  5143. if (BABYLON.Tags) {
  5144. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5145. }
  5146. var classStore = getMergedStore(destination);
  5147. // Properties
  5148. for (var property in classStore) {
  5149. var propertyDescriptor = classStore[property];
  5150. var sourceProperty = source[property];
  5151. var propertyType = propertyDescriptor.type;
  5152. if (sourceProperty !== undefined && sourceProperty !== null) {
  5153. switch (propertyType) {
  5154. case 0: // Value
  5155. case 6:// Mesh reference
  5156. destination[property] = sourceProperty;
  5157. break;
  5158. case 1:// Texture
  5159. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5160. break;
  5161. case 2: // Color3
  5162. case 3: // FresnelParameters
  5163. case 4: // Vector2
  5164. case 5: // Vector3
  5165. case 7: // Color Curves
  5166. case 10:// Quaternion
  5167. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5168. break;
  5169. }
  5170. }
  5171. }
  5172. return destination;
  5173. };
  5174. function getDirectStore(target) {
  5175. var classKey = target.getClassName();
  5176. if (!__decoratorInitialStore[classKey]) {
  5177. __decoratorInitialStore[classKey] = {};
  5178. }
  5179. return __decoratorInitialStore[classKey];
  5180. }
  5181. /**
  5182. * Return the list of properties flagged as serializable
  5183. * @param target: host object
  5184. */
  5185. function getMergedStore(target) {
  5186. var classKey = target.getClassName();
  5187. if (__mergedStore[classKey]) {
  5188. return __mergedStore[classKey];
  5189. }
  5190. __mergedStore[classKey] = {};
  5191. var store = __mergedStore[classKey];
  5192. var currentTarget = target;
  5193. var currentKey = classKey;
  5194. while (currentKey) {
  5195. var initialStore = __decoratorInitialStore[currentKey];
  5196. for (var property in initialStore) {
  5197. store[property] = initialStore[property];
  5198. }
  5199. var parent_1 = void 0;
  5200. var done = false;
  5201. do {
  5202. parent_1 = Object.getPrototypeOf(currentTarget);
  5203. if (!parent_1.getClassName) {
  5204. done = true;
  5205. break;
  5206. }
  5207. if (parent_1.getClassName() !== currentKey) {
  5208. break;
  5209. }
  5210. currentTarget = parent_1;
  5211. } while (parent_1);
  5212. if (done) {
  5213. break;
  5214. }
  5215. currentKey = parent_1.getClassName();
  5216. currentTarget = parent_1;
  5217. }
  5218. return store;
  5219. }
  5220. function generateSerializableMember(type, sourceName) {
  5221. return function (target, propertyKey) {
  5222. var classStore = getDirectStore(target);
  5223. if (!classStore[propertyKey]) {
  5224. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5225. }
  5226. };
  5227. }
  5228. function generateExpandMember(setCallback, targetKey) {
  5229. if (targetKey === void 0) { targetKey = null; }
  5230. return function (target, propertyKey) {
  5231. var key = targetKey || ("_" + propertyKey);
  5232. Object.defineProperty(target, propertyKey, {
  5233. get: function () {
  5234. return this[key];
  5235. },
  5236. set: function (value) {
  5237. if (this[key] === value) {
  5238. return;
  5239. }
  5240. this[key] = value;
  5241. target[setCallback].apply(this);
  5242. },
  5243. enumerable: true,
  5244. configurable: true
  5245. });
  5246. };
  5247. }
  5248. function expandToProperty(callback, targetKey) {
  5249. if (targetKey === void 0) { targetKey = null; }
  5250. return generateExpandMember(callback, targetKey);
  5251. }
  5252. BABYLON.expandToProperty = expandToProperty;
  5253. function serialize(sourceName) {
  5254. return generateSerializableMember(0, sourceName); // value member
  5255. }
  5256. BABYLON.serialize = serialize;
  5257. function serializeAsTexture(sourceName) {
  5258. return generateSerializableMember(1, sourceName); // texture member
  5259. }
  5260. BABYLON.serializeAsTexture = serializeAsTexture;
  5261. function serializeAsColor3(sourceName) {
  5262. return generateSerializableMember(2, sourceName); // color3 member
  5263. }
  5264. BABYLON.serializeAsColor3 = serializeAsColor3;
  5265. function serializeAsFresnelParameters(sourceName) {
  5266. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5267. }
  5268. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5269. function serializeAsVector2(sourceName) {
  5270. return generateSerializableMember(4, sourceName); // vector2 member
  5271. }
  5272. BABYLON.serializeAsVector2 = serializeAsVector2;
  5273. function serializeAsVector3(sourceName) {
  5274. return generateSerializableMember(5, sourceName); // vector3 member
  5275. }
  5276. BABYLON.serializeAsVector3 = serializeAsVector3;
  5277. function serializeAsMeshReference(sourceName) {
  5278. return generateSerializableMember(6, sourceName); // mesh reference member
  5279. }
  5280. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5281. function serializeAsColorCurves(sourceName) {
  5282. return generateSerializableMember(7, sourceName); // color curves
  5283. }
  5284. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5285. function serializeAsColor4(sourceName) {
  5286. return generateSerializableMember(8, sourceName); // color 4
  5287. }
  5288. BABYLON.serializeAsColor4 = serializeAsColor4;
  5289. function serializeAsImageProcessingConfiguration(sourceName) {
  5290. return generateSerializableMember(9, sourceName); // image processing
  5291. }
  5292. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5293. function serializeAsQuaternion(sourceName) {
  5294. return generateSerializableMember(10, sourceName); // quaternion member
  5295. }
  5296. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  5297. var SerializationHelper = /** @class */ (function () {
  5298. function SerializationHelper() {
  5299. }
  5300. SerializationHelper.Serialize = function (entity, serializationObject) {
  5301. if (!serializationObject) {
  5302. serializationObject = {};
  5303. }
  5304. // Tags
  5305. if (BABYLON.Tags) {
  5306. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5307. }
  5308. var serializedProperties = getMergedStore(entity);
  5309. // Properties
  5310. for (var property in serializedProperties) {
  5311. var propertyDescriptor = serializedProperties[property];
  5312. var targetPropertyName = propertyDescriptor.sourceName || property;
  5313. var propertyType = propertyDescriptor.type;
  5314. var sourceProperty = entity[property];
  5315. if (sourceProperty !== undefined && sourceProperty !== null) {
  5316. switch (propertyType) {
  5317. case 0:// Value
  5318. serializationObject[targetPropertyName] = sourceProperty;
  5319. break;
  5320. case 1:// Texture
  5321. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5322. break;
  5323. case 2:// Color3
  5324. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5325. break;
  5326. case 3:// FresnelParameters
  5327. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5328. break;
  5329. case 4:// Vector2
  5330. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5331. break;
  5332. case 5:// Vector3
  5333. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5334. break;
  5335. case 6:// Mesh reference
  5336. serializationObject[targetPropertyName] = sourceProperty.id;
  5337. break;
  5338. case 7:// Color Curves
  5339. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5340. break;
  5341. case 8:// Color 4
  5342. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5343. break;
  5344. case 9:// Image Processing
  5345. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5346. break;
  5347. }
  5348. }
  5349. }
  5350. return serializationObject;
  5351. };
  5352. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5353. if (rootUrl === void 0) { rootUrl = null; }
  5354. var destination = creationFunction();
  5355. if (!rootUrl) {
  5356. rootUrl = "";
  5357. }
  5358. // Tags
  5359. if (BABYLON.Tags) {
  5360. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5361. }
  5362. var classStore = getMergedStore(destination);
  5363. // Properties
  5364. for (var property in classStore) {
  5365. var propertyDescriptor = classStore[property];
  5366. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5367. var propertyType = propertyDescriptor.type;
  5368. if (sourceProperty !== undefined && sourceProperty !== null) {
  5369. var dest = destination;
  5370. switch (propertyType) {
  5371. case 0:// Value
  5372. dest[property] = sourceProperty;
  5373. break;
  5374. case 1:// Texture
  5375. if (scene) {
  5376. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5377. }
  5378. break;
  5379. case 2:// Color3
  5380. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5381. break;
  5382. case 3:// FresnelParameters
  5383. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5384. break;
  5385. case 4:// Vector2
  5386. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5387. break;
  5388. case 5:// Vector3
  5389. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5390. break;
  5391. case 6:// Mesh reference
  5392. if (scene) {
  5393. dest[property] = scene.getLastMeshByID(sourceProperty);
  5394. }
  5395. break;
  5396. case 7:// Color Curves
  5397. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5398. break;
  5399. case 8:// Color 4
  5400. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5401. break;
  5402. case 9:// Image Processing
  5403. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5404. break;
  5405. }
  5406. }
  5407. }
  5408. return destination;
  5409. };
  5410. SerializationHelper.Clone = function (creationFunction, source) {
  5411. return _copySource(creationFunction, source, false);
  5412. };
  5413. SerializationHelper.Instanciate = function (creationFunction, source) {
  5414. return _copySource(creationFunction, source, true);
  5415. };
  5416. return SerializationHelper;
  5417. }());
  5418. BABYLON.SerializationHelper = SerializationHelper;
  5419. })(BABYLON || (BABYLON = {}));
  5420. //# sourceMappingURL=babylon.decorators.js.map
  5421. var BABYLON;
  5422. (function (BABYLON) {
  5423. /**
  5424. * A class serves as a medium between the observable and its observers
  5425. */
  5426. var EventState = /** @class */ (function () {
  5427. /**
  5428. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5429. */
  5430. function EventState(mask, skipNextObservers, target, currentTarget) {
  5431. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5432. this.initalize(mask, skipNextObservers, target, currentTarget);
  5433. }
  5434. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5435. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5436. this.mask = mask;
  5437. this.skipNextObservers = skipNextObservers;
  5438. this.target = target;
  5439. this.currentTarget = currentTarget;
  5440. return this;
  5441. };
  5442. return EventState;
  5443. }());
  5444. BABYLON.EventState = EventState;
  5445. /**
  5446. * Represent an Observer registered to a given Observable object.
  5447. */
  5448. var Observer = /** @class */ (function () {
  5449. function Observer(callback, mask, scope) {
  5450. if (scope === void 0) { scope = null; }
  5451. this.callback = callback;
  5452. this.mask = mask;
  5453. this.scope = scope;
  5454. }
  5455. return Observer;
  5456. }());
  5457. BABYLON.Observer = Observer;
  5458. /**
  5459. * Represent a list of observers registered to multiple Observables object.
  5460. */
  5461. var MultiObserver = /** @class */ (function () {
  5462. function MultiObserver() {
  5463. }
  5464. MultiObserver.prototype.dispose = function () {
  5465. if (this._observers && this._observables) {
  5466. for (var index = 0; index < this._observers.length; index++) {
  5467. this._observables[index].remove(this._observers[index]);
  5468. }
  5469. }
  5470. this._observers = null;
  5471. this._observables = null;
  5472. };
  5473. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5474. if (mask === void 0) { mask = -1; }
  5475. if (scope === void 0) { scope = null; }
  5476. var result = new MultiObserver();
  5477. result._observers = new Array();
  5478. result._observables = observables;
  5479. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5480. var observable = observables_1[_i];
  5481. var observer = observable.add(callback, mask, false, scope);
  5482. if (observer) {
  5483. result._observers.push(observer);
  5484. }
  5485. }
  5486. return result;
  5487. };
  5488. return MultiObserver;
  5489. }());
  5490. BABYLON.MultiObserver = MultiObserver;
  5491. /**
  5492. * The Observable class is a simple implementation of the Observable pattern.
  5493. * 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.
  5494. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5495. * 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).
  5496. * 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.
  5497. */
  5498. var Observable = /** @class */ (function () {
  5499. function Observable(onObserverAdded) {
  5500. this._observers = new Array();
  5501. this._eventState = new EventState(0);
  5502. if (onObserverAdded) {
  5503. this._onObserverAdded = onObserverAdded;
  5504. }
  5505. }
  5506. /**
  5507. * Create a new Observer with the specified callback
  5508. * @param callback the callback that will be executed for that Observer
  5509. * @param mask the mask used to filter observers
  5510. * @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.
  5511. * @param scope optional scope for the callback to be called from
  5512. */
  5513. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5514. if (mask === void 0) { mask = -1; }
  5515. if (insertFirst === void 0) { insertFirst = false; }
  5516. if (scope === void 0) { scope = null; }
  5517. if (!callback) {
  5518. return null;
  5519. }
  5520. var observer = new Observer(callback, mask, scope);
  5521. if (insertFirst) {
  5522. this._observers.unshift(observer);
  5523. }
  5524. else {
  5525. this._observers.push(observer);
  5526. }
  5527. if (this._onObserverAdded) {
  5528. this._onObserverAdded(observer);
  5529. }
  5530. return observer;
  5531. };
  5532. /**
  5533. * Remove an Observer from the Observable object
  5534. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5535. */
  5536. Observable.prototype.remove = function (observer) {
  5537. if (!observer) {
  5538. return false;
  5539. }
  5540. var index = this._observers.indexOf(observer);
  5541. if (index !== -1) {
  5542. this._observers.splice(index, 1);
  5543. return true;
  5544. }
  5545. return false;
  5546. };
  5547. /**
  5548. * Remove a callback from the Observable object
  5549. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5550. */
  5551. Observable.prototype.removeCallback = function (callback) {
  5552. for (var index = 0; index < this._observers.length; index++) {
  5553. if (this._observers[index].callback === callback) {
  5554. this._observers.splice(index, 1);
  5555. return true;
  5556. }
  5557. }
  5558. return false;
  5559. };
  5560. /**
  5561. * Notify all Observers by calling their respective callback with the given data
  5562. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5563. * @param eventData
  5564. * @param mask
  5565. */
  5566. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5567. if (mask === void 0) { mask = -1; }
  5568. if (!this._observers.length) {
  5569. return true;
  5570. }
  5571. var state = this._eventState;
  5572. state.mask = mask;
  5573. state.target = target;
  5574. state.currentTarget = currentTarget;
  5575. state.skipNextObservers = false;
  5576. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5577. var obs = _a[_i];
  5578. if (obs.mask & mask) {
  5579. if (obs.scope) {
  5580. obs.callback.apply(obs.scope, [eventData, state]);
  5581. }
  5582. else {
  5583. obs.callback(eventData, state);
  5584. }
  5585. }
  5586. if (state.skipNextObservers) {
  5587. return false;
  5588. }
  5589. }
  5590. return true;
  5591. };
  5592. /**
  5593. * Notify a specific observer
  5594. * @param eventData
  5595. * @param mask
  5596. */
  5597. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5598. if (mask === void 0) { mask = -1; }
  5599. var state = this._eventState;
  5600. state.mask = mask;
  5601. state.skipNextObservers = false;
  5602. observer.callback(eventData, state);
  5603. };
  5604. /**
  5605. * return true is the Observable has at least one Observer registered
  5606. */
  5607. Observable.prototype.hasObservers = function () {
  5608. return this._observers.length > 0;
  5609. };
  5610. /**
  5611. * Clear the list of observers
  5612. */
  5613. Observable.prototype.clear = function () {
  5614. this._observers = new Array();
  5615. this._onObserverAdded = null;
  5616. };
  5617. /**
  5618. * Clone the current observable
  5619. */
  5620. Observable.prototype.clone = function () {
  5621. var result = new Observable();
  5622. result._observers = this._observers.slice(0);
  5623. return result;
  5624. };
  5625. /**
  5626. * Does this observable handles observer registered with a given mask
  5627. * @param {number} trigger - the mask to be tested
  5628. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5629. **/
  5630. Observable.prototype.hasSpecificMask = function (mask) {
  5631. if (mask === void 0) { mask = -1; }
  5632. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5633. var obs = _a[_i];
  5634. if (obs.mask & mask || obs.mask === mask) {
  5635. return true;
  5636. }
  5637. }
  5638. return false;
  5639. };
  5640. return Observable;
  5641. }());
  5642. BABYLON.Observable = Observable;
  5643. })(BABYLON || (BABYLON = {}));
  5644. //# sourceMappingURL=babylon.observable.js.map
  5645. var BABYLON;
  5646. (function (BABYLON) {
  5647. var SmartArray = /** @class */ (function () {
  5648. function SmartArray(capacity) {
  5649. this.length = 0;
  5650. this.data = new Array(capacity);
  5651. this._id = SmartArray._GlobalId++;
  5652. }
  5653. SmartArray.prototype.push = function (value) {
  5654. this.data[this.length++] = value;
  5655. if (this.length > this.data.length) {
  5656. this.data.length *= 2;
  5657. }
  5658. };
  5659. SmartArray.prototype.forEach = function (func) {
  5660. for (var index = 0; index < this.length; index++) {
  5661. func(this.data[index]);
  5662. }
  5663. };
  5664. SmartArray.prototype.sort = function (compareFn) {
  5665. this.data.sort(compareFn);
  5666. };
  5667. SmartArray.prototype.reset = function () {
  5668. this.length = 0;
  5669. };
  5670. SmartArray.prototype.dispose = function () {
  5671. this.reset();
  5672. if (this.data) {
  5673. this.data.length = 0;
  5674. this.data = [];
  5675. }
  5676. };
  5677. SmartArray.prototype.concat = function (array) {
  5678. if (array.length === 0) {
  5679. return;
  5680. }
  5681. if (this.length + array.length > this.data.length) {
  5682. this.data.length = (this.length + array.length) * 2;
  5683. }
  5684. for (var index = 0; index < array.length; index++) {
  5685. this.data[this.length++] = (array.data || array)[index];
  5686. }
  5687. };
  5688. SmartArray.prototype.indexOf = function (value) {
  5689. var position = this.data.indexOf(value);
  5690. if (position >= this.length) {
  5691. return -1;
  5692. }
  5693. return position;
  5694. };
  5695. SmartArray.prototype.contains = function (value) {
  5696. return this.data.indexOf(value) !== -1;
  5697. };
  5698. // Statics
  5699. SmartArray._GlobalId = 0;
  5700. return SmartArray;
  5701. }());
  5702. BABYLON.SmartArray = SmartArray;
  5703. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  5704. __extends(SmartArrayNoDuplicate, _super);
  5705. function SmartArrayNoDuplicate() {
  5706. var _this = _super !== null && _super.apply(this, arguments) || this;
  5707. _this._duplicateId = 0;
  5708. return _this;
  5709. }
  5710. SmartArrayNoDuplicate.prototype.push = function (value) {
  5711. _super.prototype.push.call(this, value);
  5712. if (!value.__smartArrayFlags) {
  5713. value.__smartArrayFlags = {};
  5714. }
  5715. value.__smartArrayFlags[this._id] = this._duplicateId;
  5716. };
  5717. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  5718. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5719. return false;
  5720. }
  5721. this.push(value);
  5722. return true;
  5723. };
  5724. SmartArrayNoDuplicate.prototype.reset = function () {
  5725. _super.prototype.reset.call(this);
  5726. this._duplicateId++;
  5727. };
  5728. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  5729. if (array.length === 0) {
  5730. return;
  5731. }
  5732. if (this.length + array.length > this.data.length) {
  5733. this.data.length = (this.length + array.length) * 2;
  5734. }
  5735. for (var index = 0; index < array.length; index++) {
  5736. var item = (array.data || array)[index];
  5737. this.pushNoDuplicate(item);
  5738. }
  5739. };
  5740. return SmartArrayNoDuplicate;
  5741. }(SmartArray));
  5742. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  5743. })(BABYLON || (BABYLON = {}));
  5744. //# sourceMappingURL=babylon.smartArray.js.map
  5745. var BABYLON;
  5746. (function (BABYLON) {
  5747. // Screenshots
  5748. var screenshotCanvas;
  5749. var cloneValue = function (source, destinationObject) {
  5750. if (!source)
  5751. return null;
  5752. if (source instanceof BABYLON.Mesh) {
  5753. return null;
  5754. }
  5755. if (source instanceof BABYLON.SubMesh) {
  5756. return source.clone(destinationObject);
  5757. }
  5758. else if (source.clone) {
  5759. return source.clone();
  5760. }
  5761. return null;
  5762. };
  5763. var Tools = /** @class */ (function () {
  5764. function Tools() {
  5765. }
  5766. /**
  5767. * Interpolates between a and b via alpha
  5768. * @param a The lower value (returned when alpha = 0)
  5769. * @param b The upper value (returned when alpha = 1)
  5770. * @param alpha The interpolation-factor
  5771. * @return The mixed value
  5772. */
  5773. Tools.Mix = function (a, b, alpha) {
  5774. return a * (1 - alpha) + b * alpha;
  5775. };
  5776. Tools.Instantiate = function (className) {
  5777. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5778. return Tools.RegisteredExternalClasses[className];
  5779. }
  5780. var arr = className.split(".");
  5781. var fn = (window || this);
  5782. for (var i = 0, len = arr.length; i < len; i++) {
  5783. fn = fn[arr[i]];
  5784. }
  5785. if (typeof fn !== "function") {
  5786. return null;
  5787. }
  5788. return fn;
  5789. };
  5790. Tools.SetImmediate = function (action) {
  5791. if (window.setImmediate) {
  5792. window.setImmediate(action);
  5793. }
  5794. else {
  5795. setTimeout(action, 1);
  5796. }
  5797. };
  5798. Tools.IsExponentOfTwo = function (value) {
  5799. var count = 1;
  5800. do {
  5801. count *= 2;
  5802. } while (count < value);
  5803. return count === value;
  5804. };
  5805. /**
  5806. * Find the next highest power of two.
  5807. * @param x Number to start search from.
  5808. * @return Next highest power of two.
  5809. */
  5810. Tools.CeilingPOT = function (x) {
  5811. x--;
  5812. x |= x >> 1;
  5813. x |= x >> 2;
  5814. x |= x >> 4;
  5815. x |= x >> 8;
  5816. x |= x >> 16;
  5817. x++;
  5818. return x;
  5819. };
  5820. /**
  5821. * Find the next lowest power of two.
  5822. * @param x Number to start search from.
  5823. * @return Next lowest power of two.
  5824. */
  5825. Tools.FloorPOT = function (x) {
  5826. x = x | (x >> 1);
  5827. x = x | (x >> 2);
  5828. x = x | (x >> 4);
  5829. x = x | (x >> 8);
  5830. x = x | (x >> 16);
  5831. return x - (x >> 1);
  5832. };
  5833. /**
  5834. * Find the nearest power of two.
  5835. * @param x Number to start search from.
  5836. * @return Next nearest power of two.
  5837. */
  5838. Tools.NearestPOT = function (x) {
  5839. var c = Tools.CeilingPOT(x);
  5840. var f = Tools.FloorPOT(x);
  5841. return (c - x) > (x - f) ? f : c;
  5842. };
  5843. Tools.GetExponentOfTwo = function (value, max, mode) {
  5844. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5845. var pot;
  5846. switch (mode) {
  5847. case BABYLON.Engine.SCALEMODE_FLOOR:
  5848. pot = Tools.FloorPOT(value);
  5849. break;
  5850. case BABYLON.Engine.SCALEMODE_NEAREST:
  5851. pot = Tools.NearestPOT(value);
  5852. break;
  5853. case BABYLON.Engine.SCALEMODE_CEILING:
  5854. default:
  5855. pot = Tools.CeilingPOT(value);
  5856. break;
  5857. }
  5858. return Math.min(pot, max);
  5859. };
  5860. Tools.GetFilename = function (path) {
  5861. var index = path.lastIndexOf("/");
  5862. if (index < 0)
  5863. return path;
  5864. return path.substring(index + 1);
  5865. };
  5866. Tools.GetFolderPath = function (uri) {
  5867. var index = uri.lastIndexOf("/");
  5868. if (index < 0)
  5869. return "";
  5870. return uri.substring(0, index + 1);
  5871. };
  5872. Tools.GetDOMTextContent = function (element) {
  5873. var result = "";
  5874. var child = element.firstChild;
  5875. while (child) {
  5876. if (child.nodeType === 3) {
  5877. result += child.textContent;
  5878. }
  5879. child = child.nextSibling;
  5880. }
  5881. return result;
  5882. };
  5883. Tools.ToDegrees = function (angle) {
  5884. return angle * 180 / Math.PI;
  5885. };
  5886. Tools.ToRadians = function (angle) {
  5887. return angle * Math.PI / 180;
  5888. };
  5889. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5890. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5891. var output = "";
  5892. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5893. var i = 0;
  5894. var bytes = new Uint8Array(buffer);
  5895. while (i < bytes.length) {
  5896. chr1 = bytes[i++];
  5897. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5898. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5899. enc1 = chr1 >> 2;
  5900. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5901. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5902. enc4 = chr3 & 63;
  5903. if (isNaN(chr2)) {
  5904. enc3 = enc4 = 64;
  5905. }
  5906. else if (isNaN(chr3)) {
  5907. enc4 = 64;
  5908. }
  5909. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5910. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5911. }
  5912. return "data:image/png;base64," + output;
  5913. };
  5914. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5915. if (bias === void 0) { bias = null; }
  5916. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5917. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5918. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5919. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5920. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5921. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5922. }
  5923. if (bias) {
  5924. minimum.x -= minimum.x * bias.x + bias.y;
  5925. minimum.y -= minimum.y * bias.x + bias.y;
  5926. minimum.z -= minimum.z * bias.x + bias.y;
  5927. maximum.x += maximum.x * bias.x + bias.y;
  5928. maximum.y += maximum.y * bias.x + bias.y;
  5929. maximum.z += maximum.z * bias.x + bias.y;
  5930. }
  5931. return {
  5932. minimum: minimum,
  5933. maximum: maximum
  5934. };
  5935. };
  5936. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5937. if (bias === void 0) { bias = null; }
  5938. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5939. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5940. if (!stride) {
  5941. stride = 3;
  5942. }
  5943. for (var index = start; index < start + count; index++) {
  5944. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5945. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5946. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5947. }
  5948. if (bias) {
  5949. minimum.x -= minimum.x * bias.x + bias.y;
  5950. minimum.y -= minimum.y * bias.x + bias.y;
  5951. minimum.z -= minimum.z * bias.x + bias.y;
  5952. maximum.x += maximum.x * bias.x + bias.y;
  5953. maximum.y += maximum.y * bias.x + bias.y;
  5954. maximum.z += maximum.z * bias.x + bias.y;
  5955. }
  5956. return {
  5957. minimum: minimum,
  5958. maximum: maximum
  5959. };
  5960. };
  5961. Tools.Vector2ArrayFeeder = function (array) {
  5962. return function (index) {
  5963. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5964. var length = isFloatArray ? array.length / 2 : array.length;
  5965. if (index >= length) {
  5966. return null;
  5967. }
  5968. if (isFloatArray) {
  5969. var fa = array;
  5970. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5971. }
  5972. var a = array;
  5973. return a[index];
  5974. };
  5975. };
  5976. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5977. if (bias === void 0) { bias = null; }
  5978. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5979. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5980. var i = 0;
  5981. var cur = feeder(i++);
  5982. while (cur) {
  5983. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5984. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5985. cur = feeder(i++);
  5986. }
  5987. if (bias) {
  5988. minimum.x -= minimum.x * bias.x + bias.y;
  5989. minimum.y -= minimum.y * bias.x + bias.y;
  5990. maximum.x += maximum.x * bias.x + bias.y;
  5991. maximum.y += maximum.y * bias.x + bias.y;
  5992. }
  5993. return {
  5994. minimum: minimum,
  5995. maximum: maximum
  5996. };
  5997. };
  5998. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5999. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6000. return null;
  6001. return Array.isArray(obj) ? obj : [obj];
  6002. };
  6003. // Misc.
  6004. Tools.GetPointerPrefix = function () {
  6005. var eventPrefix = "pointer";
  6006. // Check if pointer events are supported
  6007. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6008. eventPrefix = "mouse";
  6009. }
  6010. return eventPrefix;
  6011. };
  6012. /**
  6013. * @param func - the function to be called
  6014. * @param requester - the object that will request the next frame. Falls back to window.
  6015. */
  6016. Tools.QueueNewFrame = function (func, requester) {
  6017. if (!Tools.IsWindowObjectExist()) {
  6018. return setTimeout(func, 16);
  6019. }
  6020. if (!requester) {
  6021. requester = window;
  6022. }
  6023. if (requester.requestAnimationFrame) {
  6024. return requester.requestAnimationFrame(func);
  6025. }
  6026. else if (requester.msRequestAnimationFrame) {
  6027. return requester.msRequestAnimationFrame(func);
  6028. }
  6029. else if (requester.webkitRequestAnimationFrame) {
  6030. return requester.webkitRequestAnimationFrame(func);
  6031. }
  6032. else if (requester.mozRequestAnimationFrame) {
  6033. return requester.mozRequestAnimationFrame(func);
  6034. }
  6035. else if (requester.oRequestAnimationFrame) {
  6036. return requester.oRequestAnimationFrame(func);
  6037. }
  6038. else {
  6039. return window.setTimeout(func, 16);
  6040. }
  6041. };
  6042. Tools.RequestFullscreen = function (element) {
  6043. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6044. if (!requestFunction)
  6045. return;
  6046. requestFunction.call(element);
  6047. };
  6048. Tools.ExitFullscreen = function () {
  6049. if (document.exitFullscreen) {
  6050. document.exitFullscreen();
  6051. }
  6052. else if (document.mozCancelFullScreen) {
  6053. document.mozCancelFullScreen();
  6054. }
  6055. else if (document.webkitCancelFullScreen) {
  6056. document.webkitCancelFullScreen();
  6057. }
  6058. else if (document.msCancelFullScreen) {
  6059. document.msCancelFullScreen();
  6060. }
  6061. };
  6062. Tools.SetCorsBehavior = function (url, img) {
  6063. if (Tools.CorsBehavior) {
  6064. switch (typeof (Tools.CorsBehavior)) {
  6065. case "function":
  6066. var result = Tools.CorsBehavior(url);
  6067. if (result) {
  6068. img.crossOrigin = result;
  6069. }
  6070. break;
  6071. case "string":
  6072. default:
  6073. img.crossOrigin = Tools.CorsBehavior;
  6074. break;
  6075. }
  6076. }
  6077. };
  6078. // External files
  6079. Tools.CleanUrl = function (url) {
  6080. url = url.replace(/#/mg, "%23");
  6081. return url;
  6082. };
  6083. Tools.LoadImage = function (url, onLoad, onError, database) {
  6084. if (url instanceof ArrayBuffer) {
  6085. url = Tools.EncodeArrayBufferTobase64(url);
  6086. }
  6087. url = Tools.CleanUrl(url);
  6088. url = Tools.PreprocessUrl(url);
  6089. var img = new Image();
  6090. if (url.substr(0, 5) !== "data:") {
  6091. Tools.SetCorsBehavior(url, img);
  6092. }
  6093. img.onload = function () {
  6094. onLoad(img);
  6095. };
  6096. img.onerror = function (err) {
  6097. Tools.Error("Error while trying to load image: " + url);
  6098. if (onError) {
  6099. onError("Error while trying to load image: " + url, err);
  6100. }
  6101. };
  6102. var noIndexedDB = function () {
  6103. img.src = url;
  6104. };
  6105. var loadFromIndexedDB = function () {
  6106. if (database) {
  6107. database.loadImageFromDB(url, img);
  6108. }
  6109. };
  6110. //ANY database to do!
  6111. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6112. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6113. }
  6114. else {
  6115. if (url.indexOf("file:") !== -1) {
  6116. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6117. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6118. try {
  6119. var blobURL;
  6120. try {
  6121. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6122. }
  6123. catch (ex) {
  6124. // Chrome doesn't support oneTimeOnly parameter
  6125. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6126. }
  6127. img.src = blobURL;
  6128. }
  6129. catch (e) {
  6130. img.src = "";
  6131. }
  6132. return img;
  6133. }
  6134. }
  6135. noIndexedDB();
  6136. }
  6137. return img;
  6138. };
  6139. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6140. url = Tools.CleanUrl(url);
  6141. url = Tools.PreprocessUrl(url);
  6142. var request = null;
  6143. var noIndexedDB = function () {
  6144. request = new XMLHttpRequest();
  6145. var loadUrl = Tools.BaseUrl + url;
  6146. request.open('GET', loadUrl, true);
  6147. if (useArrayBuffer) {
  6148. request.responseType = "arraybuffer";
  6149. }
  6150. if (progressCallBack) {
  6151. request.onprogress = progressCallBack;
  6152. }
  6153. request.onreadystatechange = function () {
  6154. var req = request;
  6155. // In case of undefined state in some browsers.
  6156. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6157. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6158. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6159. callback(!useArrayBuffer ? req.responseText : req.response, req.responseURL);
  6160. }
  6161. else {
  6162. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6163. if (onError) {
  6164. onError(req, e);
  6165. }
  6166. else {
  6167. throw e;
  6168. }
  6169. }
  6170. }
  6171. };
  6172. request.send(null);
  6173. };
  6174. var loadFromIndexedDB = function () {
  6175. if (database) {
  6176. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6177. }
  6178. };
  6179. // If file and file input are set
  6180. if (url.indexOf("file:") !== -1) {
  6181. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6182. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6183. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6184. return request;
  6185. }
  6186. }
  6187. // Caching all files
  6188. if (database && database.enableSceneOffline) {
  6189. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6190. }
  6191. else {
  6192. noIndexedDB();
  6193. }
  6194. return request;
  6195. };
  6196. /**
  6197. * Load a script (identified by an url). When the url returns, the
  6198. * content of this file is added into a new script element, attached to the DOM (body element)
  6199. */
  6200. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6201. var head = document.getElementsByTagName('head')[0];
  6202. var script = document.createElement('script');
  6203. script.type = 'text/javascript';
  6204. script.src = scriptUrl;
  6205. script.onload = function () {
  6206. if (onSuccess) {
  6207. onSuccess();
  6208. }
  6209. };
  6210. script.onerror = function (e) {
  6211. if (onError) {
  6212. onError("Unable to load script", e);
  6213. }
  6214. };
  6215. head.appendChild(script);
  6216. };
  6217. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6218. var reader = new FileReader();
  6219. reader.onload = function (e) {
  6220. //target doesn't have result from ts 1.3
  6221. callback(e.target['result']);
  6222. };
  6223. reader.onprogress = progressCallback;
  6224. reader.readAsDataURL(fileToLoad);
  6225. };
  6226. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6227. var reader = new FileReader();
  6228. reader.onerror = function (e) {
  6229. Tools.Log("Error while reading file: " + fileToLoad.name);
  6230. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6231. };
  6232. reader.onload = function (e) {
  6233. //target doesn't have result from ts 1.3
  6234. callback(e.target['result']);
  6235. };
  6236. if (progressCallBack) {
  6237. reader.onprogress = progressCallBack;
  6238. }
  6239. if (!useArrayBuffer) {
  6240. // Asynchronous read
  6241. reader.readAsText(fileToLoad);
  6242. }
  6243. else {
  6244. reader.readAsArrayBuffer(fileToLoad);
  6245. }
  6246. };
  6247. //returns a downloadable url to a file content.
  6248. Tools.FileAsURL = function (content) {
  6249. var fileBlob = new Blob([content]);
  6250. var url = window.URL || window.webkitURL;
  6251. var link = url.createObjectURL(fileBlob);
  6252. return link;
  6253. };
  6254. // Misc.
  6255. Tools.Format = function (value, decimals) {
  6256. if (decimals === void 0) { decimals = 2; }
  6257. return value.toFixed(decimals);
  6258. };
  6259. Tools.CheckExtends = function (v, min, max) {
  6260. if (v.x < min.x)
  6261. min.x = v.x;
  6262. if (v.y < min.y)
  6263. min.y = v.y;
  6264. if (v.z < min.z)
  6265. min.z = v.z;
  6266. if (v.x > max.x)
  6267. max.x = v.x;
  6268. if (v.y > max.y)
  6269. max.y = v.y;
  6270. if (v.z > max.z)
  6271. max.z = v.z;
  6272. };
  6273. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6274. for (var prop in source) {
  6275. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6276. continue;
  6277. }
  6278. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6279. continue;
  6280. }
  6281. var sourceValue = source[prop];
  6282. var typeOfSourceValue = typeof sourceValue;
  6283. if (typeOfSourceValue === "function") {
  6284. continue;
  6285. }
  6286. if (typeOfSourceValue === "object") {
  6287. if (sourceValue instanceof Array) {
  6288. destination[prop] = [];
  6289. if (sourceValue.length > 0) {
  6290. if (typeof sourceValue[0] == "object") {
  6291. for (var index = 0; index < sourceValue.length; index++) {
  6292. var clonedValue = cloneValue(sourceValue[index], destination);
  6293. if (destination[prop].indexOf(clonedValue) === -1) {
  6294. destination[prop].push(clonedValue);
  6295. }
  6296. }
  6297. }
  6298. else {
  6299. destination[prop] = sourceValue.slice(0);
  6300. }
  6301. }
  6302. }
  6303. else {
  6304. destination[prop] = cloneValue(sourceValue, destination);
  6305. }
  6306. }
  6307. else {
  6308. destination[prop] = sourceValue;
  6309. }
  6310. }
  6311. };
  6312. Tools.IsEmpty = function (obj) {
  6313. for (var i in obj) {
  6314. if (obj.hasOwnProperty(i)) {
  6315. return false;
  6316. }
  6317. }
  6318. return true;
  6319. };
  6320. Tools.RegisterTopRootEvents = function (events) {
  6321. for (var index = 0; index < events.length; index++) {
  6322. var event = events[index];
  6323. window.addEventListener(event.name, event.handler, false);
  6324. try {
  6325. if (window.parent) {
  6326. window.parent.addEventListener(event.name, event.handler, false);
  6327. }
  6328. }
  6329. catch (e) {
  6330. // Silently fails...
  6331. }
  6332. }
  6333. };
  6334. Tools.UnregisterTopRootEvents = function (events) {
  6335. for (var index = 0; index < events.length; index++) {
  6336. var event = events[index];
  6337. window.removeEventListener(event.name, event.handler);
  6338. try {
  6339. if (window.parent) {
  6340. window.parent.removeEventListener(event.name, event.handler);
  6341. }
  6342. }
  6343. catch (e) {
  6344. // Silently fails...
  6345. }
  6346. }
  6347. };
  6348. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  6349. if (mimeType === void 0) { mimeType = "image/png"; }
  6350. // Read the contents of the framebuffer
  6351. var numberOfChannelsByLine = width * 4;
  6352. var halfHeight = height / 2;
  6353. //Reading datas from WebGL
  6354. var data = engine.readPixels(0, 0, width, height);
  6355. //To flip image on Y axis.
  6356. for (var i = 0; i < halfHeight; i++) {
  6357. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6358. var currentCell = j + i * numberOfChannelsByLine;
  6359. var targetLine = height - i - 1;
  6360. var targetCell = j + targetLine * numberOfChannelsByLine;
  6361. var temp = data[currentCell];
  6362. data[currentCell] = data[targetCell];
  6363. data[targetCell] = temp;
  6364. }
  6365. }
  6366. // Create a 2D canvas to store the result
  6367. if (!screenshotCanvas) {
  6368. screenshotCanvas = document.createElement('canvas');
  6369. }
  6370. screenshotCanvas.width = width;
  6371. screenshotCanvas.height = height;
  6372. var context = screenshotCanvas.getContext('2d');
  6373. if (context) {
  6374. // Copy the pixels to a 2D canvas
  6375. var imageData = context.createImageData(width, height);
  6376. var castData = (imageData.data);
  6377. castData.set(data);
  6378. context.putImageData(imageData, 0, 0);
  6379. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  6380. }
  6381. };
  6382. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  6383. if (mimeType === void 0) { mimeType = "image/png"; }
  6384. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6385. if (successCallback) {
  6386. successCallback(base64Image);
  6387. }
  6388. else {
  6389. // We need HTMLCanvasElement.toBlob for HD screenshots
  6390. if (!screenshotCanvas.toBlob) {
  6391. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  6392. screenshotCanvas.toBlob = function (callback, type, quality) {
  6393. var _this = this;
  6394. setTimeout(function () {
  6395. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  6396. for (var i = 0; i < len; i++) {
  6397. arr[i] = binStr.charCodeAt(i);
  6398. }
  6399. callback(new Blob([arr], { type: type || 'image/png' }));
  6400. });
  6401. };
  6402. }
  6403. screenshotCanvas.toBlob(function (blob) {
  6404. var url = URL.createObjectURL(blob);
  6405. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6406. if (("download" in document.createElement("a"))) {
  6407. var a = window.document.createElement("a");
  6408. a.href = url;
  6409. if (fileName) {
  6410. a.setAttribute("download", fileName);
  6411. }
  6412. else {
  6413. var date = new Date();
  6414. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6415. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6416. }
  6417. window.document.body.appendChild(a);
  6418. a.addEventListener("click", function () {
  6419. if (a.parentElement) {
  6420. a.parentElement.removeChild(a);
  6421. }
  6422. });
  6423. a.click();
  6424. }
  6425. else {
  6426. var newWindow = window.open("");
  6427. if (!newWindow)
  6428. return;
  6429. var img = newWindow.document.createElement("img");
  6430. img.onload = function () {
  6431. // no longer need to read the blob so it's revoked
  6432. URL.revokeObjectURL(url);
  6433. };
  6434. img.src = url;
  6435. newWindow.document.body.appendChild(img);
  6436. }
  6437. });
  6438. }
  6439. };
  6440. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6441. if (mimeType === void 0) { mimeType = "image/png"; }
  6442. var width;
  6443. var height;
  6444. // If a precision value is specified
  6445. if (size.precision) {
  6446. width = Math.round(engine.getRenderWidth() * size.precision);
  6447. height = Math.round(width / engine.getAspectRatio(camera));
  6448. }
  6449. else if (size.width && size.height) {
  6450. width = size.width;
  6451. height = size.height;
  6452. }
  6453. else if (size.width && !size.height) {
  6454. width = size.width;
  6455. height = Math.round(width / engine.getAspectRatio(camera));
  6456. }
  6457. else if (size.height && !size.width) {
  6458. height = size.height;
  6459. width = Math.round(height * engine.getAspectRatio(camera));
  6460. }
  6461. else if (!isNaN(size)) {
  6462. height = size;
  6463. width = size;
  6464. }
  6465. else {
  6466. Tools.Error("Invalid 'size' parameter !");
  6467. return;
  6468. }
  6469. if (!screenshotCanvas) {
  6470. screenshotCanvas = document.createElement('canvas');
  6471. }
  6472. screenshotCanvas.width = width;
  6473. screenshotCanvas.height = height;
  6474. var renderContext = screenshotCanvas.getContext("2d");
  6475. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6476. var newWidth = width;
  6477. var newHeight = newWidth / ratio;
  6478. if (newHeight > height) {
  6479. newHeight = height;
  6480. newWidth = newHeight * ratio;
  6481. }
  6482. var offsetX = Math.max(0, width - newWidth) / 2;
  6483. var offsetY = Math.max(0, height - newHeight) / 2;
  6484. var renderingCanvas = engine.getRenderingCanvas();
  6485. if (renderContext && renderingCanvas) {
  6486. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6487. }
  6488. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6489. };
  6490. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  6491. if (mimeType === void 0) { mimeType = "image/png"; }
  6492. if (samples === void 0) { samples = 1; }
  6493. if (antialiasing === void 0) { antialiasing = false; }
  6494. var width;
  6495. var height;
  6496. //If a precision value is specified
  6497. if (size.precision) {
  6498. width = Math.round(engine.getRenderWidth() * size.precision);
  6499. height = Math.round(width / engine.getAspectRatio(camera));
  6500. size = { width: width, height: height };
  6501. }
  6502. else if (size.width && size.height) {
  6503. width = size.width;
  6504. height = size.height;
  6505. }
  6506. else if (size.width && !size.height) {
  6507. width = size.width;
  6508. height = Math.round(width / engine.getAspectRatio(camera));
  6509. size = { width: width, height: height };
  6510. }
  6511. else if (size.height && !size.width) {
  6512. height = size.height;
  6513. width = Math.round(height * engine.getAspectRatio(camera));
  6514. size = { width: width, height: height };
  6515. }
  6516. else if (!isNaN(size)) {
  6517. height = size;
  6518. width = size;
  6519. }
  6520. else {
  6521. Tools.Error("Invalid 'size' parameter !");
  6522. return;
  6523. }
  6524. var scene = camera.getScene();
  6525. var previousCamera = null;
  6526. if (scene.activeCamera !== camera) {
  6527. previousCamera = scene.activeCamera;
  6528. scene.activeCamera = camera;
  6529. }
  6530. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6531. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6532. texture.renderList = null;
  6533. texture.samples = samples;
  6534. if (antialiasing) {
  6535. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  6536. }
  6537. texture.onAfterRenderObservable.add(function () {
  6538. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  6539. });
  6540. scene.incrementRenderId();
  6541. scene.resetCachedMaterial();
  6542. texture.render(true);
  6543. texture.dispose();
  6544. if (previousCamera) {
  6545. scene.activeCamera = previousCamera;
  6546. }
  6547. camera.getProjectionMatrix(true); // Force cache refresh;
  6548. };
  6549. // XHR response validator for local file scenario
  6550. Tools.ValidateXHRData = function (xhr, dataType) {
  6551. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6552. if (dataType === void 0) { dataType = 7; }
  6553. try {
  6554. if (dataType & 1) {
  6555. if (xhr.responseText && xhr.responseText.length > 0) {
  6556. return true;
  6557. }
  6558. else if (dataType === 1) {
  6559. return false;
  6560. }
  6561. }
  6562. if (dataType & 2) {
  6563. // Check header width and height since there is no "TGA" magic number
  6564. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6565. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6566. return true;
  6567. }
  6568. else if (dataType === 2) {
  6569. return false;
  6570. }
  6571. }
  6572. if (dataType & 4) {
  6573. // Check for the "DDS" magic number
  6574. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6575. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6576. return true;
  6577. }
  6578. else {
  6579. return false;
  6580. }
  6581. }
  6582. }
  6583. catch (e) {
  6584. // Global protection
  6585. }
  6586. return false;
  6587. };
  6588. /**
  6589. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6590. * Be aware Math.random() could cause collisions, but:
  6591. * "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"
  6592. */
  6593. Tools.RandomId = function () {
  6594. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6595. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6596. return v.toString(16);
  6597. });
  6598. };
  6599. Object.defineProperty(Tools, "NoneLogLevel", {
  6600. get: function () {
  6601. return Tools._NoneLogLevel;
  6602. },
  6603. enumerable: true,
  6604. configurable: true
  6605. });
  6606. Object.defineProperty(Tools, "MessageLogLevel", {
  6607. get: function () {
  6608. return Tools._MessageLogLevel;
  6609. },
  6610. enumerable: true,
  6611. configurable: true
  6612. });
  6613. Object.defineProperty(Tools, "WarningLogLevel", {
  6614. get: function () {
  6615. return Tools._WarningLogLevel;
  6616. },
  6617. enumerable: true,
  6618. configurable: true
  6619. });
  6620. Object.defineProperty(Tools, "ErrorLogLevel", {
  6621. get: function () {
  6622. return Tools._ErrorLogLevel;
  6623. },
  6624. enumerable: true,
  6625. configurable: true
  6626. });
  6627. Object.defineProperty(Tools, "AllLogLevel", {
  6628. get: function () {
  6629. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6630. },
  6631. enumerable: true,
  6632. configurable: true
  6633. });
  6634. Tools._AddLogEntry = function (entry) {
  6635. Tools._LogCache = entry + Tools._LogCache;
  6636. if (Tools.OnNewCacheEntry) {
  6637. Tools.OnNewCacheEntry(entry);
  6638. }
  6639. };
  6640. Tools._FormatMessage = function (message) {
  6641. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6642. var date = new Date();
  6643. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6644. };
  6645. Tools._LogDisabled = function (message) {
  6646. // nothing to do
  6647. };
  6648. Tools._LogEnabled = function (message) {
  6649. var formattedMessage = Tools._FormatMessage(message);
  6650. console.log("BJS - " + formattedMessage);
  6651. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6652. Tools._AddLogEntry(entry);
  6653. };
  6654. Tools._WarnDisabled = function (message) {
  6655. // nothing to do
  6656. };
  6657. Tools._WarnEnabled = function (message) {
  6658. var formattedMessage = Tools._FormatMessage(message);
  6659. console.warn("BJS - " + formattedMessage);
  6660. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6661. Tools._AddLogEntry(entry);
  6662. };
  6663. Tools._ErrorDisabled = function (message) {
  6664. // nothing to do
  6665. };
  6666. Tools._ErrorEnabled = function (message) {
  6667. Tools.errorsCount++;
  6668. var formattedMessage = Tools._FormatMessage(message);
  6669. console.error("BJS - " + formattedMessage);
  6670. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6671. Tools._AddLogEntry(entry);
  6672. };
  6673. Object.defineProperty(Tools, "LogCache", {
  6674. get: function () {
  6675. return Tools._LogCache;
  6676. },
  6677. enumerable: true,
  6678. configurable: true
  6679. });
  6680. Tools.ClearLogCache = function () {
  6681. Tools._LogCache = "";
  6682. Tools.errorsCount = 0;
  6683. };
  6684. Object.defineProperty(Tools, "LogLevels", {
  6685. set: function (level) {
  6686. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6687. Tools.Log = Tools._LogEnabled;
  6688. }
  6689. else {
  6690. Tools.Log = Tools._LogDisabled;
  6691. }
  6692. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6693. Tools.Warn = Tools._WarnEnabled;
  6694. }
  6695. else {
  6696. Tools.Warn = Tools._WarnDisabled;
  6697. }
  6698. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6699. Tools.Error = Tools._ErrorEnabled;
  6700. }
  6701. else {
  6702. Tools.Error = Tools._ErrorDisabled;
  6703. }
  6704. },
  6705. enumerable: true,
  6706. configurable: true
  6707. });
  6708. Tools.IsWindowObjectExist = function () {
  6709. return (typeof window) !== "undefined";
  6710. };
  6711. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6712. get: function () {
  6713. return Tools._PerformanceNoneLogLevel;
  6714. },
  6715. enumerable: true,
  6716. configurable: true
  6717. });
  6718. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6719. get: function () {
  6720. return Tools._PerformanceUserMarkLogLevel;
  6721. },
  6722. enumerable: true,
  6723. configurable: true
  6724. });
  6725. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6726. get: function () {
  6727. return Tools._PerformanceConsoleLogLevel;
  6728. },
  6729. enumerable: true,
  6730. configurable: true
  6731. });
  6732. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6733. set: function (level) {
  6734. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6735. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6736. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6737. return;
  6738. }
  6739. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6740. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6741. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6742. return;
  6743. }
  6744. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6745. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6746. },
  6747. enumerable: true,
  6748. configurable: true
  6749. });
  6750. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6751. };
  6752. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6753. };
  6754. Tools._StartUserMark = function (counterName, condition) {
  6755. if (condition === void 0) { condition = true; }
  6756. if (!Tools._performance) {
  6757. if (!Tools.IsWindowObjectExist()) {
  6758. return;
  6759. }
  6760. Tools._performance = window.performance;
  6761. }
  6762. if (!condition || !Tools._performance.mark) {
  6763. return;
  6764. }
  6765. Tools._performance.mark(counterName + "-Begin");
  6766. };
  6767. Tools._EndUserMark = function (counterName, condition) {
  6768. if (condition === void 0) { condition = true; }
  6769. if (!condition || !Tools._performance.mark) {
  6770. return;
  6771. }
  6772. Tools._performance.mark(counterName + "-End");
  6773. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6774. };
  6775. Tools._StartPerformanceConsole = function (counterName, condition) {
  6776. if (condition === void 0) { condition = true; }
  6777. if (!condition) {
  6778. return;
  6779. }
  6780. Tools._StartUserMark(counterName, condition);
  6781. if (console.time) {
  6782. console.time(counterName);
  6783. }
  6784. };
  6785. Tools._EndPerformanceConsole = function (counterName, condition) {
  6786. if (condition === void 0) { condition = true; }
  6787. if (!condition) {
  6788. return;
  6789. }
  6790. Tools._EndUserMark(counterName, condition);
  6791. if (console.time) {
  6792. console.timeEnd(counterName);
  6793. }
  6794. };
  6795. Object.defineProperty(Tools, "Now", {
  6796. get: function () {
  6797. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6798. return window.performance.now();
  6799. }
  6800. return new Date().getTime();
  6801. },
  6802. enumerable: true,
  6803. configurable: true
  6804. });
  6805. /**
  6806. * This method will return the name of the class used to create the instance of the given object.
  6807. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6808. * @param object the object to get the class name from
  6809. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6810. */
  6811. Tools.GetClassName = function (object, isType) {
  6812. if (isType === void 0) { isType = false; }
  6813. var name = null;
  6814. if (!isType && object.getClassName) {
  6815. name = object.getClassName();
  6816. }
  6817. else {
  6818. if (object instanceof Object) {
  6819. var classObj = isType ? object : Object.getPrototypeOf(object);
  6820. name = classObj.constructor["__bjsclassName__"];
  6821. }
  6822. if (!name) {
  6823. name = typeof object;
  6824. }
  6825. }
  6826. return name;
  6827. };
  6828. Tools.First = function (array, predicate) {
  6829. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6830. var el = array_1[_i];
  6831. if (predicate(el)) {
  6832. return el;
  6833. }
  6834. }
  6835. return null;
  6836. };
  6837. /**
  6838. * This method will return the name of the full name of the class, including its owning module (if any).
  6839. * 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).
  6840. * @param object the object to get the class name from
  6841. * @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.
  6842. */
  6843. Tools.getFullClassName = function (object, isType) {
  6844. if (isType === void 0) { isType = false; }
  6845. var className = null;
  6846. var moduleName = null;
  6847. if (!isType && object.getClassName) {
  6848. className = object.getClassName();
  6849. }
  6850. else {
  6851. if (object instanceof Object) {
  6852. var classObj = isType ? object : Object.getPrototypeOf(object);
  6853. className = classObj.constructor["__bjsclassName__"];
  6854. moduleName = classObj.constructor["__bjsmoduleName__"];
  6855. }
  6856. if (!className) {
  6857. className = typeof object;
  6858. }
  6859. }
  6860. if (!className) {
  6861. return null;
  6862. }
  6863. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6864. };
  6865. /**
  6866. * 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.
  6867. * @param array
  6868. */
  6869. Tools.arrayOrStringFeeder = function (array) {
  6870. return function (index) {
  6871. if (index >= array.length) {
  6872. return null;
  6873. }
  6874. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6875. if (val && val.getHashCode) {
  6876. val = val.getHashCode();
  6877. }
  6878. if (typeof val === "string") {
  6879. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6880. }
  6881. return val;
  6882. };
  6883. };
  6884. /**
  6885. * Compute the hashCode of a stream of number
  6886. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6887. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6888. * @return the hash code computed
  6889. */
  6890. Tools.hashCodeFromStream = function (feeder) {
  6891. // Based from here: http://stackoverflow.com/a/7616484/802124
  6892. var hash = 0;
  6893. var index = 0;
  6894. var chr = feeder(index++);
  6895. while (chr != null) {
  6896. hash = ((hash << 5) - hash) + chr;
  6897. hash |= 0; // Convert to 32bit integer
  6898. chr = feeder(index++);
  6899. }
  6900. return hash;
  6901. };
  6902. Tools.BaseUrl = "";
  6903. Tools.CorsBehavior = "anonymous";
  6904. Tools.UseFallbackTexture = true;
  6905. /**
  6906. * Use this object to register external classes like custom textures or material
  6907. * to allow the laoders to instantiate them
  6908. */
  6909. Tools.RegisteredExternalClasses = {};
  6910. // Used in case of a texture loading problem
  6911. 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";
  6912. Tools.PreprocessUrl = function (url) {
  6913. return url;
  6914. };
  6915. // Logs
  6916. Tools._NoneLogLevel = 0;
  6917. Tools._MessageLogLevel = 1;
  6918. Tools._WarningLogLevel = 2;
  6919. Tools._ErrorLogLevel = 4;
  6920. Tools._LogCache = "";
  6921. Tools.errorsCount = 0;
  6922. Tools.Log = Tools._LogEnabled;
  6923. Tools.Warn = Tools._WarnEnabled;
  6924. Tools.Error = Tools._ErrorEnabled;
  6925. // Performances
  6926. Tools._PerformanceNoneLogLevel = 0;
  6927. Tools._PerformanceUserMarkLogLevel = 1;
  6928. Tools._PerformanceConsoleLogLevel = 2;
  6929. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6930. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6931. return Tools;
  6932. }());
  6933. BABYLON.Tools = Tools;
  6934. /**
  6935. * This class is used to track a performance counter which is number based.
  6936. * The user has access to many properties which give statistics of different nature
  6937. *
  6938. * The implementer can track two kinds of Performance Counter: time and count
  6939. * 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.
  6940. * 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.
  6941. */
  6942. var PerfCounter = /** @class */ (function () {
  6943. function PerfCounter() {
  6944. this._startMonitoringTime = 0;
  6945. this._min = 0;
  6946. this._max = 0;
  6947. this._average = 0;
  6948. this._lastSecAverage = 0;
  6949. this._current = 0;
  6950. this._totalValueCount = 0;
  6951. this._totalAccumulated = 0;
  6952. this._lastSecAccumulated = 0;
  6953. this._lastSecTime = 0;
  6954. this._lastSecValueCount = 0;
  6955. }
  6956. Object.defineProperty(PerfCounter.prototype, "min", {
  6957. /**
  6958. * Returns the smallest value ever
  6959. */
  6960. get: function () {
  6961. return this._min;
  6962. },
  6963. enumerable: true,
  6964. configurable: true
  6965. });
  6966. Object.defineProperty(PerfCounter.prototype, "max", {
  6967. /**
  6968. * Returns the biggest value ever
  6969. */
  6970. get: function () {
  6971. return this._max;
  6972. },
  6973. enumerable: true,
  6974. configurable: true
  6975. });
  6976. Object.defineProperty(PerfCounter.prototype, "average", {
  6977. /**
  6978. * Returns the average value since the performance counter is running
  6979. */
  6980. get: function () {
  6981. return this._average;
  6982. },
  6983. enumerable: true,
  6984. configurable: true
  6985. });
  6986. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6987. /**
  6988. * Returns the average value of the last second the counter was monitored
  6989. */
  6990. get: function () {
  6991. return this._lastSecAverage;
  6992. },
  6993. enumerable: true,
  6994. configurable: true
  6995. });
  6996. Object.defineProperty(PerfCounter.prototype, "current", {
  6997. /**
  6998. * Returns the current value
  6999. */
  7000. get: function () {
  7001. return this._current;
  7002. },
  7003. enumerable: true,
  7004. configurable: true
  7005. });
  7006. Object.defineProperty(PerfCounter.prototype, "total", {
  7007. get: function () {
  7008. return this._totalAccumulated;
  7009. },
  7010. enumerable: true,
  7011. configurable: true
  7012. });
  7013. Object.defineProperty(PerfCounter.prototype, "count", {
  7014. get: function () {
  7015. return this._totalValueCount;
  7016. },
  7017. enumerable: true,
  7018. configurable: true
  7019. });
  7020. /**
  7021. * Call this method to start monitoring a new frame.
  7022. * 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.
  7023. */
  7024. PerfCounter.prototype.fetchNewFrame = function () {
  7025. this._totalValueCount++;
  7026. this._current = 0;
  7027. this._lastSecValueCount++;
  7028. };
  7029. /**
  7030. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7031. * @param newCount the count value to add to the monitored count
  7032. * @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.
  7033. */
  7034. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7035. if (!PerfCounter.Enabled) {
  7036. return;
  7037. }
  7038. this._current += newCount;
  7039. if (fetchResult) {
  7040. this._fetchResult();
  7041. }
  7042. };
  7043. /**
  7044. * Start monitoring this performance counter
  7045. */
  7046. PerfCounter.prototype.beginMonitoring = function () {
  7047. if (!PerfCounter.Enabled) {
  7048. return;
  7049. }
  7050. this._startMonitoringTime = Tools.Now;
  7051. };
  7052. /**
  7053. * Compute the time lapsed since the previous beginMonitoring() call.
  7054. * @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
  7055. */
  7056. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7057. if (newFrame === void 0) { newFrame = true; }
  7058. if (!PerfCounter.Enabled) {
  7059. return;
  7060. }
  7061. if (newFrame) {
  7062. this.fetchNewFrame();
  7063. }
  7064. var currentTime = Tools.Now;
  7065. this._current = currentTime - this._startMonitoringTime;
  7066. if (newFrame) {
  7067. this._fetchResult();
  7068. }
  7069. };
  7070. PerfCounter.prototype._fetchResult = function () {
  7071. this._totalAccumulated += this._current;
  7072. this._lastSecAccumulated += this._current;
  7073. // Min/Max update
  7074. this._min = Math.min(this._min, this._current);
  7075. this._max = Math.max(this._max, this._current);
  7076. this._average = this._totalAccumulated / this._totalValueCount;
  7077. // Reset last sec?
  7078. var now = Tools.Now;
  7079. if ((now - this._lastSecTime) > 1000) {
  7080. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7081. this._lastSecTime = now;
  7082. this._lastSecAccumulated = 0;
  7083. this._lastSecValueCount = 0;
  7084. }
  7085. };
  7086. PerfCounter.Enabled = true;
  7087. return PerfCounter;
  7088. }());
  7089. BABYLON.PerfCounter = PerfCounter;
  7090. /**
  7091. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7092. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7093. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7094. * @param name The name of the class, case should be preserved
  7095. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7096. */
  7097. function className(name, module) {
  7098. return function (target) {
  7099. target["__bjsclassName__"] = name;
  7100. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7101. };
  7102. }
  7103. BABYLON.className = className;
  7104. /**
  7105. * An implementation of a loop for asynchronous functions.
  7106. */
  7107. var AsyncLoop = /** @class */ (function () {
  7108. /**
  7109. * Constroctor.
  7110. * @param iterations the number of iterations.
  7111. * @param _fn the function to run each iteration
  7112. * @param _successCallback the callback that will be called upon succesful execution
  7113. * @param offset starting offset.
  7114. */
  7115. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7116. if (offset === void 0) { offset = 0; }
  7117. this.iterations = iterations;
  7118. this._fn = _fn;
  7119. this._successCallback = _successCallback;
  7120. this.index = offset - 1;
  7121. this._done = false;
  7122. }
  7123. /**
  7124. * Execute the next iteration. Must be called after the last iteration was finished.
  7125. */
  7126. AsyncLoop.prototype.executeNext = function () {
  7127. if (!this._done) {
  7128. if (this.index + 1 < this.iterations) {
  7129. ++this.index;
  7130. this._fn(this);
  7131. }
  7132. else {
  7133. this.breakLoop();
  7134. }
  7135. }
  7136. };
  7137. /**
  7138. * Break the loop and run the success callback.
  7139. */
  7140. AsyncLoop.prototype.breakLoop = function () {
  7141. this._done = true;
  7142. this._successCallback();
  7143. };
  7144. /**
  7145. * Helper function
  7146. */
  7147. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7148. if (offset === void 0) { offset = 0; }
  7149. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7150. loop.executeNext();
  7151. return loop;
  7152. };
  7153. /**
  7154. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7155. * @param iterations total number of iterations
  7156. * @param syncedIterations number of synchronous iterations in each async iteration.
  7157. * @param fn the function to call each iteration.
  7158. * @param callback a success call back that will be called when iterating stops.
  7159. * @param breakFunction a break condition (optional)
  7160. * @param timeout timeout settings for the setTimeout function. default - 0.
  7161. * @constructor
  7162. */
  7163. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7164. if (timeout === void 0) { timeout = 0; }
  7165. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7166. if (breakFunction && breakFunction())
  7167. loop.breakLoop();
  7168. else {
  7169. setTimeout(function () {
  7170. for (var i = 0; i < syncedIterations; ++i) {
  7171. var iteration = (loop.index * syncedIterations) + i;
  7172. if (iteration >= iterations)
  7173. break;
  7174. fn(iteration);
  7175. if (breakFunction && breakFunction()) {
  7176. loop.breakLoop();
  7177. break;
  7178. }
  7179. }
  7180. loop.executeNext();
  7181. }, timeout);
  7182. }
  7183. }, callback);
  7184. };
  7185. return AsyncLoop;
  7186. }());
  7187. BABYLON.AsyncLoop = AsyncLoop;
  7188. })(BABYLON || (BABYLON = {}));
  7189. //# sourceMappingURL=babylon.tools.js.map
  7190. var BABYLON;
  7191. (function (BABYLON) {
  7192. var Internals;
  7193. (function (Internals) {
  7194. var _AlphaState = /** @class */ (function () {
  7195. /**
  7196. * Initializes the state.
  7197. */
  7198. function _AlphaState() {
  7199. this._isAlphaBlendDirty = false;
  7200. this._isBlendFunctionParametersDirty = false;
  7201. this._isBlendEquationParametersDirty = false;
  7202. this._isBlendConstantsDirty = false;
  7203. this._alphaBlend = false;
  7204. this._blendFunctionParameters = new Array(4);
  7205. this._blendEquationParameters = new Array(2);
  7206. this._blendConstants = new Array(4);
  7207. this.reset();
  7208. }
  7209. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7210. get: function () {
  7211. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7212. },
  7213. enumerable: true,
  7214. configurable: true
  7215. });
  7216. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7217. get: function () {
  7218. return this._alphaBlend;
  7219. },
  7220. set: function (value) {
  7221. if (this._alphaBlend === value) {
  7222. return;
  7223. }
  7224. this._alphaBlend = value;
  7225. this._isAlphaBlendDirty = true;
  7226. },
  7227. enumerable: true,
  7228. configurable: true
  7229. });
  7230. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7231. if (this._blendConstants[0] === r &&
  7232. this._blendConstants[1] === g &&
  7233. this._blendConstants[2] === b &&
  7234. this._blendConstants[3] === a) {
  7235. return;
  7236. }
  7237. this._blendConstants[0] = r;
  7238. this._blendConstants[1] = g;
  7239. this._blendConstants[2] = b;
  7240. this._blendConstants[3] = a;
  7241. this._isBlendConstantsDirty = true;
  7242. };
  7243. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7244. if (this._blendFunctionParameters[0] === value0 &&
  7245. this._blendFunctionParameters[1] === value1 &&
  7246. this._blendFunctionParameters[2] === value2 &&
  7247. this._blendFunctionParameters[3] === value3) {
  7248. return;
  7249. }
  7250. this._blendFunctionParameters[0] = value0;
  7251. this._blendFunctionParameters[1] = value1;
  7252. this._blendFunctionParameters[2] = value2;
  7253. this._blendFunctionParameters[3] = value3;
  7254. this._isBlendFunctionParametersDirty = true;
  7255. };
  7256. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7257. if (this._blendEquationParameters[0] === rgb &&
  7258. this._blendEquationParameters[1] === alpha) {
  7259. return;
  7260. }
  7261. this._blendEquationParameters[0] = rgb;
  7262. this._blendEquationParameters[1] = alpha;
  7263. this._isBlendEquationParametersDirty = true;
  7264. };
  7265. _AlphaState.prototype.reset = function () {
  7266. this._alphaBlend = false;
  7267. this._blendFunctionParameters[0] = null;
  7268. this._blendFunctionParameters[1] = null;
  7269. this._blendFunctionParameters[2] = null;
  7270. this._blendFunctionParameters[3] = null;
  7271. this._blendEquationParameters[0] = null;
  7272. this._blendEquationParameters[1] = null;
  7273. this._blendConstants[0] = null;
  7274. this._blendConstants[1] = null;
  7275. this._blendConstants[2] = null;
  7276. this._blendConstants[3] = null;
  7277. this._isAlphaBlendDirty = true;
  7278. this._isBlendFunctionParametersDirty = false;
  7279. this._isBlendEquationParametersDirty = false;
  7280. this._isBlendConstantsDirty = false;
  7281. };
  7282. _AlphaState.prototype.apply = function (gl) {
  7283. if (!this.isDirty) {
  7284. return;
  7285. }
  7286. // Alpha blend
  7287. if (this._isAlphaBlendDirty) {
  7288. if (this._alphaBlend) {
  7289. gl.enable(gl.BLEND);
  7290. }
  7291. else {
  7292. gl.disable(gl.BLEND);
  7293. }
  7294. this._isAlphaBlendDirty = false;
  7295. }
  7296. // Alpha function
  7297. if (this._isBlendFunctionParametersDirty) {
  7298. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7299. this._isBlendFunctionParametersDirty = false;
  7300. }
  7301. // Alpha equation
  7302. if (this._isBlendEquationParametersDirty) {
  7303. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7304. this._isBlendEquationParametersDirty = false;
  7305. }
  7306. // Constants
  7307. if (this._isBlendConstantsDirty) {
  7308. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7309. this._isBlendConstantsDirty = false;
  7310. }
  7311. };
  7312. return _AlphaState;
  7313. }());
  7314. Internals._AlphaState = _AlphaState;
  7315. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7316. })(BABYLON || (BABYLON = {}));
  7317. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7318. var BABYLON;
  7319. (function (BABYLON) {
  7320. var Internals;
  7321. (function (Internals) {
  7322. var _DepthCullingState = /** @class */ (function () {
  7323. /**
  7324. * Initializes the state.
  7325. */
  7326. function _DepthCullingState() {
  7327. this._isDepthTestDirty = false;
  7328. this._isDepthMaskDirty = false;
  7329. this._isDepthFuncDirty = false;
  7330. this._isCullFaceDirty = false;
  7331. this._isCullDirty = false;
  7332. this._isZOffsetDirty = false;
  7333. this.reset();
  7334. }
  7335. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7336. get: function () {
  7337. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7338. },
  7339. enumerable: true,
  7340. configurable: true
  7341. });
  7342. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7343. get: function () {
  7344. return this._zOffset;
  7345. },
  7346. set: function (value) {
  7347. if (this._zOffset === value) {
  7348. return;
  7349. }
  7350. this._zOffset = value;
  7351. this._isZOffsetDirty = true;
  7352. },
  7353. enumerable: true,
  7354. configurable: true
  7355. });
  7356. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7357. get: function () {
  7358. return this._cullFace;
  7359. },
  7360. set: function (value) {
  7361. if (this._cullFace === value) {
  7362. return;
  7363. }
  7364. this._cullFace = value;
  7365. this._isCullFaceDirty = true;
  7366. },
  7367. enumerable: true,
  7368. configurable: true
  7369. });
  7370. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7371. get: function () {
  7372. return this._cull;
  7373. },
  7374. set: function (value) {
  7375. if (this._cull === value) {
  7376. return;
  7377. }
  7378. this._cull = value;
  7379. this._isCullDirty = true;
  7380. },
  7381. enumerable: true,
  7382. configurable: true
  7383. });
  7384. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7385. get: function () {
  7386. return this._depthFunc;
  7387. },
  7388. set: function (value) {
  7389. if (this._depthFunc === value) {
  7390. return;
  7391. }
  7392. this._depthFunc = value;
  7393. this._isDepthFuncDirty = true;
  7394. },
  7395. enumerable: true,
  7396. configurable: true
  7397. });
  7398. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7399. get: function () {
  7400. return this._depthMask;
  7401. },
  7402. set: function (value) {
  7403. if (this._depthMask === value) {
  7404. return;
  7405. }
  7406. this._depthMask = value;
  7407. this._isDepthMaskDirty = true;
  7408. },
  7409. enumerable: true,
  7410. configurable: true
  7411. });
  7412. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7413. get: function () {
  7414. return this._depthTest;
  7415. },
  7416. set: function (value) {
  7417. if (this._depthTest === value) {
  7418. return;
  7419. }
  7420. this._depthTest = value;
  7421. this._isDepthTestDirty = true;
  7422. },
  7423. enumerable: true,
  7424. configurable: true
  7425. });
  7426. _DepthCullingState.prototype.reset = function () {
  7427. this._depthMask = true;
  7428. this._depthTest = true;
  7429. this._depthFunc = null;
  7430. this._cullFace = null;
  7431. this._cull = null;
  7432. this._zOffset = 0;
  7433. this._isDepthTestDirty = true;
  7434. this._isDepthMaskDirty = true;
  7435. this._isDepthFuncDirty = false;
  7436. this._isCullFaceDirty = false;
  7437. this._isCullDirty = false;
  7438. this._isZOffsetDirty = false;
  7439. };
  7440. _DepthCullingState.prototype.apply = function (gl) {
  7441. if (!this.isDirty) {
  7442. return;
  7443. }
  7444. // Cull
  7445. if (this._isCullDirty) {
  7446. if (this.cull) {
  7447. gl.enable(gl.CULL_FACE);
  7448. }
  7449. else {
  7450. gl.disable(gl.CULL_FACE);
  7451. }
  7452. this._isCullDirty = false;
  7453. }
  7454. // Cull face
  7455. if (this._isCullFaceDirty) {
  7456. gl.cullFace(this.cullFace);
  7457. this._isCullFaceDirty = false;
  7458. }
  7459. // Depth mask
  7460. if (this._isDepthMaskDirty) {
  7461. gl.depthMask(this.depthMask);
  7462. this._isDepthMaskDirty = false;
  7463. }
  7464. // Depth test
  7465. if (this._isDepthTestDirty) {
  7466. if (this.depthTest) {
  7467. gl.enable(gl.DEPTH_TEST);
  7468. }
  7469. else {
  7470. gl.disable(gl.DEPTH_TEST);
  7471. }
  7472. this._isDepthTestDirty = false;
  7473. }
  7474. // Depth func
  7475. if (this._isDepthFuncDirty) {
  7476. gl.depthFunc(this.depthFunc);
  7477. this._isDepthFuncDirty = false;
  7478. }
  7479. // zOffset
  7480. if (this._isZOffsetDirty) {
  7481. if (this.zOffset) {
  7482. gl.enable(gl.POLYGON_OFFSET_FILL);
  7483. gl.polygonOffset(this.zOffset, 0);
  7484. }
  7485. else {
  7486. gl.disable(gl.POLYGON_OFFSET_FILL);
  7487. }
  7488. this._isZOffsetDirty = false;
  7489. }
  7490. };
  7491. return _DepthCullingState;
  7492. }());
  7493. Internals._DepthCullingState = _DepthCullingState;
  7494. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7495. })(BABYLON || (BABYLON = {}));
  7496. //# sourceMappingURL=babylon.depthCullingState.js.map
  7497. var BABYLON;
  7498. (function (BABYLON) {
  7499. var Internals;
  7500. (function (Internals) {
  7501. var _StencilState = /** @class */ (function () {
  7502. function _StencilState() {
  7503. this._isStencilTestDirty = false;
  7504. this._isStencilMaskDirty = false;
  7505. this._isStencilFuncDirty = false;
  7506. this._isStencilOpDirty = false;
  7507. this.reset();
  7508. }
  7509. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7510. get: function () {
  7511. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7512. },
  7513. enumerable: true,
  7514. configurable: true
  7515. });
  7516. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7517. get: function () {
  7518. return this._stencilFunc;
  7519. },
  7520. set: function (value) {
  7521. if (this._stencilFunc === value) {
  7522. return;
  7523. }
  7524. this._stencilFunc = value;
  7525. this._isStencilFuncDirty = true;
  7526. },
  7527. enumerable: true,
  7528. configurable: true
  7529. });
  7530. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7531. get: function () {
  7532. return this._stencilFuncRef;
  7533. },
  7534. set: function (value) {
  7535. if (this._stencilFuncRef === value) {
  7536. return;
  7537. }
  7538. this._stencilFuncRef = value;
  7539. this._isStencilFuncDirty = true;
  7540. },
  7541. enumerable: true,
  7542. configurable: true
  7543. });
  7544. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7545. get: function () {
  7546. return this._stencilFuncMask;
  7547. },
  7548. set: function (value) {
  7549. if (this._stencilFuncMask === value) {
  7550. return;
  7551. }
  7552. this._stencilFuncMask = value;
  7553. this._isStencilFuncDirty = true;
  7554. },
  7555. enumerable: true,
  7556. configurable: true
  7557. });
  7558. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7559. get: function () {
  7560. return this._stencilOpStencilFail;
  7561. },
  7562. set: function (value) {
  7563. if (this._stencilOpStencilFail === value) {
  7564. return;
  7565. }
  7566. this._stencilOpStencilFail = value;
  7567. this._isStencilOpDirty = true;
  7568. },
  7569. enumerable: true,
  7570. configurable: true
  7571. });
  7572. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7573. get: function () {
  7574. return this._stencilOpDepthFail;
  7575. },
  7576. set: function (value) {
  7577. if (this._stencilOpDepthFail === value) {
  7578. return;
  7579. }
  7580. this._stencilOpDepthFail = value;
  7581. this._isStencilOpDirty = true;
  7582. },
  7583. enumerable: true,
  7584. configurable: true
  7585. });
  7586. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7587. get: function () {
  7588. return this._stencilOpStencilDepthPass;
  7589. },
  7590. set: function (value) {
  7591. if (this._stencilOpStencilDepthPass === value) {
  7592. return;
  7593. }
  7594. this._stencilOpStencilDepthPass = value;
  7595. this._isStencilOpDirty = true;
  7596. },
  7597. enumerable: true,
  7598. configurable: true
  7599. });
  7600. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7601. get: function () {
  7602. return this._stencilMask;
  7603. },
  7604. set: function (value) {
  7605. if (this._stencilMask === value) {
  7606. return;
  7607. }
  7608. this._stencilMask = value;
  7609. this._isStencilMaskDirty = true;
  7610. },
  7611. enumerable: true,
  7612. configurable: true
  7613. });
  7614. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7615. get: function () {
  7616. return this._stencilTest;
  7617. },
  7618. set: function (value) {
  7619. if (this._stencilTest === value) {
  7620. return;
  7621. }
  7622. this._stencilTest = value;
  7623. this._isStencilTestDirty = true;
  7624. },
  7625. enumerable: true,
  7626. configurable: true
  7627. });
  7628. _StencilState.prototype.reset = function () {
  7629. this._stencilTest = false;
  7630. this._stencilMask = 0xFF;
  7631. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7632. this._stencilFuncRef = 1;
  7633. this._stencilFuncMask = 0xFF;
  7634. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7635. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7636. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7637. this._isStencilTestDirty = true;
  7638. this._isStencilMaskDirty = true;
  7639. this._isStencilFuncDirty = true;
  7640. this._isStencilOpDirty = true;
  7641. };
  7642. _StencilState.prototype.apply = function (gl) {
  7643. if (!this.isDirty) {
  7644. return;
  7645. }
  7646. // Stencil test
  7647. if (this._isStencilTestDirty) {
  7648. if (this.stencilTest) {
  7649. gl.enable(gl.STENCIL_TEST);
  7650. }
  7651. else {
  7652. gl.disable(gl.STENCIL_TEST);
  7653. }
  7654. this._isStencilTestDirty = false;
  7655. }
  7656. // Stencil mask
  7657. if (this._isStencilMaskDirty) {
  7658. gl.stencilMask(this.stencilMask);
  7659. this._isStencilMaskDirty = false;
  7660. }
  7661. // Stencil func
  7662. if (this._isStencilFuncDirty) {
  7663. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7664. this._isStencilFuncDirty = false;
  7665. }
  7666. // Stencil op
  7667. if (this._isStencilOpDirty) {
  7668. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7669. this._isStencilOpDirty = false;
  7670. }
  7671. };
  7672. return _StencilState;
  7673. }());
  7674. Internals._StencilState = _StencilState;
  7675. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7676. })(BABYLON || (BABYLON = {}));
  7677. //# sourceMappingURL=babylon.stencilState.js.map
  7678. var BABYLON;
  7679. (function (BABYLON) {
  7680. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7681. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7682. };
  7683. var compileRawShader = function (gl, source, type) {
  7684. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7685. gl.shaderSource(shader, source);
  7686. gl.compileShader(shader);
  7687. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7688. var log = gl.getShaderInfoLog(shader);
  7689. if (log) {
  7690. throw new Error(log);
  7691. }
  7692. }
  7693. if (!shader) {
  7694. throw new Error("Something went wrong while compile the shader.");
  7695. }
  7696. return shader;
  7697. };
  7698. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7699. var magFilter = gl.NEAREST;
  7700. var minFilter = gl.NEAREST;
  7701. switch (samplingMode) {
  7702. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7703. magFilter = gl.LINEAR;
  7704. if (generateMipMaps) {
  7705. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7706. }
  7707. else {
  7708. minFilter = gl.LINEAR;
  7709. }
  7710. break;
  7711. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7712. magFilter = gl.LINEAR;
  7713. if (generateMipMaps) {
  7714. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7715. }
  7716. else {
  7717. minFilter = gl.LINEAR;
  7718. }
  7719. break;
  7720. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7721. magFilter = gl.NEAREST;
  7722. if (generateMipMaps) {
  7723. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7724. }
  7725. else {
  7726. minFilter = gl.NEAREST;
  7727. }
  7728. break;
  7729. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7730. magFilter = gl.NEAREST;
  7731. if (generateMipMaps) {
  7732. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7733. }
  7734. else {
  7735. minFilter = gl.NEAREST;
  7736. }
  7737. break;
  7738. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7739. magFilter = gl.NEAREST;
  7740. if (generateMipMaps) {
  7741. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7742. }
  7743. else {
  7744. minFilter = gl.LINEAR;
  7745. }
  7746. break;
  7747. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7748. magFilter = gl.NEAREST;
  7749. if (generateMipMaps) {
  7750. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7751. }
  7752. else {
  7753. minFilter = gl.LINEAR;
  7754. }
  7755. break;
  7756. case BABYLON.Texture.NEAREST_LINEAR:
  7757. magFilter = gl.NEAREST;
  7758. minFilter = gl.LINEAR;
  7759. break;
  7760. case BABYLON.Texture.NEAREST_NEAREST:
  7761. magFilter = gl.NEAREST;
  7762. minFilter = gl.NEAREST;
  7763. break;
  7764. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7765. magFilter = gl.LINEAR;
  7766. if (generateMipMaps) {
  7767. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7768. }
  7769. else {
  7770. minFilter = gl.NEAREST;
  7771. }
  7772. break;
  7773. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7774. magFilter = gl.LINEAR;
  7775. if (generateMipMaps) {
  7776. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7777. }
  7778. else {
  7779. minFilter = gl.NEAREST;
  7780. }
  7781. break;
  7782. case BABYLON.Texture.LINEAR_LINEAR:
  7783. magFilter = gl.LINEAR;
  7784. minFilter = gl.LINEAR;
  7785. break;
  7786. case BABYLON.Texture.LINEAR_NEAREST:
  7787. magFilter = gl.LINEAR;
  7788. minFilter = gl.NEAREST;
  7789. break;
  7790. }
  7791. return {
  7792. min: minFilter,
  7793. mag: magFilter
  7794. };
  7795. };
  7796. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7797. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7798. var img;
  7799. var onload = function () {
  7800. loadedImages[index] = img;
  7801. loadedImages._internalCount++;
  7802. if (scene) {
  7803. scene._removePendingData(img);
  7804. }
  7805. if (loadedImages._internalCount === 6) {
  7806. onfinish(loadedImages);
  7807. }
  7808. };
  7809. var onerror = function (message, exception) {
  7810. if (scene) {
  7811. scene._removePendingData(img);
  7812. }
  7813. if (onErrorCallBack) {
  7814. onErrorCallBack(message, exception);
  7815. }
  7816. };
  7817. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7818. if (scene) {
  7819. scene._addPendingData(img);
  7820. }
  7821. };
  7822. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  7823. if (onError === void 0) { onError = null; }
  7824. var loadedImages = [];
  7825. loadedImages._internalCount = 0;
  7826. for (var index = 0; index < 6; index++) {
  7827. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  7828. }
  7829. };
  7830. var partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  7831. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7832. var onload = function (data) {
  7833. loadedFiles[index] = data;
  7834. loadedFiles._internalCount++;
  7835. if (loadedFiles._internalCount === 6) {
  7836. onfinish(loadedFiles);
  7837. }
  7838. };
  7839. var onerror = function (request, exception) {
  7840. if (onErrorCallBack && request) {
  7841. onErrorCallBack(request.status + " " + request.statusText, exception);
  7842. }
  7843. };
  7844. BABYLON.Tools.LoadFile(url, onload, undefined, undefined, true, onerror);
  7845. };
  7846. var cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  7847. if (onError === void 0) { onError = null; }
  7848. var loadedFiles = [];
  7849. loadedFiles._internalCount = 0;
  7850. for (var index = 0; index < 6; index++) {
  7851. partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  7852. }
  7853. };
  7854. var BufferPointer = /** @class */ (function () {
  7855. function BufferPointer() {
  7856. }
  7857. return BufferPointer;
  7858. }());
  7859. var InstancingAttributeInfo = /** @class */ (function () {
  7860. function InstancingAttributeInfo() {
  7861. }
  7862. return InstancingAttributeInfo;
  7863. }());
  7864. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7865. /**
  7866. * Define options used to create a render target texture
  7867. */
  7868. var RenderTargetCreationOptions = /** @class */ (function () {
  7869. function RenderTargetCreationOptions() {
  7870. }
  7871. return RenderTargetCreationOptions;
  7872. }());
  7873. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7874. /**
  7875. * Regroup several parameters relative to the browser in use
  7876. */
  7877. var EngineCapabilities = /** @class */ (function () {
  7878. function EngineCapabilities() {
  7879. }
  7880. return EngineCapabilities;
  7881. }());
  7882. BABYLON.EngineCapabilities = EngineCapabilities;
  7883. /**
  7884. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7885. */
  7886. var Engine = /** @class */ (function () {
  7887. /**
  7888. * @constructor
  7889. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7890. * @param {boolean} [antialias] - enable antialias
  7891. * @param options - further options to be sent to the getContext function
  7892. */
  7893. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7894. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7895. var _this = this;
  7896. // Public members
  7897. this.forcePOTTextures = false;
  7898. this.isFullscreen = false;
  7899. this.isPointerLock = false;
  7900. this.cullBackFaces = true;
  7901. this.renderEvenInBackground = true;
  7902. this.preventCacheWipeBetweenFrames = false;
  7903. // To enable/disable IDB support and avoid XHR on .manifest
  7904. this.enableOfflineSupport = false;
  7905. this.scenes = new Array();
  7906. this.postProcesses = new Array();
  7907. // Observables
  7908. /**
  7909. * Observable event triggered each time the rendering canvas is resized
  7910. */
  7911. this.onResizeObservable = new BABYLON.Observable();
  7912. /**
  7913. * Observable event triggered each time the canvas loses focus
  7914. */
  7915. this.onCanvasBlurObservable = new BABYLON.Observable();
  7916. /**
  7917. * Observable event triggered each time the canvas gains focus
  7918. */
  7919. this.onCanvasFocusObservable = new BABYLON.Observable();
  7920. /**
  7921. * Observable event triggered each time the canvas receives pointerout event
  7922. */
  7923. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7924. /**
  7925. * Observable event triggered before each texture is initialized
  7926. */
  7927. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7928. //WebVR
  7929. this._vrDisplay = undefined;
  7930. this._vrSupported = false;
  7931. this._vrExclusivePointerMode = false;
  7932. // Uniform buffers list
  7933. this.disableUniformBuffers = false;
  7934. this._uniformBuffers = new Array();
  7935. // Observables
  7936. /**
  7937. * Observable raised when the engine begins a new frame
  7938. */
  7939. this.onBeginFrameObservable = new BABYLON.Observable();
  7940. /**
  7941. * Observable raised when the engine ends the current frame
  7942. */
  7943. this.onEndFrameObservable = new BABYLON.Observable();
  7944. /**
  7945. * Observable raised when the engine is about to compile a shader
  7946. */
  7947. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  7948. /**
  7949. * Observable raised when the engine has jsut compiled a shader
  7950. */
  7951. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  7952. this._windowIsBackground = false;
  7953. this._webGLVersion = 1.0;
  7954. this._badOS = false;
  7955. this._badDesktopOS = false;
  7956. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7957. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7958. this.onVRRequestPresentStart = new BABYLON.Observable();
  7959. this._colorWrite = true;
  7960. this._drawCalls = new BABYLON.PerfCounter();
  7961. this._renderingQueueLaunched = false;
  7962. this._activeRenderLoops = new Array();
  7963. // Deterministic lockstepMaxSteps
  7964. this._deterministicLockstep = false;
  7965. this._lockstepMaxSteps = 4;
  7966. // Lost context
  7967. this.onContextLostObservable = new BABYLON.Observable();
  7968. this.onContextRestoredObservable = new BABYLON.Observable();
  7969. this._contextWasLost = false;
  7970. this._doNotHandleContextLost = false;
  7971. // FPS
  7972. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7973. this._fps = 60;
  7974. this._deltaTime = 0;
  7975. /**
  7976. * Turn this value on if you want to pause FPS computation when in background
  7977. */
  7978. this.disablePerformanceMonitorInBackground = false;
  7979. // States
  7980. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7981. this._stencilState = new BABYLON.Internals._StencilState();
  7982. this._alphaState = new BABYLON.Internals._AlphaState();
  7983. this._alphaMode = Engine.ALPHA_DISABLE;
  7984. // Cache
  7985. this._internalTexturesCache = new Array();
  7986. this._activeTexturesCache = {};
  7987. this._compiledEffects = {};
  7988. this._vertexAttribArraysEnabled = [];
  7989. this._uintIndicesCurrentlySet = false;
  7990. this._currentBoundBuffer = new Array();
  7991. this._currentBufferPointers = new Array();
  7992. this._currentInstanceLocations = new Array();
  7993. this._currentInstanceBuffers = new Array();
  7994. this._vaoRecordInProgress = false;
  7995. this._mustWipeVertexAttributes = false;
  7996. // Hardware supported Compressed Textures
  7997. this._texturesSupported = new Array();
  7998. this._onVRFullScreenTriggered = function () {
  7999. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8000. //get the old size before we change
  8001. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8002. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8003. //get the width and height, change the render size
  8004. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8005. _this.setHardwareScalingLevel(1);
  8006. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8007. }
  8008. else {
  8009. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8010. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8011. }
  8012. };
  8013. var canvas = null;
  8014. Engine.Instances.push(this);
  8015. if (!canvasOrContext) {
  8016. return;
  8017. }
  8018. options = options || {};
  8019. if (canvasOrContext.getContext) {
  8020. canvas = canvasOrContext;
  8021. this._renderingCanvas = canvas;
  8022. if (antialias != null) {
  8023. options.antialias = antialias;
  8024. }
  8025. if (options.deterministicLockstep === undefined) {
  8026. options.deterministicLockstep = false;
  8027. }
  8028. if (options.lockstepMaxSteps === undefined) {
  8029. options.lockstepMaxSteps = 4;
  8030. }
  8031. if (options.preserveDrawingBuffer === undefined) {
  8032. options.preserveDrawingBuffer = false;
  8033. }
  8034. if (options.audioEngine === undefined) {
  8035. options.audioEngine = true;
  8036. }
  8037. if (options.stencil === undefined) {
  8038. options.stencil = true;
  8039. }
  8040. this._deterministicLockstep = options.deterministicLockstep;
  8041. this._lockstepMaxSteps = options.lockstepMaxSteps;
  8042. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  8043. // GL
  8044. if (!options.disableWebGL2Support) {
  8045. try {
  8046. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  8047. if (this._gl) {
  8048. this._webGLVersion = 2.0;
  8049. }
  8050. }
  8051. catch (e) {
  8052. // Do nothing
  8053. }
  8054. }
  8055. if (!this._gl) {
  8056. if (!canvas) {
  8057. throw new Error("The provided canvas is null or undefined.");
  8058. }
  8059. try {
  8060. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  8061. }
  8062. catch (e) {
  8063. throw new Error("WebGL not supported");
  8064. }
  8065. }
  8066. if (!this._gl) {
  8067. throw new Error("WebGL not supported");
  8068. }
  8069. this._onCanvasFocus = function () {
  8070. _this.onCanvasFocusObservable.notifyObservers(_this);
  8071. };
  8072. this._onCanvasBlur = function () {
  8073. _this.onCanvasBlurObservable.notifyObservers(_this);
  8074. };
  8075. canvas.addEventListener("focus", this._onCanvasFocus);
  8076. canvas.addEventListener("blur", this._onCanvasBlur);
  8077. this._onBlur = function () {
  8078. if (_this.disablePerformanceMonitorInBackground) {
  8079. _this._performanceMonitor.disable();
  8080. }
  8081. _this._windowIsBackground = true;
  8082. };
  8083. this._onFocus = function () {
  8084. if (_this.disablePerformanceMonitorInBackground) {
  8085. _this._performanceMonitor.enable();
  8086. }
  8087. _this._windowIsBackground = false;
  8088. };
  8089. this._onCanvasPointerOut = function () {
  8090. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8091. };
  8092. window.addEventListener("blur", this._onBlur);
  8093. window.addEventListener("focus", this._onFocus);
  8094. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8095. // Context lost
  8096. if (!this._doNotHandleContextLost) {
  8097. this._onContextLost = function (evt) {
  8098. evt.preventDefault();
  8099. _this._contextWasLost = true;
  8100. BABYLON.Tools.Warn("WebGL context lost.");
  8101. _this.onContextLostObservable.notifyObservers(_this);
  8102. };
  8103. this._onContextRestored = function (evt) {
  8104. // Adding a timeout to avoid race condition at browser level
  8105. setTimeout(function () {
  8106. // Rebuild gl context
  8107. _this._initGLContext();
  8108. // Rebuild effects
  8109. _this._rebuildEffects();
  8110. // Rebuild textures
  8111. _this._rebuildInternalTextures();
  8112. // Rebuild buffers
  8113. _this._rebuildBuffers();
  8114. // Cache
  8115. _this.wipeCaches(true);
  8116. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8117. _this.onContextRestoredObservable.notifyObservers(_this);
  8118. _this._contextWasLost = false;
  8119. }, 0);
  8120. };
  8121. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8122. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8123. }
  8124. }
  8125. else {
  8126. this._gl = canvasOrContext;
  8127. this._renderingCanvas = this._gl.canvas;
  8128. if (this._gl.renderbufferStorageMultisample) {
  8129. this._webGLVersion = 2.0;
  8130. }
  8131. options.stencil = this._gl.getContextAttributes().stencil;
  8132. }
  8133. // Viewport
  8134. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8135. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8136. this.resize();
  8137. this._isStencilEnable = options.stencil ? true : false;
  8138. this._initGLContext();
  8139. if (canvas) {
  8140. // Fullscreen
  8141. this._onFullscreenChange = function () {
  8142. if (document.fullscreen !== undefined) {
  8143. _this.isFullscreen = document.fullscreen;
  8144. }
  8145. else if (document.mozFullScreen !== undefined) {
  8146. _this.isFullscreen = document.mozFullScreen;
  8147. }
  8148. else if (document.webkitIsFullScreen !== undefined) {
  8149. _this.isFullscreen = document.webkitIsFullScreen;
  8150. }
  8151. else if (document.msIsFullScreen !== undefined) {
  8152. _this.isFullscreen = document.msIsFullScreen;
  8153. }
  8154. // Pointer lock
  8155. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8156. canvas.requestPointerLock = canvas.requestPointerLock ||
  8157. canvas.msRequestPointerLock ||
  8158. canvas.mozRequestPointerLock ||
  8159. canvas.webkitRequestPointerLock;
  8160. if (canvas.requestPointerLock) {
  8161. canvas.requestPointerLock();
  8162. }
  8163. }
  8164. };
  8165. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8166. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8167. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8168. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8169. // Pointer lock
  8170. this._onPointerLockChange = function () {
  8171. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8172. document.webkitPointerLockElement === canvas ||
  8173. document.msPointerLockElement === canvas ||
  8174. document.pointerLockElement === canvas);
  8175. };
  8176. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8177. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8178. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8179. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8180. this._onVRDisplayPointerRestricted = function () {
  8181. if (canvas) {
  8182. canvas.requestPointerLock();
  8183. }
  8184. };
  8185. this._onVRDisplayPointerUnrestricted = function () {
  8186. document.exitPointerLock();
  8187. };
  8188. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8189. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8190. }
  8191. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8192. Engine.audioEngine = new BABYLON.AudioEngine();
  8193. }
  8194. // Prepare buffer pointers
  8195. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8196. this._currentBufferPointers[i] = new BufferPointer();
  8197. }
  8198. // Load WebVR Devices
  8199. if (options.autoEnableWebVR) {
  8200. this.initWebVR();
  8201. }
  8202. // Detect if we are running on a faulty buggy OS.
  8203. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8204. // Detect if we are running on a faulty buggy desktop OS.
  8205. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8206. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8207. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8208. }
  8209. Object.defineProperty(Engine, "LastCreatedEngine", {
  8210. get: function () {
  8211. if (Engine.Instances.length === 0) {
  8212. return null;
  8213. }
  8214. return Engine.Instances[Engine.Instances.length - 1];
  8215. },
  8216. enumerable: true,
  8217. configurable: true
  8218. });
  8219. Object.defineProperty(Engine, "LastCreatedScene", {
  8220. get: function () {
  8221. var lastCreatedEngine = Engine.LastCreatedEngine;
  8222. if (!lastCreatedEngine) {
  8223. return null;
  8224. }
  8225. if (lastCreatedEngine.scenes.length === 0) {
  8226. return null;
  8227. }
  8228. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8229. },
  8230. enumerable: true,
  8231. configurable: true
  8232. });
  8233. /**
  8234. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8235. */
  8236. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8237. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8238. var engine = Engine.Instances[engineIndex];
  8239. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8240. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8241. }
  8242. }
  8243. };
  8244. Object.defineProperty(Engine, "NEVER", {
  8245. get: function () {
  8246. return Engine._NEVER;
  8247. },
  8248. enumerable: true,
  8249. configurable: true
  8250. });
  8251. Object.defineProperty(Engine, "ALWAYS", {
  8252. get: function () {
  8253. return Engine._ALWAYS;
  8254. },
  8255. enumerable: true,
  8256. configurable: true
  8257. });
  8258. Object.defineProperty(Engine, "LESS", {
  8259. get: function () {
  8260. return Engine._LESS;
  8261. },
  8262. enumerable: true,
  8263. configurable: true
  8264. });
  8265. Object.defineProperty(Engine, "EQUAL", {
  8266. get: function () {
  8267. return Engine._EQUAL;
  8268. },
  8269. enumerable: true,
  8270. configurable: true
  8271. });
  8272. Object.defineProperty(Engine, "LEQUAL", {
  8273. get: function () {
  8274. return Engine._LEQUAL;
  8275. },
  8276. enumerable: true,
  8277. configurable: true
  8278. });
  8279. Object.defineProperty(Engine, "GREATER", {
  8280. get: function () {
  8281. return Engine._GREATER;
  8282. },
  8283. enumerable: true,
  8284. configurable: true
  8285. });
  8286. Object.defineProperty(Engine, "GEQUAL", {
  8287. get: function () {
  8288. return Engine._GEQUAL;
  8289. },
  8290. enumerable: true,
  8291. configurable: true
  8292. });
  8293. Object.defineProperty(Engine, "NOTEQUAL", {
  8294. get: function () {
  8295. return Engine._NOTEQUAL;
  8296. },
  8297. enumerable: true,
  8298. configurable: true
  8299. });
  8300. Object.defineProperty(Engine, "KEEP", {
  8301. get: function () {
  8302. return Engine._KEEP;
  8303. },
  8304. enumerable: true,
  8305. configurable: true
  8306. });
  8307. Object.defineProperty(Engine, "REPLACE", {
  8308. get: function () {
  8309. return Engine._REPLACE;
  8310. },
  8311. enumerable: true,
  8312. configurable: true
  8313. });
  8314. Object.defineProperty(Engine, "INCR", {
  8315. get: function () {
  8316. return Engine._INCR;
  8317. },
  8318. enumerable: true,
  8319. configurable: true
  8320. });
  8321. Object.defineProperty(Engine, "DECR", {
  8322. get: function () {
  8323. return Engine._DECR;
  8324. },
  8325. enumerable: true,
  8326. configurable: true
  8327. });
  8328. Object.defineProperty(Engine, "INVERT", {
  8329. get: function () {
  8330. return Engine._INVERT;
  8331. },
  8332. enumerable: true,
  8333. configurable: true
  8334. });
  8335. Object.defineProperty(Engine, "INCR_WRAP", {
  8336. get: function () {
  8337. return Engine._INCR_WRAP;
  8338. },
  8339. enumerable: true,
  8340. configurable: true
  8341. });
  8342. Object.defineProperty(Engine, "DECR_WRAP", {
  8343. get: function () {
  8344. return Engine._DECR_WRAP;
  8345. },
  8346. enumerable: true,
  8347. configurable: true
  8348. });
  8349. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8350. get: function () {
  8351. return Engine._ALPHA_DISABLE;
  8352. },
  8353. enumerable: true,
  8354. configurable: true
  8355. });
  8356. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8357. get: function () {
  8358. return Engine._ALPHA_ONEONE;
  8359. },
  8360. enumerable: true,
  8361. configurable: true
  8362. });
  8363. Object.defineProperty(Engine, "ALPHA_ADD", {
  8364. get: function () {
  8365. return Engine._ALPHA_ADD;
  8366. },
  8367. enumerable: true,
  8368. configurable: true
  8369. });
  8370. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8371. get: function () {
  8372. return Engine._ALPHA_COMBINE;
  8373. },
  8374. enumerable: true,
  8375. configurable: true
  8376. });
  8377. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8378. get: function () {
  8379. return Engine._ALPHA_SUBTRACT;
  8380. },
  8381. enumerable: true,
  8382. configurable: true
  8383. });
  8384. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8385. get: function () {
  8386. return Engine._ALPHA_MULTIPLY;
  8387. },
  8388. enumerable: true,
  8389. configurable: true
  8390. });
  8391. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8392. get: function () {
  8393. return Engine._ALPHA_MAXIMIZED;
  8394. },
  8395. enumerable: true,
  8396. configurable: true
  8397. });
  8398. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8399. get: function () {
  8400. return Engine._ALPHA_PREMULTIPLIED;
  8401. },
  8402. enumerable: true,
  8403. configurable: true
  8404. });
  8405. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8406. get: function () {
  8407. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8408. },
  8409. enumerable: true,
  8410. configurable: true
  8411. });
  8412. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8413. get: function () {
  8414. return Engine._ALPHA_INTERPOLATE;
  8415. },
  8416. enumerable: true,
  8417. configurable: true
  8418. });
  8419. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8420. get: function () {
  8421. return Engine._ALPHA_SCREENMODE;
  8422. },
  8423. enumerable: true,
  8424. configurable: true
  8425. });
  8426. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8427. get: function () {
  8428. return Engine._DELAYLOADSTATE_NONE;
  8429. },
  8430. enumerable: true,
  8431. configurable: true
  8432. });
  8433. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8434. get: function () {
  8435. return Engine._DELAYLOADSTATE_LOADED;
  8436. },
  8437. enumerable: true,
  8438. configurable: true
  8439. });
  8440. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8441. get: function () {
  8442. return Engine._DELAYLOADSTATE_LOADING;
  8443. },
  8444. enumerable: true,
  8445. configurable: true
  8446. });
  8447. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8448. get: function () {
  8449. return Engine._DELAYLOADSTATE_NOTLOADED;
  8450. },
  8451. enumerable: true,
  8452. configurable: true
  8453. });
  8454. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8455. get: function () {
  8456. return Engine._TEXTUREFORMAT_ALPHA;
  8457. },
  8458. enumerable: true,
  8459. configurable: true
  8460. });
  8461. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8462. get: function () {
  8463. return Engine._TEXTUREFORMAT_LUMINANCE;
  8464. },
  8465. enumerable: true,
  8466. configurable: true
  8467. });
  8468. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8469. get: function () {
  8470. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8471. },
  8472. enumerable: true,
  8473. configurable: true
  8474. });
  8475. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8476. get: function () {
  8477. return Engine._TEXTUREFORMAT_RGB;
  8478. },
  8479. enumerable: true,
  8480. configurable: true
  8481. });
  8482. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8483. get: function () {
  8484. return Engine._TEXTUREFORMAT_RGBA;
  8485. },
  8486. enumerable: true,
  8487. configurable: true
  8488. });
  8489. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8490. get: function () {
  8491. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8492. },
  8493. enumerable: true,
  8494. configurable: true
  8495. });
  8496. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8497. get: function () {
  8498. return Engine._TEXTURETYPE_FLOAT;
  8499. },
  8500. enumerable: true,
  8501. configurable: true
  8502. });
  8503. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8504. get: function () {
  8505. return Engine._TEXTURETYPE_HALF_FLOAT;
  8506. },
  8507. enumerable: true,
  8508. configurable: true
  8509. });
  8510. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8511. get: function () {
  8512. return Engine._SCALEMODE_FLOOR;
  8513. },
  8514. enumerable: true,
  8515. configurable: true
  8516. });
  8517. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8518. get: function () {
  8519. return Engine._SCALEMODE_NEAREST;
  8520. },
  8521. enumerable: true,
  8522. configurable: true
  8523. });
  8524. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8525. get: function () {
  8526. return Engine._SCALEMODE_CEILING;
  8527. },
  8528. enumerable: true,
  8529. configurable: true
  8530. });
  8531. Object.defineProperty(Engine, "Version", {
  8532. get: function () {
  8533. return "3.1-beta-5";
  8534. },
  8535. enumerable: true,
  8536. configurable: true
  8537. });
  8538. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8539. get: function () {
  8540. return this._vrExclusivePointerMode;
  8541. },
  8542. enumerable: true,
  8543. configurable: true
  8544. });
  8545. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8546. get: function () {
  8547. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8548. },
  8549. enumerable: true,
  8550. configurable: true
  8551. });
  8552. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8553. get: function () {
  8554. return this._webGLVersion < 2 || this.forcePOTTextures;
  8555. },
  8556. enumerable: true,
  8557. configurable: true
  8558. });
  8559. Object.defineProperty(Engine.prototype, "badOS", {
  8560. get: function () {
  8561. return this._badOS;
  8562. },
  8563. enumerable: true,
  8564. configurable: true
  8565. });
  8566. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8567. get: function () {
  8568. return this._badDesktopOS;
  8569. },
  8570. enumerable: true,
  8571. configurable: true
  8572. });
  8573. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8574. get: function () {
  8575. return this._performanceMonitor;
  8576. },
  8577. enumerable: true,
  8578. configurable: true
  8579. });
  8580. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8581. get: function () {
  8582. return this._texturesSupported;
  8583. },
  8584. enumerable: true,
  8585. configurable: true
  8586. });
  8587. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8588. get: function () {
  8589. return this._textureFormatInUse;
  8590. },
  8591. enumerable: true,
  8592. configurable: true
  8593. });
  8594. Object.defineProperty(Engine.prototype, "currentViewport", {
  8595. get: function () {
  8596. return this._cachedViewport;
  8597. },
  8598. enumerable: true,
  8599. configurable: true
  8600. });
  8601. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8602. // Empty texture
  8603. get: function () {
  8604. if (!this._emptyTexture) {
  8605. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8606. }
  8607. return this._emptyTexture;
  8608. },
  8609. enumerable: true,
  8610. configurable: true
  8611. });
  8612. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8613. get: function () {
  8614. if (!this._emptyTexture3D) {
  8615. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8616. }
  8617. return this._emptyTexture3D;
  8618. },
  8619. enumerable: true,
  8620. configurable: true
  8621. });
  8622. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8623. get: function () {
  8624. if (!this._emptyCubeTexture) {
  8625. var faceData = new Uint8Array(4);
  8626. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8627. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8628. }
  8629. return this._emptyCubeTexture;
  8630. },
  8631. enumerable: true,
  8632. configurable: true
  8633. });
  8634. Engine.prototype._rebuildInternalTextures = function () {
  8635. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8636. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8637. var internalTexture = currentState_1[_i];
  8638. internalTexture._rebuild();
  8639. }
  8640. };
  8641. Engine.prototype._rebuildEffects = function () {
  8642. for (var key in this._compiledEffects) {
  8643. var effect = this._compiledEffects[key];
  8644. effect._prepareEffect();
  8645. }
  8646. BABYLON.Effect.ResetCache();
  8647. };
  8648. Engine.prototype._rebuildBuffers = function () {
  8649. // Index / Vertex
  8650. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8651. var scene = _a[_i];
  8652. scene.resetCachedMaterial();
  8653. scene._rebuildGeometries();
  8654. scene._rebuildTextures();
  8655. }
  8656. // Uniforms
  8657. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8658. var uniformBuffer = _c[_b];
  8659. uniformBuffer._rebuild();
  8660. }
  8661. };
  8662. Engine.prototype._initGLContext = function () {
  8663. // Caps
  8664. this._caps = new EngineCapabilities();
  8665. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8666. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8667. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8668. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8669. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8670. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8671. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8672. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8673. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8674. // Infos
  8675. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8676. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8677. if (rendererInfo != null) {
  8678. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8679. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8680. }
  8681. if (!this._glVendor) {
  8682. this._glVendor = "Unknown vendor";
  8683. }
  8684. if (!this._glRenderer) {
  8685. this._glRenderer = "Unknown renderer";
  8686. }
  8687. // Constants
  8688. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8689. if (this._gl.RGBA16F !== 0x881A) {
  8690. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8691. }
  8692. if (this._gl.RGBA32F !== 0x8814) {
  8693. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8694. }
  8695. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8696. this._gl.DEPTH24_STENCIL8 = 35056;
  8697. }
  8698. // Extensions
  8699. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8700. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8701. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8702. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8703. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8704. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8705. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8706. 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');
  8707. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8708. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8709. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8710. this._caps.highPrecisionShaderSupported = true;
  8711. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8712. if (this._caps.timerQuery) {
  8713. if (this._webGLVersion === 1) {
  8714. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8715. }
  8716. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8717. }
  8718. // Checks if some of the format renders first to allow the use of webgl inspector.
  8719. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8720. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8721. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8722. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8723. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8724. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8725. if (this._webGLVersion > 1) {
  8726. this._gl.HALF_FLOAT_OES = 0x140B;
  8727. }
  8728. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8729. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8730. // Draw buffers
  8731. if (this._webGLVersion > 1) {
  8732. this._caps.drawBuffersExtension = true;
  8733. }
  8734. else {
  8735. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8736. if (drawBuffersExtension !== null) {
  8737. this._caps.drawBuffersExtension = true;
  8738. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8739. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8740. for (var i = 0; i < 16; i++) {
  8741. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8742. }
  8743. }
  8744. else {
  8745. this._caps.drawBuffersExtension = false;
  8746. }
  8747. }
  8748. // Depth Texture
  8749. if (this._webGLVersion > 1) {
  8750. this._caps.depthTextureExtension = true;
  8751. }
  8752. else {
  8753. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8754. if (depthTextureExtension != null) {
  8755. this._caps.depthTextureExtension = true;
  8756. }
  8757. }
  8758. // Vertex array object
  8759. if (this._webGLVersion > 1) {
  8760. this._caps.vertexArrayObject = true;
  8761. }
  8762. else {
  8763. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8764. if (vertexArrayObjectExtension != null) {
  8765. this._caps.vertexArrayObject = true;
  8766. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8767. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8768. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8769. }
  8770. else {
  8771. this._caps.vertexArrayObject = false;
  8772. }
  8773. }
  8774. // Instances count
  8775. if (this._webGLVersion > 1) {
  8776. this._caps.instancedArrays = true;
  8777. }
  8778. else {
  8779. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8780. if (instanceExtension != null) {
  8781. this._caps.instancedArrays = true;
  8782. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8783. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8784. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8785. }
  8786. else {
  8787. this._caps.instancedArrays = false;
  8788. }
  8789. }
  8790. // Intelligently add supported compressed formats in order to check for.
  8791. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8792. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8793. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8794. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8795. if (this._caps.astc)
  8796. this.texturesSupported.push('-astc.ktx');
  8797. if (this._caps.s3tc)
  8798. this.texturesSupported.push('-dxt.ktx');
  8799. if (this._caps.pvrtc)
  8800. this.texturesSupported.push('-pvrtc.ktx');
  8801. if (this._caps.etc2)
  8802. this.texturesSupported.push('-etc2.ktx');
  8803. if (this._caps.etc1)
  8804. this.texturesSupported.push('-etc1.ktx');
  8805. if (this._gl.getShaderPrecisionFormat) {
  8806. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8807. if (highp) {
  8808. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8809. }
  8810. }
  8811. // Depth buffer
  8812. this.setDepthBuffer(true);
  8813. this.setDepthFunctionToLessOrEqual();
  8814. this.setDepthWrite(true);
  8815. };
  8816. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8817. get: function () {
  8818. return this._webGLVersion;
  8819. },
  8820. enumerable: true,
  8821. configurable: true
  8822. });
  8823. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8824. /**
  8825. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8826. */
  8827. get: function () {
  8828. return this._isStencilEnable;
  8829. },
  8830. enumerable: true,
  8831. configurable: true
  8832. });
  8833. Engine.prototype._prepareWorkingCanvas = function () {
  8834. if (this._workingCanvas) {
  8835. return;
  8836. }
  8837. this._workingCanvas = document.createElement("canvas");
  8838. var context = this._workingCanvas.getContext("2d");
  8839. if (context) {
  8840. this._workingContext = context;
  8841. }
  8842. };
  8843. Engine.prototype.resetTextureCache = function () {
  8844. for (var key in this._activeTexturesCache) {
  8845. this._activeTexturesCache[key] = null;
  8846. }
  8847. };
  8848. Engine.prototype.isDeterministicLockStep = function () {
  8849. return this._deterministicLockstep;
  8850. };
  8851. Engine.prototype.getLockstepMaxSteps = function () {
  8852. return this._lockstepMaxSteps;
  8853. };
  8854. Engine.prototype.getGlInfo = function () {
  8855. return {
  8856. vendor: this._glVendor,
  8857. renderer: this._glRenderer,
  8858. version: this._glVersion
  8859. };
  8860. };
  8861. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8862. if (useScreen === void 0) { useScreen = false; }
  8863. var viewport = camera.viewport;
  8864. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8865. };
  8866. Engine.prototype.getRenderWidth = function (useScreen) {
  8867. if (useScreen === void 0) { useScreen = false; }
  8868. if (!useScreen && this._currentRenderTarget) {
  8869. return this._currentRenderTarget.width;
  8870. }
  8871. return this._gl.drawingBufferWidth;
  8872. };
  8873. Engine.prototype.getRenderHeight = function (useScreen) {
  8874. if (useScreen === void 0) { useScreen = false; }
  8875. if (!useScreen && this._currentRenderTarget) {
  8876. return this._currentRenderTarget.height;
  8877. }
  8878. return this._gl.drawingBufferHeight;
  8879. };
  8880. Engine.prototype.getRenderingCanvas = function () {
  8881. return this._renderingCanvas;
  8882. };
  8883. Engine.prototype.getRenderingCanvasClientRect = function () {
  8884. if (!this._renderingCanvas) {
  8885. return null;
  8886. }
  8887. return this._renderingCanvas.getBoundingClientRect();
  8888. };
  8889. Engine.prototype.setHardwareScalingLevel = function (level) {
  8890. this._hardwareScalingLevel = level;
  8891. this.resize();
  8892. };
  8893. Engine.prototype.getHardwareScalingLevel = function () {
  8894. return this._hardwareScalingLevel;
  8895. };
  8896. Engine.prototype.getLoadedTexturesCache = function () {
  8897. return this._internalTexturesCache;
  8898. };
  8899. Engine.prototype.getCaps = function () {
  8900. return this._caps;
  8901. };
  8902. Object.defineProperty(Engine.prototype, "drawCalls", {
  8903. /** The number of draw calls submitted last frame */
  8904. get: function () {
  8905. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  8906. return 0;
  8907. },
  8908. enumerable: true,
  8909. configurable: true
  8910. });
  8911. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8912. get: function () {
  8913. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  8914. return null;
  8915. },
  8916. enumerable: true,
  8917. configurable: true
  8918. });
  8919. Engine.prototype.getDepthFunction = function () {
  8920. return this._depthCullingState.depthFunc;
  8921. };
  8922. Engine.prototype.setDepthFunction = function (depthFunc) {
  8923. this._depthCullingState.depthFunc = depthFunc;
  8924. };
  8925. Engine.prototype.setDepthFunctionToGreater = function () {
  8926. this._depthCullingState.depthFunc = this._gl.GREATER;
  8927. };
  8928. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8929. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8930. };
  8931. Engine.prototype.setDepthFunctionToLess = function () {
  8932. this._depthCullingState.depthFunc = this._gl.LESS;
  8933. };
  8934. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8935. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8936. };
  8937. Engine.prototype.getStencilBuffer = function () {
  8938. return this._stencilState.stencilTest;
  8939. };
  8940. Engine.prototype.setStencilBuffer = function (enable) {
  8941. this._stencilState.stencilTest = enable;
  8942. };
  8943. Engine.prototype.getStencilMask = function () {
  8944. return this._stencilState.stencilMask;
  8945. };
  8946. Engine.prototype.setStencilMask = function (mask) {
  8947. this._stencilState.stencilMask = mask;
  8948. };
  8949. Engine.prototype.getStencilFunction = function () {
  8950. return this._stencilState.stencilFunc;
  8951. };
  8952. Engine.prototype.getStencilFunctionReference = function () {
  8953. return this._stencilState.stencilFuncRef;
  8954. };
  8955. Engine.prototype.getStencilFunctionMask = function () {
  8956. return this._stencilState.stencilFuncMask;
  8957. };
  8958. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8959. this._stencilState.stencilFunc = stencilFunc;
  8960. };
  8961. Engine.prototype.setStencilFunctionReference = function (reference) {
  8962. this._stencilState.stencilFuncRef = reference;
  8963. };
  8964. Engine.prototype.setStencilFunctionMask = function (mask) {
  8965. this._stencilState.stencilFuncMask = mask;
  8966. };
  8967. Engine.prototype.getStencilOperationFail = function () {
  8968. return this._stencilState.stencilOpStencilFail;
  8969. };
  8970. Engine.prototype.getStencilOperationDepthFail = function () {
  8971. return this._stencilState.stencilOpDepthFail;
  8972. };
  8973. Engine.prototype.getStencilOperationPass = function () {
  8974. return this._stencilState.stencilOpStencilDepthPass;
  8975. };
  8976. Engine.prototype.setStencilOperationFail = function (operation) {
  8977. this._stencilState.stencilOpStencilFail = operation;
  8978. };
  8979. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8980. this._stencilState.stencilOpDepthFail = operation;
  8981. };
  8982. Engine.prototype.setStencilOperationPass = function (operation) {
  8983. this._stencilState.stencilOpStencilDepthPass = operation;
  8984. };
  8985. Engine.prototype.setDitheringState = function (value) {
  8986. if (value) {
  8987. this._gl.enable(this._gl.DITHER);
  8988. }
  8989. else {
  8990. this._gl.disable(this._gl.DITHER);
  8991. }
  8992. };
  8993. Engine.prototype.setRasterizerState = function (value) {
  8994. if (value) {
  8995. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  8996. }
  8997. else {
  8998. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  8999. }
  9000. };
  9001. /**
  9002. * stop executing a render loop function and remove it from the execution array
  9003. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  9004. */
  9005. Engine.prototype.stopRenderLoop = function (renderFunction) {
  9006. if (!renderFunction) {
  9007. this._activeRenderLoops = [];
  9008. return;
  9009. }
  9010. var index = this._activeRenderLoops.indexOf(renderFunction);
  9011. if (index >= 0) {
  9012. this._activeRenderLoops.splice(index, 1);
  9013. }
  9014. };
  9015. Engine.prototype._renderLoop = function () {
  9016. if (!this._contextWasLost) {
  9017. var shouldRender = true;
  9018. if (!this.renderEvenInBackground && this._windowIsBackground) {
  9019. shouldRender = false;
  9020. }
  9021. if (shouldRender) {
  9022. // Start new frame
  9023. this.beginFrame();
  9024. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  9025. var renderFunction = this._activeRenderLoops[index];
  9026. renderFunction();
  9027. }
  9028. // Present
  9029. this.endFrame();
  9030. }
  9031. }
  9032. if (this._activeRenderLoops.length > 0) {
  9033. // Register new frame
  9034. var requester = null;
  9035. if (this._vrDisplay && this._vrDisplay.isPresenting)
  9036. requester = this._vrDisplay;
  9037. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  9038. }
  9039. else {
  9040. this._renderingQueueLaunched = false;
  9041. }
  9042. };
  9043. /**
  9044. * Register and execute a render loop. The engine can have more than one render function.
  9045. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  9046. * @example
  9047. * engine.runRenderLoop(function () {
  9048. * scene.render()
  9049. * })
  9050. */
  9051. Engine.prototype.runRenderLoop = function (renderFunction) {
  9052. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  9053. return;
  9054. }
  9055. this._activeRenderLoops.push(renderFunction);
  9056. if (!this._renderingQueueLaunched) {
  9057. this._renderingQueueLaunched = true;
  9058. this._bindedRenderFunction = this._renderLoop.bind(this);
  9059. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  9060. }
  9061. };
  9062. /**
  9063. * Toggle full screen mode.
  9064. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  9065. * @param {any} options - an options object to be sent to the requestFullscreen function
  9066. */
  9067. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  9068. if (this.isFullscreen) {
  9069. BABYLON.Tools.ExitFullscreen();
  9070. }
  9071. else {
  9072. this._pointerLockRequested = requestPointerLock;
  9073. if (this._renderingCanvas) {
  9074. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  9075. }
  9076. }
  9077. };
  9078. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  9079. if (stencil === void 0) { stencil = false; }
  9080. this.applyStates();
  9081. var mode = 0;
  9082. if (backBuffer && color) {
  9083. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  9084. mode |= this._gl.COLOR_BUFFER_BIT;
  9085. }
  9086. if (depth) {
  9087. this._gl.clearDepth(1.0);
  9088. mode |= this._gl.DEPTH_BUFFER_BIT;
  9089. }
  9090. if (stencil) {
  9091. this._gl.clearStencil(0);
  9092. mode |= this._gl.STENCIL_BUFFER_BIT;
  9093. }
  9094. this._gl.clear(mode);
  9095. };
  9096. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9097. var gl = this._gl;
  9098. // Save state
  9099. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9100. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9101. // Change state
  9102. gl.enable(gl.SCISSOR_TEST);
  9103. gl.scissor(x, y, width, height);
  9104. // Clear
  9105. this.clear(clearColor, true, true, true);
  9106. // Restore state
  9107. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9108. if (curScissor === true) {
  9109. gl.enable(gl.SCISSOR_TEST);
  9110. }
  9111. else {
  9112. gl.disable(gl.SCISSOR_TEST);
  9113. }
  9114. };
  9115. /**
  9116. * Set the WebGL's viewport
  9117. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9118. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9119. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9120. */
  9121. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9122. var width = requiredWidth || this.getRenderWidth();
  9123. var height = requiredHeight || this.getRenderHeight();
  9124. var x = viewport.x || 0;
  9125. var y = viewport.y || 0;
  9126. this._cachedViewport = viewport;
  9127. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9128. };
  9129. /**
  9130. * Directly set the WebGL Viewport
  9131. * The x, y, width & height are directly passed to the WebGL call
  9132. * @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.
  9133. */
  9134. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9135. var currentViewport = this._cachedViewport;
  9136. this._cachedViewport = null;
  9137. this._gl.viewport(x, y, width, height);
  9138. return currentViewport;
  9139. };
  9140. Engine.prototype.beginFrame = function () {
  9141. this.onBeginFrameObservable.notifyObservers(this);
  9142. this._measureFps();
  9143. };
  9144. Engine.prototype.endFrame = function () {
  9145. //force a flush in case we are using a bad OS.
  9146. if (this._badOS) {
  9147. this.flushFramebuffer();
  9148. }
  9149. //submit frame to the vr device, if enabled
  9150. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9151. // TODO: We should only submit the frame if we read frameData successfully.
  9152. this._vrDisplay.submitFrame();
  9153. }
  9154. this.onEndFrameObservable.notifyObservers(this);
  9155. };
  9156. /**
  9157. * resize the view according to the canvas' size.
  9158. * @example
  9159. * window.addEventListener("resize", function () {
  9160. * engine.resize();
  9161. * });
  9162. */
  9163. Engine.prototype.resize = function () {
  9164. // We're not resizing the size of the canvas while in VR mode & presenting
  9165. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9166. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9167. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9168. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9169. }
  9170. };
  9171. /**
  9172. * force a specific size of the canvas
  9173. * @param {number} width - the new canvas' width
  9174. * @param {number} height - the new canvas' height
  9175. */
  9176. Engine.prototype.setSize = function (width, height) {
  9177. if (!this._renderingCanvas) {
  9178. return;
  9179. }
  9180. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9181. return;
  9182. }
  9183. this._renderingCanvas.width = width;
  9184. this._renderingCanvas.height = height;
  9185. for (var index = 0; index < this.scenes.length; index++) {
  9186. var scene = this.scenes[index];
  9187. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9188. var cam = scene.cameras[camIndex];
  9189. cam._currentRenderId = 0;
  9190. }
  9191. }
  9192. if (this.onResizeObservable.hasObservers) {
  9193. this.onResizeObservable.notifyObservers(this);
  9194. }
  9195. };
  9196. // WebVR functions
  9197. Engine.prototype.isVRDevicePresent = function () {
  9198. return !!this._vrDisplay;
  9199. };
  9200. Engine.prototype.getVRDevice = function () {
  9201. return this._vrDisplay;
  9202. };
  9203. Engine.prototype.initWebVR = function () {
  9204. var _this = this;
  9205. var notifyObservers = function () {
  9206. var eventArgs = {
  9207. vrDisplay: _this._vrDisplay,
  9208. vrSupported: _this._vrSupported
  9209. };
  9210. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9211. };
  9212. if (!this._onVrDisplayConnect) {
  9213. this._onVrDisplayConnect = function (event) {
  9214. _this._vrDisplay = event.display;
  9215. notifyObservers();
  9216. };
  9217. this._onVrDisplayDisconnect = function () {
  9218. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9219. _this._vrDisplay = undefined;
  9220. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9221. notifyObservers();
  9222. };
  9223. this._onVrDisplayPresentChange = function () {
  9224. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9225. };
  9226. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9227. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9228. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9229. }
  9230. this._getVRDisplays(notifyObservers);
  9231. return this.onVRDisplayChangedObservable;
  9232. };
  9233. Engine.prototype.enableVR = function () {
  9234. var _this = this;
  9235. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9236. var onResolved = function () {
  9237. _this.onVRRequestPresentComplete.notifyObservers(true);
  9238. _this._onVRFullScreenTriggered();
  9239. };
  9240. var onRejected = function () {
  9241. _this.onVRRequestPresentComplete.notifyObservers(false);
  9242. };
  9243. this.onVRRequestPresentStart.notifyObservers(this);
  9244. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9245. }
  9246. };
  9247. Engine.prototype.disableVR = function () {
  9248. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9249. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9250. }
  9251. };
  9252. Engine.prototype._getVRDisplays = function (callback) {
  9253. var _this = this;
  9254. var getWebVRDevices = function (devices) {
  9255. _this._vrSupported = true;
  9256. // note that devices may actually be an empty array. This is fine;
  9257. // we expect this._vrDisplay to be undefined in this case.
  9258. return _this._vrDisplay = devices[0];
  9259. };
  9260. if (navigator.getVRDisplays) {
  9261. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9262. // TODO: System CANNOT support WebVR, despite API presence.
  9263. _this._vrSupported = false;
  9264. callback();
  9265. });
  9266. }
  9267. else {
  9268. // TODO: Browser does not support WebVR
  9269. this._vrDisplay = undefined;
  9270. this._vrSupported = false;
  9271. callback();
  9272. }
  9273. };
  9274. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9275. if (this._currentRenderTarget) {
  9276. this.unBindFramebuffer(this._currentRenderTarget);
  9277. }
  9278. this._currentRenderTarget = texture;
  9279. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9280. var gl = this._gl;
  9281. if (texture.isCube) {
  9282. if (faceIndex === undefined) {
  9283. faceIndex = 0;
  9284. }
  9285. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9286. }
  9287. if (this._cachedViewport && !forceFullscreenViewport) {
  9288. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9289. }
  9290. else {
  9291. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9292. }
  9293. this.wipeCaches();
  9294. };
  9295. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9296. if (this._currentFramebuffer !== framebuffer) {
  9297. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9298. this._currentFramebuffer = framebuffer;
  9299. }
  9300. };
  9301. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9302. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9303. this._currentRenderTarget = null;
  9304. // If MSAA, we need to bitblt back to main texture
  9305. var gl = this._gl;
  9306. if (texture._MSAAFramebuffer) {
  9307. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9308. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9309. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9310. }
  9311. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9312. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9313. gl.generateMipmap(gl.TEXTURE_2D);
  9314. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9315. }
  9316. if (onBeforeUnbind) {
  9317. if (texture._MSAAFramebuffer) {
  9318. // Bind the correct framebuffer
  9319. this.bindUnboundFramebuffer(texture._framebuffer);
  9320. }
  9321. onBeforeUnbind();
  9322. }
  9323. this.bindUnboundFramebuffer(null);
  9324. };
  9325. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9326. if (texture.generateMipMaps) {
  9327. var gl = this._gl;
  9328. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9329. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9330. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9331. }
  9332. };
  9333. Engine.prototype.flushFramebuffer = function () {
  9334. this._gl.flush();
  9335. };
  9336. Engine.prototype.restoreDefaultFramebuffer = function () {
  9337. if (this._currentRenderTarget) {
  9338. this.unBindFramebuffer(this._currentRenderTarget);
  9339. }
  9340. else {
  9341. this.bindUnboundFramebuffer(null);
  9342. }
  9343. if (this._cachedViewport) {
  9344. this.setViewport(this._cachedViewport);
  9345. }
  9346. this.wipeCaches();
  9347. };
  9348. // UBOs
  9349. Engine.prototype.createUniformBuffer = function (elements) {
  9350. var ubo = this._gl.createBuffer();
  9351. if (!ubo) {
  9352. throw new Error("Unable to create uniform buffer");
  9353. }
  9354. this.bindUniformBuffer(ubo);
  9355. if (elements instanceof Float32Array) {
  9356. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9357. }
  9358. else {
  9359. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9360. }
  9361. this.bindUniformBuffer(null);
  9362. ubo.references = 1;
  9363. return ubo;
  9364. };
  9365. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9366. var ubo = this._gl.createBuffer();
  9367. if (!ubo) {
  9368. throw new Error("Unable to create dynamic uniform buffer");
  9369. }
  9370. this.bindUniformBuffer(ubo);
  9371. if (elements instanceof Float32Array) {
  9372. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9373. }
  9374. else {
  9375. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9376. }
  9377. this.bindUniformBuffer(null);
  9378. ubo.references = 1;
  9379. return ubo;
  9380. };
  9381. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9382. this.bindUniformBuffer(uniformBuffer);
  9383. if (offset === undefined) {
  9384. offset = 0;
  9385. }
  9386. if (count === undefined) {
  9387. if (elements instanceof Float32Array) {
  9388. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9389. }
  9390. else {
  9391. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9392. }
  9393. }
  9394. else {
  9395. if (elements instanceof Float32Array) {
  9396. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9397. }
  9398. else {
  9399. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9400. }
  9401. }
  9402. this.bindUniformBuffer(null);
  9403. };
  9404. // VBOs
  9405. Engine.prototype._resetVertexBufferBinding = function () {
  9406. this.bindArrayBuffer(null);
  9407. this._cachedVertexBuffers = null;
  9408. };
  9409. Engine.prototype.createVertexBuffer = function (vertices) {
  9410. var vbo = this._gl.createBuffer();
  9411. if (!vbo) {
  9412. throw new Error("Unable to create vertex buffer");
  9413. }
  9414. this.bindArrayBuffer(vbo);
  9415. if (vertices instanceof Float32Array) {
  9416. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9417. }
  9418. else {
  9419. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9420. }
  9421. this._resetVertexBufferBinding();
  9422. vbo.references = 1;
  9423. return vbo;
  9424. };
  9425. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9426. var vbo = this._gl.createBuffer();
  9427. if (!vbo) {
  9428. throw new Error("Unable to create dynamic vertex buffer");
  9429. }
  9430. this.bindArrayBuffer(vbo);
  9431. if (vertices instanceof Float32Array) {
  9432. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9433. }
  9434. else {
  9435. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9436. }
  9437. this._resetVertexBufferBinding();
  9438. vbo.references = 1;
  9439. return vbo;
  9440. };
  9441. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9442. if (offset === void 0) { offset = 0; }
  9443. // Force cache update
  9444. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9445. this.bindIndexBuffer(indexBuffer);
  9446. var arrayBuffer;
  9447. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9448. arrayBuffer = indices;
  9449. }
  9450. else {
  9451. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9452. }
  9453. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9454. this._resetIndexBufferBinding();
  9455. };
  9456. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9457. this.bindArrayBuffer(vertexBuffer);
  9458. if (offset === undefined) {
  9459. offset = 0;
  9460. }
  9461. if (count === undefined) {
  9462. if (vertices instanceof Float32Array) {
  9463. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9464. }
  9465. else {
  9466. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9467. }
  9468. }
  9469. else {
  9470. if (vertices instanceof Float32Array) {
  9471. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9472. }
  9473. else {
  9474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9475. }
  9476. }
  9477. this._resetVertexBufferBinding();
  9478. };
  9479. Engine.prototype._resetIndexBufferBinding = function () {
  9480. this.bindIndexBuffer(null);
  9481. this._cachedIndexBuffer = null;
  9482. };
  9483. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9484. var vbo = this._gl.createBuffer();
  9485. if (!vbo) {
  9486. throw new Error("Unable to create index buffer");
  9487. }
  9488. this.bindIndexBuffer(vbo);
  9489. // Check for 32 bits indices
  9490. var arrayBuffer;
  9491. var need32Bits = false;
  9492. if (indices instanceof Uint16Array) {
  9493. arrayBuffer = indices;
  9494. }
  9495. else {
  9496. //check 32 bit support
  9497. if (this._caps.uintIndices) {
  9498. if (indices instanceof Uint32Array) {
  9499. arrayBuffer = indices;
  9500. need32Bits = true;
  9501. }
  9502. else {
  9503. //number[] or Int32Array, check if 32 bit is necessary
  9504. for (var index = 0; index < indices.length; index++) {
  9505. if (indices[index] > 65535) {
  9506. need32Bits = true;
  9507. break;
  9508. }
  9509. }
  9510. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9511. }
  9512. }
  9513. else {
  9514. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9515. arrayBuffer = new Uint16Array(indices);
  9516. }
  9517. }
  9518. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9519. this._resetIndexBufferBinding();
  9520. vbo.references = 1;
  9521. vbo.is32Bits = need32Bits;
  9522. return vbo;
  9523. };
  9524. Engine.prototype.bindArrayBuffer = function (buffer) {
  9525. if (!this._vaoRecordInProgress) {
  9526. this._unbindVertexArrayObject();
  9527. }
  9528. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9529. };
  9530. Engine.prototype.bindUniformBuffer = function (buffer) {
  9531. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9532. };
  9533. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9534. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9535. };
  9536. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9537. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9538. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9539. };
  9540. ;
  9541. Engine.prototype.bindIndexBuffer = function (buffer) {
  9542. if (!this._vaoRecordInProgress) {
  9543. this._unbindVertexArrayObject();
  9544. }
  9545. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9546. };
  9547. Engine.prototype.bindBuffer = function (buffer, target) {
  9548. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9549. this._gl.bindBuffer(target, buffer);
  9550. this._currentBoundBuffer[target] = buffer;
  9551. }
  9552. };
  9553. Engine.prototype.updateArrayBuffer = function (data) {
  9554. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9555. };
  9556. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9557. var pointer = this._currentBufferPointers[indx];
  9558. var changed = false;
  9559. if (!pointer.active) {
  9560. changed = true;
  9561. pointer.active = true;
  9562. pointer.index = indx;
  9563. pointer.size = size;
  9564. pointer.type = type;
  9565. pointer.normalized = normalized;
  9566. pointer.stride = stride;
  9567. pointer.offset = offset;
  9568. pointer.buffer = buffer;
  9569. }
  9570. else {
  9571. if (pointer.buffer !== buffer) {
  9572. pointer.buffer = buffer;
  9573. changed = true;
  9574. }
  9575. if (pointer.size !== size) {
  9576. pointer.size = size;
  9577. changed = true;
  9578. }
  9579. if (pointer.type !== type) {
  9580. pointer.type = type;
  9581. changed = true;
  9582. }
  9583. if (pointer.normalized !== normalized) {
  9584. pointer.normalized = normalized;
  9585. changed = true;
  9586. }
  9587. if (pointer.stride !== stride) {
  9588. pointer.stride = stride;
  9589. changed = true;
  9590. }
  9591. if (pointer.offset !== offset) {
  9592. pointer.offset = offset;
  9593. changed = true;
  9594. }
  9595. }
  9596. if (changed || this._vaoRecordInProgress) {
  9597. this.bindArrayBuffer(buffer);
  9598. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9599. }
  9600. };
  9601. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9602. if (indexBuffer == null) {
  9603. return;
  9604. }
  9605. if (this._cachedIndexBuffer !== indexBuffer) {
  9606. this._cachedIndexBuffer = indexBuffer;
  9607. this.bindIndexBuffer(indexBuffer);
  9608. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9609. }
  9610. };
  9611. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9612. var attributes = effect.getAttributesNames();
  9613. if (!this._vaoRecordInProgress) {
  9614. this._unbindVertexArrayObject();
  9615. }
  9616. this.unbindAllAttributes();
  9617. for (var index = 0; index < attributes.length; index++) {
  9618. var order = effect.getAttributeLocation(index);
  9619. if (order >= 0) {
  9620. var vertexBuffer = vertexBuffers[attributes[index]];
  9621. if (!vertexBuffer) {
  9622. continue;
  9623. }
  9624. this._gl.enableVertexAttribArray(order);
  9625. if (!this._vaoRecordInProgress) {
  9626. this._vertexAttribArraysEnabled[order] = true;
  9627. }
  9628. var buffer = vertexBuffer.getBuffer();
  9629. if (buffer) {
  9630. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9631. if (vertexBuffer.getIsInstanced()) {
  9632. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9633. if (!this._vaoRecordInProgress) {
  9634. this._currentInstanceLocations.push(order);
  9635. this._currentInstanceBuffers.push(buffer);
  9636. }
  9637. }
  9638. }
  9639. }
  9640. }
  9641. };
  9642. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9643. var vao = this._gl.createVertexArray();
  9644. this._vaoRecordInProgress = true;
  9645. this._gl.bindVertexArray(vao);
  9646. this._mustWipeVertexAttributes = true;
  9647. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9648. this.bindIndexBuffer(indexBuffer);
  9649. this._vaoRecordInProgress = false;
  9650. this._gl.bindVertexArray(null);
  9651. return vao;
  9652. };
  9653. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9654. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9655. this._cachedVertexArrayObject = vertexArrayObject;
  9656. this._gl.bindVertexArray(vertexArrayObject);
  9657. this._cachedVertexBuffers = null;
  9658. this._cachedIndexBuffer = null;
  9659. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9660. this._mustWipeVertexAttributes = true;
  9661. }
  9662. };
  9663. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9664. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9665. this._cachedVertexBuffers = vertexBuffer;
  9666. this._cachedEffectForVertexBuffers = effect;
  9667. var attributesCount = effect.getAttributesCount();
  9668. this._unbindVertexArrayObject();
  9669. this.unbindAllAttributes();
  9670. var offset = 0;
  9671. for (var index = 0; index < attributesCount; index++) {
  9672. if (index < vertexDeclaration.length) {
  9673. var order = effect.getAttributeLocation(index);
  9674. if (order >= 0) {
  9675. this._gl.enableVertexAttribArray(order);
  9676. this._vertexAttribArraysEnabled[order] = true;
  9677. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9678. }
  9679. offset += vertexDeclaration[index] * 4;
  9680. }
  9681. }
  9682. }
  9683. this._bindIndexBufferWithCache(indexBuffer);
  9684. };
  9685. Engine.prototype._unbindVertexArrayObject = function () {
  9686. if (!this._cachedVertexArrayObject) {
  9687. return;
  9688. }
  9689. this._cachedVertexArrayObject = null;
  9690. this._gl.bindVertexArray(null);
  9691. };
  9692. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9693. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9694. this._cachedVertexBuffers = vertexBuffers;
  9695. this._cachedEffectForVertexBuffers = effect;
  9696. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9697. }
  9698. this._bindIndexBufferWithCache(indexBuffer);
  9699. };
  9700. Engine.prototype.unbindInstanceAttributes = function () {
  9701. var boundBuffer;
  9702. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9703. var instancesBuffer = this._currentInstanceBuffers[i];
  9704. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9705. boundBuffer = instancesBuffer;
  9706. this.bindArrayBuffer(instancesBuffer);
  9707. }
  9708. var offsetLocation = this._currentInstanceLocations[i];
  9709. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9710. }
  9711. this._currentInstanceBuffers.length = 0;
  9712. this._currentInstanceLocations.length = 0;
  9713. };
  9714. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9715. this._gl.deleteVertexArray(vao);
  9716. };
  9717. Engine.prototype._releaseBuffer = function (buffer) {
  9718. buffer.references--;
  9719. if (buffer.references === 0) {
  9720. this._gl.deleteBuffer(buffer);
  9721. return true;
  9722. }
  9723. return false;
  9724. };
  9725. Engine.prototype.createInstancesBuffer = function (capacity) {
  9726. var buffer = this._gl.createBuffer();
  9727. if (!buffer) {
  9728. throw new Error("Unable to create instance buffer");
  9729. }
  9730. buffer.capacity = capacity;
  9731. this.bindArrayBuffer(buffer);
  9732. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9733. return buffer;
  9734. };
  9735. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9736. this._gl.deleteBuffer(buffer);
  9737. };
  9738. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9739. this.bindArrayBuffer(instancesBuffer);
  9740. if (data) {
  9741. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9742. }
  9743. if (offsetLocations[0].index !== undefined) {
  9744. var stride = 0;
  9745. for (var i = 0; i < offsetLocations.length; i++) {
  9746. var ai = offsetLocations[i];
  9747. stride += ai.attributeSize * 4;
  9748. }
  9749. for (var i = 0; i < offsetLocations.length; i++) {
  9750. var ai = offsetLocations[i];
  9751. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9752. this._gl.enableVertexAttribArray(ai.index);
  9753. this._vertexAttribArraysEnabled[ai.index] = true;
  9754. }
  9755. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9756. this._gl.vertexAttribDivisor(ai.index, 1);
  9757. this._currentInstanceLocations.push(ai.index);
  9758. this._currentInstanceBuffers.push(instancesBuffer);
  9759. }
  9760. }
  9761. else {
  9762. for (var index = 0; index < 4; index++) {
  9763. var offsetLocation = offsetLocations[index];
  9764. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9765. this._gl.enableVertexAttribArray(offsetLocation);
  9766. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9767. }
  9768. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9769. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9770. this._currentInstanceLocations.push(offsetLocation);
  9771. this._currentInstanceBuffers.push(instancesBuffer);
  9772. }
  9773. }
  9774. };
  9775. Engine.prototype.applyStates = function () {
  9776. this._depthCullingState.apply(this._gl);
  9777. this._stencilState.apply(this._gl);
  9778. this._alphaState.apply(this._gl);
  9779. };
  9780. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9781. // Apply states
  9782. this.applyStates();
  9783. this._drawCalls.addCount(1, false);
  9784. // Render
  9785. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9786. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9787. if (instancesCount) {
  9788. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9789. return;
  9790. }
  9791. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9792. };
  9793. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9794. // Apply states
  9795. this.applyStates();
  9796. this._drawCalls.addCount(1, false);
  9797. if (instancesCount) {
  9798. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9799. return;
  9800. }
  9801. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9802. };
  9803. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9804. // Apply states
  9805. this.applyStates();
  9806. this._drawCalls.addCount(1, false);
  9807. if (instancesCount) {
  9808. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9809. return;
  9810. }
  9811. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9812. };
  9813. // Shaders
  9814. Engine.prototype._releaseEffect = function (effect) {
  9815. if (this._compiledEffects[effect._key]) {
  9816. delete this._compiledEffects[effect._key];
  9817. this._deleteProgram(effect.getProgram());
  9818. }
  9819. };
  9820. Engine.prototype._deleteProgram = function (program) {
  9821. if (program) {
  9822. program.__SPECTOR_rebuildProgram = null;
  9823. if (program.transformFeedback) {
  9824. this.deleteTransformFeedback(program.transformFeedback);
  9825. program.transformFeedback = null;
  9826. }
  9827. this._gl.deleteProgram(program);
  9828. }
  9829. };
  9830. /**
  9831. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9832. * @param samplers An array of string used to represent textures
  9833. */
  9834. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9835. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9836. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9837. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9838. if (this._compiledEffects[name]) {
  9839. var compiledEffect = this._compiledEffects[name];
  9840. if (onCompiled && compiledEffect.isReady()) {
  9841. onCompiled(compiledEffect);
  9842. }
  9843. return compiledEffect;
  9844. }
  9845. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9846. effect._key = name;
  9847. this._compiledEffects[name] = effect;
  9848. return effect;
  9849. };
  9850. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9851. if (uniformsNames === void 0) { uniformsNames = []; }
  9852. if (samplers === void 0) { samplers = []; }
  9853. if (defines === void 0) { defines = ""; }
  9854. return this.createEffect({
  9855. vertex: "particles",
  9856. fragmentElement: fragmentName
  9857. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9858. };
  9859. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  9860. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9861. context = context || this._gl;
  9862. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9863. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9864. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9865. };
  9866. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  9867. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9868. context = context || this._gl;
  9869. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9870. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9871. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9872. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9873. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9874. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9875. return program;
  9876. };
  9877. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  9878. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9879. var shaderProgram = context.createProgram();
  9880. if (!shaderProgram) {
  9881. throw new Error("Unable to create program");
  9882. }
  9883. context.attachShader(shaderProgram, vertexShader);
  9884. context.attachShader(shaderProgram, fragmentShader);
  9885. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9886. var transformFeedback = this.createTransformFeedback();
  9887. this.bindTransformFeedback(transformFeedback);
  9888. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  9889. shaderProgram.transformFeedback = transformFeedback;
  9890. }
  9891. context.linkProgram(shaderProgram);
  9892. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9893. this.bindTransformFeedback(null);
  9894. }
  9895. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9896. if (!linked) {
  9897. context.validateProgram(shaderProgram);
  9898. var error = context.getProgramInfoLog(shaderProgram);
  9899. if (error) {
  9900. throw new Error(error);
  9901. }
  9902. }
  9903. context.deleteShader(vertexShader);
  9904. context.deleteShader(fragmentShader);
  9905. return shaderProgram;
  9906. };
  9907. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9908. var results = new Array();
  9909. for (var index = 0; index < uniformsNames.length; index++) {
  9910. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9911. }
  9912. return results;
  9913. };
  9914. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9915. var results = [];
  9916. for (var index = 0; index < attributesNames.length; index++) {
  9917. try {
  9918. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9919. }
  9920. catch (e) {
  9921. results.push(-1);
  9922. }
  9923. }
  9924. return results;
  9925. };
  9926. Engine.prototype.enableEffect = function (effect) {
  9927. if (!effect) {
  9928. return;
  9929. }
  9930. // Use program
  9931. this.setProgram(effect.getProgram());
  9932. this._currentEffect = effect;
  9933. if (effect.onBind) {
  9934. effect.onBind(effect);
  9935. }
  9936. effect.onBindObservable.notifyObservers(effect);
  9937. };
  9938. Engine.prototype.setIntArray = function (uniform, array) {
  9939. if (!uniform)
  9940. return;
  9941. this._gl.uniform1iv(uniform, array);
  9942. };
  9943. Engine.prototype.setIntArray2 = function (uniform, array) {
  9944. if (!uniform || array.length % 2 !== 0)
  9945. return;
  9946. this._gl.uniform2iv(uniform, array);
  9947. };
  9948. Engine.prototype.setIntArray3 = function (uniform, array) {
  9949. if (!uniform || array.length % 3 !== 0)
  9950. return;
  9951. this._gl.uniform3iv(uniform, array);
  9952. };
  9953. Engine.prototype.setIntArray4 = function (uniform, array) {
  9954. if (!uniform || array.length % 4 !== 0)
  9955. return;
  9956. this._gl.uniform4iv(uniform, array);
  9957. };
  9958. Engine.prototype.setFloatArray = function (uniform, array) {
  9959. if (!uniform)
  9960. return;
  9961. this._gl.uniform1fv(uniform, array);
  9962. };
  9963. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9964. if (!uniform || array.length % 2 !== 0)
  9965. return;
  9966. this._gl.uniform2fv(uniform, array);
  9967. };
  9968. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9969. if (!uniform || array.length % 3 !== 0)
  9970. return;
  9971. this._gl.uniform3fv(uniform, array);
  9972. };
  9973. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9974. if (!uniform || array.length % 4 !== 0)
  9975. return;
  9976. this._gl.uniform4fv(uniform, array);
  9977. };
  9978. Engine.prototype.setArray = function (uniform, array) {
  9979. if (!uniform)
  9980. return;
  9981. this._gl.uniform1fv(uniform, array);
  9982. };
  9983. Engine.prototype.setArray2 = function (uniform, array) {
  9984. if (!uniform || array.length % 2 !== 0)
  9985. return;
  9986. this._gl.uniform2fv(uniform, array);
  9987. };
  9988. Engine.prototype.setArray3 = function (uniform, array) {
  9989. if (!uniform || array.length % 3 !== 0)
  9990. return;
  9991. this._gl.uniform3fv(uniform, array);
  9992. };
  9993. Engine.prototype.setArray4 = function (uniform, array) {
  9994. if (!uniform || array.length % 4 !== 0)
  9995. return;
  9996. this._gl.uniform4fv(uniform, array);
  9997. };
  9998. Engine.prototype.setMatrices = function (uniform, matrices) {
  9999. if (!uniform)
  10000. return;
  10001. this._gl.uniformMatrix4fv(uniform, false, matrices);
  10002. };
  10003. Engine.prototype.setMatrix = function (uniform, matrix) {
  10004. if (!uniform)
  10005. return;
  10006. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  10007. };
  10008. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  10009. if (!uniform)
  10010. return;
  10011. this._gl.uniformMatrix3fv(uniform, false, matrix);
  10012. };
  10013. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  10014. if (!uniform)
  10015. return;
  10016. this._gl.uniformMatrix2fv(uniform, false, matrix);
  10017. };
  10018. Engine.prototype.setFloat = function (uniform, value) {
  10019. if (!uniform)
  10020. return;
  10021. this._gl.uniform1f(uniform, value);
  10022. };
  10023. Engine.prototype.setFloat2 = function (uniform, x, y) {
  10024. if (!uniform)
  10025. return;
  10026. this._gl.uniform2f(uniform, x, y);
  10027. };
  10028. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  10029. if (!uniform)
  10030. return;
  10031. this._gl.uniform3f(uniform, x, y, z);
  10032. };
  10033. Engine.prototype.setBool = function (uniform, bool) {
  10034. if (!uniform)
  10035. return;
  10036. this._gl.uniform1i(uniform, bool);
  10037. };
  10038. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  10039. if (!uniform)
  10040. return;
  10041. this._gl.uniform4f(uniform, x, y, z, w);
  10042. };
  10043. Engine.prototype.setColor3 = function (uniform, color3) {
  10044. if (!uniform)
  10045. return;
  10046. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  10047. };
  10048. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  10049. if (!uniform)
  10050. return;
  10051. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  10052. };
  10053. // States
  10054. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  10055. if (zOffset === void 0) { zOffset = 0; }
  10056. if (reverseSide === void 0) { reverseSide = false; }
  10057. // Culling
  10058. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  10059. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  10060. var cullFace = this.cullBackFaces ? showSide : hideSide;
  10061. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  10062. if (culling) {
  10063. this._depthCullingState.cullFace = cullFace;
  10064. this._depthCullingState.cull = true;
  10065. }
  10066. else {
  10067. this._depthCullingState.cull = false;
  10068. }
  10069. }
  10070. // Z offset
  10071. this.setZOffset(zOffset);
  10072. };
  10073. Engine.prototype.setZOffset = function (value) {
  10074. this._depthCullingState.zOffset = value;
  10075. };
  10076. Engine.prototype.getZOffset = function () {
  10077. return this._depthCullingState.zOffset;
  10078. };
  10079. Engine.prototype.setDepthBuffer = function (enable) {
  10080. this._depthCullingState.depthTest = enable;
  10081. };
  10082. Engine.prototype.getDepthWrite = function () {
  10083. return this._depthCullingState.depthMask;
  10084. };
  10085. Engine.prototype.setDepthWrite = function (enable) {
  10086. this._depthCullingState.depthMask = enable;
  10087. };
  10088. Engine.prototype.setColorWrite = function (enable) {
  10089. this._gl.colorMask(enable, enable, enable, enable);
  10090. this._colorWrite = enable;
  10091. };
  10092. Engine.prototype.getColorWrite = function () {
  10093. return this._colorWrite;
  10094. };
  10095. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10096. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10097. };
  10098. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10099. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10100. if (this._alphaMode === mode) {
  10101. return;
  10102. }
  10103. switch (mode) {
  10104. case Engine.ALPHA_DISABLE:
  10105. this._alphaState.alphaBlend = false;
  10106. break;
  10107. case Engine.ALPHA_PREMULTIPLIED:
  10108. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10109. this._alphaState.alphaBlend = true;
  10110. break;
  10111. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10112. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10113. this._alphaState.alphaBlend = true;
  10114. break;
  10115. case Engine.ALPHA_COMBINE:
  10116. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10117. this._alphaState.alphaBlend = true;
  10118. break;
  10119. case Engine.ALPHA_ONEONE:
  10120. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10121. this._alphaState.alphaBlend = true;
  10122. break;
  10123. case Engine.ALPHA_ADD:
  10124. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10125. this._alphaState.alphaBlend = true;
  10126. break;
  10127. case Engine.ALPHA_SUBTRACT:
  10128. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10129. this._alphaState.alphaBlend = true;
  10130. break;
  10131. case Engine.ALPHA_MULTIPLY:
  10132. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10133. this._alphaState.alphaBlend = true;
  10134. break;
  10135. case Engine.ALPHA_MAXIMIZED:
  10136. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10137. this._alphaState.alphaBlend = true;
  10138. break;
  10139. case Engine.ALPHA_INTERPOLATE:
  10140. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10141. this._alphaState.alphaBlend = true;
  10142. break;
  10143. case Engine.ALPHA_SCREENMODE:
  10144. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10145. this._alphaState.alphaBlend = true;
  10146. break;
  10147. }
  10148. if (!noDepthWriteChange) {
  10149. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10150. }
  10151. this._alphaMode = mode;
  10152. };
  10153. Engine.prototype.getAlphaMode = function () {
  10154. return this._alphaMode;
  10155. };
  10156. Engine.prototype.setAlphaTesting = function (enable) {
  10157. this._alphaTest = enable;
  10158. };
  10159. Engine.prototype.getAlphaTesting = function () {
  10160. return !!this._alphaTest;
  10161. };
  10162. // Textures
  10163. Engine.prototype.wipeCaches = function (bruteForce) {
  10164. if (this.preventCacheWipeBetweenFrames) {
  10165. return;
  10166. }
  10167. this.resetTextureCache();
  10168. this._currentEffect = null;
  10169. // 6/8/2017: deltakosh: Should not be required anymore.
  10170. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10171. if (bruteForce) {
  10172. this._currentProgram = null;
  10173. this._stencilState.reset();
  10174. this._depthCullingState.reset();
  10175. this.setDepthFunctionToLessOrEqual();
  10176. this._alphaState.reset();
  10177. }
  10178. this._cachedVertexBuffers = null;
  10179. this._cachedIndexBuffer = null;
  10180. this._cachedEffectForVertexBuffers = null;
  10181. this._unbindVertexArrayObject();
  10182. this.bindIndexBuffer(null);
  10183. this.bindArrayBuffer(null);
  10184. };
  10185. /**
  10186. * Set the compressed texture format to use, based on the formats you have, and the formats
  10187. * supported by the hardware / browser.
  10188. *
  10189. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10190. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10191. * to API arguments needed to compressed textures. This puts the burden on the container
  10192. * generator to house the arcane code for determining these for current & future formats.
  10193. *
  10194. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10195. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10196. *
  10197. * Note: The result of this call is not taken into account when a texture is base64.
  10198. *
  10199. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10200. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10201. *
  10202. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10203. * @returns The extension selected.
  10204. */
  10205. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10206. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10207. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10208. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10209. return this._textureFormatInUse = this._texturesSupported[i];
  10210. }
  10211. }
  10212. }
  10213. // actively set format to nothing, to allow this to be called more than once
  10214. // and possibly fail the 2nd time
  10215. this._textureFormatInUse = null;
  10216. return null;
  10217. };
  10218. Engine.prototype._createTexture = function () {
  10219. var texture = this._gl.createTexture();
  10220. if (!texture) {
  10221. throw new Error("Unable to create texture");
  10222. }
  10223. return texture;
  10224. };
  10225. /**
  10226. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10227. * @param {string} urlArg- This contains one of the following:
  10228. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10229. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10230. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10231. *
  10232. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10233. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10234. * @param {Scene} scene- Needed for loading to the correct scene.
  10235. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10236. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10237. * @param {callback} onError- Optional callback to be called upon failure.
  10238. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10239. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10240. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10241. *
  10242. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10243. */
  10244. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10245. var _this = this;
  10246. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10247. if (onLoad === void 0) { onLoad = null; }
  10248. if (onError === void 0) { onError = null; }
  10249. if (buffer === void 0) { buffer = null; }
  10250. if (fallBack === void 0) { fallBack = null; }
  10251. if (format === void 0) { format = null; }
  10252. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10253. var fromData = url.substr(0, 5) === "data:";
  10254. var fromBlob = url.substr(0, 5) === "blob:";
  10255. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10256. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10257. // establish the file extension, if possible
  10258. var lastDot = url.lastIndexOf('.');
  10259. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10260. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10261. var isTGA = (extension === ".tga");
  10262. // determine if a ktx file should be substituted
  10263. var isKTX = false;
  10264. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10265. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10266. isKTX = true;
  10267. }
  10268. if (scene) {
  10269. scene._addPendingData(texture);
  10270. }
  10271. texture.url = url;
  10272. texture.generateMipMaps = !noMipmap;
  10273. texture.samplingMode = samplingMode;
  10274. texture.invertY = invertY;
  10275. if (!this._doNotHandleContextLost) {
  10276. // Keep a link to the buffer only if we plan to handle context lost
  10277. texture._buffer = buffer;
  10278. }
  10279. var onLoadObserver = null;
  10280. if (onLoad && !fallBack) {
  10281. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  10282. }
  10283. if (!fallBack)
  10284. this._internalTexturesCache.push(texture);
  10285. var onerror = function () {
  10286. if (scene) {
  10287. scene._removePendingData(texture);
  10288. }
  10289. if (onLoadObserver) {
  10290. texture.onLoadedObservable.remove(onLoadObserver);
  10291. }
  10292. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10293. if (isKTX) {
  10294. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10295. }
  10296. else if (BABYLON.Tools.UseFallbackTexture) {
  10297. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10298. }
  10299. if (onError) {
  10300. onError();
  10301. }
  10302. };
  10303. var callback = null;
  10304. // processing for non-image formats
  10305. if (isKTX || isTGA || isDDS) {
  10306. if (isKTX) {
  10307. callback = function (data) {
  10308. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10309. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10310. ktx.uploadLevels(_this._gl, !noMipmap);
  10311. return false;
  10312. }, samplingMode);
  10313. };
  10314. }
  10315. else if (isTGA) {
  10316. callback = function (arrayBuffer) {
  10317. var data = new Uint8Array(arrayBuffer);
  10318. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10319. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10320. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10321. return false;
  10322. }, samplingMode);
  10323. };
  10324. }
  10325. else if (isDDS) {
  10326. callback = function (data) {
  10327. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10328. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10329. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10330. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10331. return false;
  10332. }, samplingMode);
  10333. };
  10334. }
  10335. if (!buffer) {
  10336. BABYLON.Tools.LoadFile(url, function (data) {
  10337. if (callback) {
  10338. callback(data);
  10339. }
  10340. }, undefined, scene ? scene.database : undefined, true, onerror);
  10341. }
  10342. else {
  10343. if (callback) {
  10344. callback(buffer);
  10345. }
  10346. }
  10347. // image format processing
  10348. }
  10349. else {
  10350. var onload = function (img) {
  10351. if (fromBlob && !_this._doNotHandleContextLost) {
  10352. // We need to store the image if we need to rebuild the texture
  10353. // in case of a webgl context lost
  10354. texture._buffer = img;
  10355. }
  10356. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10357. var gl = _this._gl;
  10358. var isPot = (img.width === potWidth && img.height === potHeight);
  10359. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10360. if (isPot) {
  10361. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10362. return false;
  10363. }
  10364. // Using shaders to rescale because canvas.drawImage is lossy
  10365. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10366. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10367. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10368. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10369. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10370. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10371. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10372. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10373. _this._releaseTexture(source);
  10374. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10375. continuationCallback();
  10376. });
  10377. return true;
  10378. }, samplingMode);
  10379. };
  10380. if (!fromData || isBase64)
  10381. if (buffer instanceof HTMLImageElement) {
  10382. onload(buffer);
  10383. }
  10384. else {
  10385. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10386. }
  10387. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10388. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10389. else
  10390. onload(buffer);
  10391. }
  10392. return texture;
  10393. };
  10394. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10395. var _this = this;
  10396. var rtt = this.createRenderTargetTexture({
  10397. width: destination.width,
  10398. height: destination.height,
  10399. }, {
  10400. generateMipMaps: false,
  10401. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10402. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10403. generateDepthBuffer: false,
  10404. generateStencilBuffer: false
  10405. });
  10406. if (!this._rescalePostProcess) {
  10407. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10408. }
  10409. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10410. _this._rescalePostProcess.onApply = function (effect) {
  10411. effect._bindTexture("textureSampler", source);
  10412. };
  10413. var hostingScene = scene;
  10414. if (!hostingScene) {
  10415. hostingScene = _this.scenes[_this.scenes.length - 1];
  10416. }
  10417. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10418. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10419. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10420. _this.unBindFramebuffer(rtt);
  10421. _this._releaseTexture(rtt);
  10422. if (onComplete) {
  10423. onComplete();
  10424. }
  10425. });
  10426. };
  10427. Engine.prototype._getInternalFormat = function (format) {
  10428. var internalFormat = this._gl.RGBA;
  10429. switch (format) {
  10430. case Engine.TEXTUREFORMAT_ALPHA:
  10431. internalFormat = this._gl.ALPHA;
  10432. break;
  10433. case Engine.TEXTUREFORMAT_LUMINANCE:
  10434. internalFormat = this._gl.LUMINANCE;
  10435. break;
  10436. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10437. internalFormat = this._gl.LUMINANCE_ALPHA;
  10438. break;
  10439. case Engine.TEXTUREFORMAT_RGB:
  10440. internalFormat = this._gl.RGB;
  10441. break;
  10442. case Engine.TEXTUREFORMAT_RGBA:
  10443. internalFormat = this._gl.RGBA;
  10444. break;
  10445. }
  10446. return internalFormat;
  10447. };
  10448. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10449. if (compression === void 0) { compression = null; }
  10450. if (!texture) {
  10451. return;
  10452. }
  10453. var internalFormat = this._getInternalFormat(format);
  10454. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10455. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10456. if (!this._doNotHandleContextLost) {
  10457. texture._bufferView = data;
  10458. texture.format = format;
  10459. texture.invertY = invertY;
  10460. texture._compression = compression;
  10461. }
  10462. if (texture.width % 4 !== 0) {
  10463. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10464. }
  10465. if (compression && data) {
  10466. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10467. }
  10468. else {
  10469. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10470. }
  10471. if (texture.generateMipMaps) {
  10472. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10473. }
  10474. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10475. this.resetTextureCache();
  10476. texture.isReady = true;
  10477. };
  10478. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10479. if (compression === void 0) { compression = null; }
  10480. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10481. texture.baseWidth = width;
  10482. texture.baseHeight = height;
  10483. texture.width = width;
  10484. texture.height = height;
  10485. texture.format = format;
  10486. texture.generateMipMaps = generateMipMaps;
  10487. texture.samplingMode = samplingMode;
  10488. texture.invertY = invertY;
  10489. texture._compression = compression;
  10490. if (!this._doNotHandleContextLost) {
  10491. texture._bufferView = data;
  10492. }
  10493. this.updateRawTexture(texture, data, format, invertY, compression);
  10494. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10495. // Filters
  10496. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10497. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10498. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10499. if (generateMipMaps) {
  10500. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10501. }
  10502. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10503. this._internalTexturesCache.push(texture);
  10504. return texture;
  10505. };
  10506. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10507. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10508. texture.baseWidth = width;
  10509. texture.baseHeight = height;
  10510. if (generateMipMaps) {
  10511. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10512. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10513. }
  10514. this.resetTextureCache();
  10515. texture.width = width;
  10516. texture.height = height;
  10517. texture.isReady = false;
  10518. texture.generateMipMaps = generateMipMaps;
  10519. texture.samplingMode = samplingMode;
  10520. this.updateTextureSamplingMode(samplingMode, texture);
  10521. this._internalTexturesCache.push(texture);
  10522. return texture;
  10523. };
  10524. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10525. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10526. if (texture.isCube) {
  10527. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10528. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10529. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10530. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10531. }
  10532. else if (texture.is3D) {
  10533. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10534. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10535. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10536. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10537. }
  10538. else {
  10539. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10540. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10541. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10542. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10543. }
  10544. texture.samplingMode = samplingMode;
  10545. };
  10546. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10547. if (premulAlpha === void 0) { premulAlpha = false; }
  10548. if (!texture) {
  10549. return;
  10550. }
  10551. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10552. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10553. if (premulAlpha) {
  10554. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10555. }
  10556. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10557. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10558. if (texture.generateMipMaps) {
  10559. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10560. }
  10561. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10562. if (premulAlpha) {
  10563. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10564. }
  10565. this.resetTextureCache();
  10566. texture.isReady = true;
  10567. };
  10568. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10569. if (!texture || texture._isDisabled) {
  10570. return;
  10571. }
  10572. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10573. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10574. try {
  10575. // Testing video texture support
  10576. if (this._videoTextureSupported === undefined) {
  10577. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10578. if (this._gl.getError() !== 0) {
  10579. this._videoTextureSupported = false;
  10580. }
  10581. else {
  10582. this._videoTextureSupported = true;
  10583. }
  10584. }
  10585. // Copy video through the current working canvas if video texture is not supported
  10586. if (!this._videoTextureSupported) {
  10587. if (!texture._workingCanvas) {
  10588. texture._workingCanvas = document.createElement("canvas");
  10589. var context = texture._workingCanvas.getContext("2d");
  10590. if (!context) {
  10591. throw new Error("Unable to get 2d context");
  10592. }
  10593. texture._workingContext = context;
  10594. texture._workingCanvas.width = texture.width;
  10595. texture._workingCanvas.height = texture.height;
  10596. }
  10597. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10598. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10599. }
  10600. else {
  10601. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10602. }
  10603. if (texture.generateMipMaps) {
  10604. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10605. }
  10606. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10607. this.resetTextureCache();
  10608. texture.isReady = true;
  10609. }
  10610. catch (ex) {
  10611. // Something unexpected
  10612. // Let's disable the texture
  10613. texture._isDisabled = true;
  10614. }
  10615. };
  10616. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10617. var fullOptions = new RenderTargetCreationOptions();
  10618. if (options !== undefined && typeof options === "object") {
  10619. fullOptions.generateMipMaps = options.generateMipMaps;
  10620. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10621. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10622. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10623. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10624. }
  10625. else {
  10626. fullOptions.generateMipMaps = options;
  10627. fullOptions.generateDepthBuffer = true;
  10628. fullOptions.generateStencilBuffer = false;
  10629. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10630. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10631. }
  10632. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10633. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10634. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10635. }
  10636. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10637. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10638. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10639. }
  10640. var gl = this._gl;
  10641. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10642. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10643. var width = size.width || size;
  10644. var height = size.height || size;
  10645. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10646. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10647. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10648. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10649. }
  10650. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10651. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10652. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10653. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10654. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10655. // Create the framebuffer
  10656. var framebuffer = gl.createFramebuffer();
  10657. this.bindUnboundFramebuffer(framebuffer);
  10658. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10659. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10660. if (fullOptions.generateMipMaps) {
  10661. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10662. }
  10663. // Unbind
  10664. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10665. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10666. this.bindUnboundFramebuffer(null);
  10667. texture._framebuffer = framebuffer;
  10668. texture.baseWidth = width;
  10669. texture.baseHeight = height;
  10670. texture.width = width;
  10671. texture.height = height;
  10672. texture.isReady = true;
  10673. texture.samples = 1;
  10674. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10675. texture.samplingMode = fullOptions.samplingMode;
  10676. texture.type = fullOptions.type;
  10677. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10678. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10679. this.resetTextureCache();
  10680. this._internalTexturesCache.push(texture);
  10681. return texture;
  10682. };
  10683. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10684. var generateMipMaps = false;
  10685. var generateDepthBuffer = true;
  10686. var generateStencilBuffer = false;
  10687. var generateDepthTexture = false;
  10688. var textureCount = 1;
  10689. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10690. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10691. var types = [], samplingModes = [];
  10692. if (options !== undefined) {
  10693. generateMipMaps = options.generateMipMaps;
  10694. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10695. generateStencilBuffer = options.generateStencilBuffer;
  10696. generateDepthTexture = options.generateDepthTexture;
  10697. textureCount = options.textureCount || 1;
  10698. if (options.types) {
  10699. types = options.types;
  10700. }
  10701. if (options.samplingModes) {
  10702. samplingModes = options.samplingModes;
  10703. }
  10704. }
  10705. var gl = this._gl;
  10706. // Create the framebuffer
  10707. var framebuffer = gl.createFramebuffer();
  10708. this.bindUnboundFramebuffer(framebuffer);
  10709. var width = size.width || size;
  10710. var height = size.height || size;
  10711. var textures = [];
  10712. var attachments = [];
  10713. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10714. for (var i = 0; i < textureCount; i++) {
  10715. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10716. var type = types[i] || defaultType;
  10717. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10718. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10719. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10720. }
  10721. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10722. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10723. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10724. }
  10725. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10726. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10727. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10728. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10729. }
  10730. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10731. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10732. textures.push(texture);
  10733. attachments.push(attachment);
  10734. gl.activeTexture(gl["TEXTURE" + i]);
  10735. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10736. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10737. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10738. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10739. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10740. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10741. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10742. if (generateMipMaps) {
  10743. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10744. }
  10745. // Unbind
  10746. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10747. texture._framebuffer = framebuffer;
  10748. texture._depthStencilBuffer = depthStencilBuffer;
  10749. texture.baseWidth = width;
  10750. texture.baseHeight = height;
  10751. texture.width = width;
  10752. texture.height = height;
  10753. texture.isReady = true;
  10754. texture.samples = 1;
  10755. texture.generateMipMaps = generateMipMaps;
  10756. texture.samplingMode = samplingMode;
  10757. texture.type = type;
  10758. texture._generateDepthBuffer = generateDepthBuffer;
  10759. texture._generateStencilBuffer = generateStencilBuffer;
  10760. this._internalTexturesCache.push(texture);
  10761. }
  10762. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10763. // Depth texture
  10764. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10765. gl.activeTexture(gl.TEXTURE0);
  10766. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10767. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10768. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10769. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10770. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10771. 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);
  10772. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10773. depthTexture._framebuffer = framebuffer;
  10774. depthTexture.baseWidth = width;
  10775. depthTexture.baseHeight = height;
  10776. depthTexture.width = width;
  10777. depthTexture.height = height;
  10778. depthTexture.isReady = true;
  10779. depthTexture.samples = 1;
  10780. depthTexture.generateMipMaps = generateMipMaps;
  10781. depthTexture.samplingMode = gl.NEAREST;
  10782. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10783. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10784. textures.push(depthTexture);
  10785. this._internalTexturesCache.push(depthTexture);
  10786. }
  10787. gl.drawBuffers(attachments);
  10788. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10789. this.bindUnboundFramebuffer(null);
  10790. this.resetTextureCache();
  10791. return textures;
  10792. };
  10793. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10794. if (samples === void 0) { samples = 1; }
  10795. var depthStencilBuffer = null;
  10796. var gl = this._gl;
  10797. // Create the depth/stencil buffer
  10798. if (generateStencilBuffer) {
  10799. depthStencilBuffer = gl.createRenderbuffer();
  10800. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10801. if (samples > 1) {
  10802. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10803. }
  10804. else {
  10805. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10806. }
  10807. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10808. }
  10809. else if (generateDepthBuffer) {
  10810. depthStencilBuffer = gl.createRenderbuffer();
  10811. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10812. if (samples > 1) {
  10813. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10814. }
  10815. else {
  10816. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10817. }
  10818. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10819. }
  10820. return depthStencilBuffer;
  10821. };
  10822. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10823. if (this.webGLVersion < 2 || !texture) {
  10824. return 1;
  10825. }
  10826. if (texture.samples === samples) {
  10827. return samples;
  10828. }
  10829. var gl = this._gl;
  10830. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10831. // Dispose previous render buffers
  10832. if (texture._depthStencilBuffer) {
  10833. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10834. }
  10835. if (texture._MSAAFramebuffer) {
  10836. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10837. }
  10838. if (texture._MSAARenderBuffer) {
  10839. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10840. }
  10841. if (samples > 1) {
  10842. var framebuffer = gl.createFramebuffer();
  10843. if (!framebuffer) {
  10844. throw new Error("Unable to create multi sampled framebuffer");
  10845. }
  10846. texture._MSAAFramebuffer = framebuffer;
  10847. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10848. var colorRenderbuffer = gl.createRenderbuffer();
  10849. if (!colorRenderbuffer) {
  10850. throw new Error("Unable to create multi sampled framebuffer");
  10851. }
  10852. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10853. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10854. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10855. texture._MSAARenderBuffer = colorRenderbuffer;
  10856. }
  10857. else {
  10858. this.bindUnboundFramebuffer(texture._framebuffer);
  10859. }
  10860. texture.samples = samples;
  10861. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10862. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10863. this.bindUnboundFramebuffer(null);
  10864. return samples;
  10865. };
  10866. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10867. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10868. };
  10869. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10870. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10871. };
  10872. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10873. var gl = this._gl;
  10874. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10875. var generateMipMaps = true;
  10876. var generateDepthBuffer = true;
  10877. var generateStencilBuffer = false;
  10878. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10879. if (options !== undefined) {
  10880. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10881. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10882. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10883. if (options.samplingMode !== undefined) {
  10884. samplingMode = options.samplingMode;
  10885. }
  10886. }
  10887. texture.isCube = true;
  10888. texture.generateMipMaps = generateMipMaps;
  10889. texture.samples = 1;
  10890. texture.samplingMode = samplingMode;
  10891. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10892. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10893. for (var face = 0; face < 6; face++) {
  10894. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10895. }
  10896. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10897. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10898. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10899. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10900. // Create the framebuffer
  10901. var framebuffer = gl.createFramebuffer();
  10902. this.bindUnboundFramebuffer(framebuffer);
  10903. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10904. // Mipmaps
  10905. if (texture.generateMipMaps) {
  10906. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10907. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10908. }
  10909. // Unbind
  10910. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10911. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10912. this.bindUnboundFramebuffer(null);
  10913. texture._framebuffer = framebuffer;
  10914. texture.width = size;
  10915. texture.height = size;
  10916. texture.isReady = true;
  10917. this.resetTextureCache();
  10918. this._internalTexturesCache.push(texture);
  10919. return texture;
  10920. };
  10921. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10922. var _this = this;
  10923. if (onLoad === void 0) { onLoad = null; }
  10924. if (onError === void 0) { onError = null; }
  10925. if (forcedExtension === void 0) { forcedExtension = null; }
  10926. var callback = function (loadData) {
  10927. if (!loadData) {
  10928. if (onLoad) {
  10929. onLoad(null);
  10930. }
  10931. return;
  10932. }
  10933. var texture = loadData.texture;
  10934. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10935. texture._lodGenerationScale = scale;
  10936. texture._lodGenerationOffset = offset;
  10937. if (_this._caps.textureLOD) {
  10938. // Do not add extra process if texture lod is supported.
  10939. if (onLoad) {
  10940. onLoad(texture);
  10941. }
  10942. return;
  10943. }
  10944. var mipSlices = 3;
  10945. var gl = _this._gl;
  10946. var width = loadData.width;
  10947. if (!width) {
  10948. return;
  10949. }
  10950. var textures = [];
  10951. for (var i = 0; i < mipSlices; i++) {
  10952. //compute LOD from even spacing in smoothness (matching shader calculation)
  10953. var smoothness = i / (mipSlices - 1);
  10954. var roughness = 1 - smoothness;
  10955. var minLODIndex = offset; // roughness = 0
  10956. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10957. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10958. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10959. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10960. glTextureFromLod.isCube = true;
  10961. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10962. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10963. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10964. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10965. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10966. if (loadData.isDDS) {
  10967. var info = loadData.info;
  10968. var data = loadData.data;
  10969. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10970. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10971. }
  10972. else {
  10973. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10974. }
  10975. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10976. // Wrap in a base texture for easy binding.
  10977. var lodTexture = new BABYLON.BaseTexture(scene);
  10978. lodTexture.isCube = true;
  10979. lodTexture._texture = glTextureFromLod;
  10980. glTextureFromLod.isReady = true;
  10981. textures.push(lodTexture);
  10982. }
  10983. texture._lodTextureHigh = textures[2];
  10984. texture._lodTextureMid = textures[1];
  10985. texture._lodTextureLow = textures[0];
  10986. if (onLoad) {
  10987. onLoad(texture);
  10988. }
  10989. };
  10990. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10991. };
  10992. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10993. var _this = this;
  10994. if (onLoad === void 0) { onLoad = null; }
  10995. if (onError === void 0) { onError = null; }
  10996. if (forcedExtension === void 0) { forcedExtension = null; }
  10997. var gl = this._gl;
  10998. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10999. texture.isCube = true;
  11000. texture.url = rootUrl;
  11001. texture.generateMipMaps = !noMipmap;
  11002. if (!this._doNotHandleContextLost) {
  11003. texture._extension = forcedExtension;
  11004. texture._files = files;
  11005. }
  11006. var isKTX = false;
  11007. var isDDS = false;
  11008. var lastDot = rootUrl.lastIndexOf('.');
  11009. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  11010. if (this._textureFormatInUse) {
  11011. extension = this._textureFormatInUse;
  11012. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  11013. isKTX = true;
  11014. }
  11015. else {
  11016. isDDS = (extension === ".dds");
  11017. }
  11018. var onerror = function (request, exception) {
  11019. if (onError && request) {
  11020. onError(request.status + " " + request.statusText, exception);
  11021. }
  11022. };
  11023. if (isKTX) {
  11024. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11025. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  11026. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  11027. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11028. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  11029. ktx.uploadLevels(_this._gl, !noMipmap);
  11030. _this.setCubeMapTextureParams(gl, loadMipmap);
  11031. texture.width = ktx.pixelWidth;
  11032. texture.height = ktx.pixelHeight;
  11033. texture.isReady = true;
  11034. }, undefined, undefined, true, onerror);
  11035. }
  11036. else if (isDDS) {
  11037. if (files && files.length === 6) {
  11038. cascadeLoadFiles(rootUrl, scene, function (imgs) {
  11039. var info;
  11040. var loadMipmap = false;
  11041. var width = 0;
  11042. for (var index = 0; index < imgs.length; index++) {
  11043. var data = imgs[index];
  11044. info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11045. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11046. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11047. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11048. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  11049. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11050. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11051. }
  11052. texture.width = info.width;
  11053. texture.height = info.height;
  11054. texture.type = info.textureType;
  11055. width = info.width;
  11056. }
  11057. _this.setCubeMapTextureParams(gl, loadMipmap);
  11058. texture.isReady = true;
  11059. if (onLoad) {
  11060. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  11061. }
  11062. }, files, onError);
  11063. }
  11064. else {
  11065. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11066. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11067. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11068. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11069. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11070. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  11071. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11072. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11073. }
  11074. _this.setCubeMapTextureParams(gl, loadMipmap);
  11075. texture.width = info.width;
  11076. texture.height = info.height;
  11077. texture.isReady = true;
  11078. texture.type = info.textureType;
  11079. if (onLoad) {
  11080. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  11081. }
  11082. }, undefined, undefined, true, onerror);
  11083. }
  11084. }
  11085. else {
  11086. if (!files) {
  11087. throw new Error("Cannot load cubemap because files were not defined");
  11088. }
  11089. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  11090. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  11091. var height = width;
  11092. _this._prepareWorkingCanvas();
  11093. if (!_this._workingCanvas || !_this._workingContext) {
  11094. return;
  11095. }
  11096. _this._workingCanvas.width = width;
  11097. _this._workingCanvas.height = height;
  11098. var faces = [
  11099. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  11100. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  11101. ];
  11102. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11103. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11104. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  11105. for (var index = 0; index < faces.length; index++) {
  11106. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  11107. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  11108. }
  11109. if (!noMipmap) {
  11110. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11111. }
  11112. _this.setCubeMapTextureParams(gl, !noMipmap);
  11113. texture.width = width;
  11114. texture.height = height;
  11115. texture.isReady = true;
  11116. if (format) {
  11117. texture.format = format;
  11118. }
  11119. texture.onLoadedObservable.notifyObservers(texture);
  11120. texture.onLoadedObservable.clear();
  11121. if (onLoad) {
  11122. onLoad();
  11123. }
  11124. }, files, onError);
  11125. }
  11126. this._internalTexturesCache.push(texture);
  11127. return texture;
  11128. };
  11129. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  11130. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11131. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  11132. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11133. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11134. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11135. this.resetTextureCache();
  11136. };
  11137. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11138. if (compression === void 0) { compression = null; }
  11139. if (level === void 0) { level = 0; }
  11140. texture._bufferViewArray = data;
  11141. texture.format = format;
  11142. texture.type = type;
  11143. texture.invertY = invertY;
  11144. texture._compression = compression;
  11145. var gl = this._gl;
  11146. var textureType = this._getWebGLTextureType(type);
  11147. var internalFormat = this._getInternalFormat(format);
  11148. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11149. var needConversion = false;
  11150. if (internalFormat === gl.RGB) {
  11151. internalFormat = gl.RGBA;
  11152. needConversion = true;
  11153. }
  11154. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11155. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11156. if (texture.width % 4 !== 0) {
  11157. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11158. }
  11159. // Data are known to be in +X +Y +Z -X -Y -Z
  11160. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11161. var faceData = data[faceIndex];
  11162. if (compression) {
  11163. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11164. }
  11165. else {
  11166. if (needConversion) {
  11167. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11168. }
  11169. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11170. }
  11171. }
  11172. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11173. if (isPot && texture.generateMipMaps && level === 0) {
  11174. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11175. }
  11176. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11177. this.resetTextureCache();
  11178. texture.isReady = true;
  11179. };
  11180. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11181. if (compression === void 0) { compression = null; }
  11182. var gl = this._gl;
  11183. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11184. texture.isCube = true;
  11185. texture.generateMipMaps = generateMipMaps;
  11186. texture.format = format;
  11187. texture.type = type;
  11188. if (!this._doNotHandleContextLost) {
  11189. texture._bufferViewArray = data;
  11190. }
  11191. var textureType = this._getWebGLTextureType(type);
  11192. var internalFormat = this._getInternalFormat(format);
  11193. if (internalFormat === gl.RGB) {
  11194. internalFormat = gl.RGBA;
  11195. }
  11196. var width = size;
  11197. var height = width;
  11198. texture.width = width;
  11199. texture.height = height;
  11200. // Double check on POT to generate Mips.
  11201. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11202. if (!isPot) {
  11203. generateMipMaps = false;
  11204. }
  11205. // Upload data if needed. The texture won't be ready until then.
  11206. if (data) {
  11207. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11208. }
  11209. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11210. // Filters
  11211. if (data && generateMipMaps) {
  11212. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11213. }
  11214. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11215. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11216. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11217. }
  11218. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11219. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11220. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11221. }
  11222. else {
  11223. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11224. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11225. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11226. }
  11227. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11228. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11229. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11230. return texture;
  11231. };
  11232. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11233. var _this = this;
  11234. if (onLoad === void 0) { onLoad = null; }
  11235. if (onError === void 0) { onError = null; }
  11236. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11237. if (invertY === void 0) { invertY = false; }
  11238. var gl = this._gl;
  11239. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11240. scene._addPendingData(texture);
  11241. texture.url = url;
  11242. this._internalTexturesCache.push(texture);
  11243. var onerror = function (request, exception) {
  11244. scene._removePendingData(texture);
  11245. if (onError && request) {
  11246. onError(request.status + " " + request.statusText, exception);
  11247. }
  11248. };
  11249. var internalCallback = function (data) {
  11250. var width = texture.width;
  11251. var faceDataArrays = callback(data);
  11252. if (!faceDataArrays) {
  11253. return;
  11254. }
  11255. if (mipmmapGenerator) {
  11256. var textureType = _this._getWebGLTextureType(type);
  11257. var internalFormat = _this._getInternalFormat(format);
  11258. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11259. var needConversion = false;
  11260. if (internalFormat === gl.RGB) {
  11261. internalFormat = gl.RGBA;
  11262. needConversion = true;
  11263. }
  11264. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11265. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11266. var mipData = mipmmapGenerator(faceDataArrays);
  11267. for (var level = 0; level < mipData.length; level++) {
  11268. var mipSize = width >> level;
  11269. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11270. var mipFaceData = mipData[level][faceIndex];
  11271. if (needConversion) {
  11272. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11273. }
  11274. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11275. }
  11276. }
  11277. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11278. }
  11279. else {
  11280. texture.generateMipMaps = !noMipmap;
  11281. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11282. }
  11283. texture.isReady = true;
  11284. _this.resetTextureCache();
  11285. scene._removePendingData(texture);
  11286. if (onLoad) {
  11287. onLoad();
  11288. }
  11289. };
  11290. BABYLON.Tools.LoadFile(url, function (data) {
  11291. internalCallback(data);
  11292. }, undefined, scene.database, true, onerror);
  11293. return texture;
  11294. };
  11295. ;
  11296. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11297. if (compression === void 0) { compression = null; }
  11298. var internalFormat = this._getInternalFormat(format);
  11299. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11300. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11301. if (!this._doNotHandleContextLost) {
  11302. texture._bufferView = data;
  11303. texture.format = format;
  11304. texture.invertY = invertY;
  11305. texture._compression = compression;
  11306. }
  11307. if (texture.width % 4 !== 0) {
  11308. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11309. }
  11310. if (compression && data) {
  11311. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11312. }
  11313. else {
  11314. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11315. }
  11316. if (texture.generateMipMaps) {
  11317. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11318. }
  11319. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11320. this.resetTextureCache();
  11321. texture.isReady = true;
  11322. };
  11323. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11324. if (compression === void 0) { compression = null; }
  11325. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11326. texture.baseWidth = width;
  11327. texture.baseHeight = height;
  11328. texture.baseDepth = depth;
  11329. texture.width = width;
  11330. texture.height = height;
  11331. texture.depth = depth;
  11332. texture.format = format;
  11333. texture.generateMipMaps = generateMipMaps;
  11334. texture.samplingMode = samplingMode;
  11335. texture.is3D = true;
  11336. if (!this._doNotHandleContextLost) {
  11337. texture._bufferView = data;
  11338. }
  11339. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11340. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11341. // Filters
  11342. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11343. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11344. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11345. if (generateMipMaps) {
  11346. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11347. }
  11348. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11349. this._internalTexturesCache.push(texture);
  11350. return texture;
  11351. };
  11352. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11353. var gl = this._gl;
  11354. if (!gl) {
  11355. return;
  11356. }
  11357. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11358. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11359. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11360. if (!noMipmap && !isCompressed) {
  11361. gl.generateMipmap(gl.TEXTURE_2D);
  11362. }
  11363. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11364. this.resetTextureCache();
  11365. if (scene) {
  11366. scene._removePendingData(texture);
  11367. }
  11368. texture.onLoadedObservable.notifyObservers(texture);
  11369. texture.onLoadedObservable.clear();
  11370. };
  11371. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11372. var _this = this;
  11373. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11374. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11375. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11376. var gl = this._gl;
  11377. if (!gl) {
  11378. return;
  11379. }
  11380. if (!texture._webGLTexture) {
  11381. this.resetTextureCache();
  11382. if (scene) {
  11383. scene._removePendingData(texture);
  11384. }
  11385. return;
  11386. }
  11387. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11388. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11389. texture.baseWidth = width;
  11390. texture.baseHeight = height;
  11391. texture.width = potWidth;
  11392. texture.height = potHeight;
  11393. texture.isReady = true;
  11394. if (processFunction(potWidth, potHeight, function () {
  11395. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11396. })) {
  11397. // Returning as texture needs extra async steps
  11398. return;
  11399. }
  11400. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11401. };
  11402. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11403. // Create new RGBA data container.
  11404. var rgbaData;
  11405. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11406. rgbaData = new Float32Array(width * height * 4);
  11407. }
  11408. else {
  11409. rgbaData = new Uint32Array(width * height * 4);
  11410. }
  11411. // Convert each pixel.
  11412. for (var x = 0; x < width; x++) {
  11413. for (var y = 0; y < height; y++) {
  11414. var index = (y * width + x) * 3;
  11415. var newIndex = (y * width + x) * 4;
  11416. // Map Old Value to new value.
  11417. rgbaData[newIndex + 0] = rgbData[index + 0];
  11418. rgbaData[newIndex + 1] = rgbData[index + 1];
  11419. rgbaData[newIndex + 2] = rgbData[index + 2];
  11420. // Add fully opaque alpha channel.
  11421. rgbaData[newIndex + 3] = 1;
  11422. }
  11423. }
  11424. return rgbaData;
  11425. };
  11426. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11427. var gl = this._gl;
  11428. if (texture._framebuffer) {
  11429. gl.deleteFramebuffer(texture._framebuffer);
  11430. texture._framebuffer = null;
  11431. }
  11432. if (texture._depthStencilBuffer) {
  11433. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11434. texture._depthStencilBuffer = null;
  11435. }
  11436. if (texture._MSAAFramebuffer) {
  11437. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11438. texture._MSAAFramebuffer = null;
  11439. }
  11440. if (texture._MSAARenderBuffer) {
  11441. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11442. texture._MSAARenderBuffer = null;
  11443. }
  11444. };
  11445. Engine.prototype._releaseTexture = function (texture) {
  11446. var gl = this._gl;
  11447. this._releaseFramebufferObjects(texture);
  11448. gl.deleteTexture(texture._webGLTexture);
  11449. // Unbind channels
  11450. this.unbindAllTextures();
  11451. var index = this._internalTexturesCache.indexOf(texture);
  11452. if (index !== -1) {
  11453. this._internalTexturesCache.splice(index, 1);
  11454. }
  11455. // Integrated fixed lod samplers.
  11456. if (texture._lodTextureHigh) {
  11457. texture._lodTextureHigh.dispose();
  11458. }
  11459. if (texture._lodTextureMid) {
  11460. texture._lodTextureMid.dispose();
  11461. }
  11462. if (texture._lodTextureLow) {
  11463. texture._lodTextureLow.dispose();
  11464. }
  11465. };
  11466. Engine.prototype.setProgram = function (program) {
  11467. if (this._currentProgram !== program) {
  11468. this._gl.useProgram(program);
  11469. this._currentProgram = program;
  11470. }
  11471. };
  11472. Engine.prototype.bindSamplers = function (effect) {
  11473. this.setProgram(effect.getProgram());
  11474. var samplers = effect.getSamplers();
  11475. for (var index = 0; index < samplers.length; index++) {
  11476. var uniform = effect.getUniform(samplers[index]);
  11477. this._gl.uniform1i(uniform, index);
  11478. }
  11479. this._currentEffect = null;
  11480. };
  11481. Engine.prototype.activateTextureChannel = function (textureChannel) {
  11482. if (this._activeTextureChannel !== textureChannel) {
  11483. this._gl.activeTexture(textureChannel);
  11484. this._activeTextureChannel = textureChannel;
  11485. }
  11486. };
  11487. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11488. if (this._activeTexturesCache[this._activeTextureChannel] !== texture) {
  11489. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11490. this._activeTexturesCache[this._activeTextureChannel] = texture;
  11491. }
  11492. };
  11493. Engine.prototype._bindTexture = function (channel, texture) {
  11494. if (channel < 0) {
  11495. return;
  11496. }
  11497. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11498. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11499. };
  11500. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11501. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11502. };
  11503. Engine.prototype.unbindAllTextures = function () {
  11504. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11505. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11506. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11507. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11508. if (this.webGLVersion > 1) {
  11509. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11510. }
  11511. }
  11512. };
  11513. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11514. if (channel < 0) {
  11515. return;
  11516. }
  11517. if (this._setTexture(channel, texture)) {
  11518. this._gl.uniform1i(uniform, channel);
  11519. }
  11520. };
  11521. Engine.prototype._setTexture = function (channel, texture) {
  11522. // Not ready?
  11523. if (!texture) {
  11524. if (this._activeTexturesCache[channel] != null) {
  11525. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11526. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11527. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11528. if (this.webGLVersion > 1) {
  11529. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11530. }
  11531. }
  11532. return false;
  11533. }
  11534. // Video
  11535. var alreadyActivated = false;
  11536. if (texture.video) {
  11537. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11538. alreadyActivated = true;
  11539. texture.update();
  11540. }
  11541. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11542. texture.delayLoad();
  11543. return false;
  11544. }
  11545. var internalTexture;
  11546. if (texture.isReady()) {
  11547. internalTexture = texture.getInternalTexture();
  11548. }
  11549. else if (texture.isCube) {
  11550. internalTexture = this.emptyCubeTexture;
  11551. }
  11552. else if (texture.is3D) {
  11553. internalTexture = this.emptyTexture3D;
  11554. }
  11555. else {
  11556. internalTexture = this.emptyTexture;
  11557. }
  11558. if (!alreadyActivated) {
  11559. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11560. }
  11561. if (this._activeTexturesCache[this._activeTextureChannel] === internalTexture) {
  11562. return false;
  11563. }
  11564. if (internalTexture && internalTexture.is3D) {
  11565. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11566. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11567. internalTexture._cachedWrapU = texture.wrapU;
  11568. switch (texture.wrapU) {
  11569. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11570. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11571. break;
  11572. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11573. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11574. break;
  11575. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11576. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11577. break;
  11578. }
  11579. }
  11580. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11581. internalTexture._cachedWrapV = texture.wrapV;
  11582. switch (texture.wrapV) {
  11583. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11584. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11585. break;
  11586. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11587. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11588. break;
  11589. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11590. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11591. break;
  11592. }
  11593. }
  11594. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11595. internalTexture._cachedWrapR = texture.wrapR;
  11596. switch (texture.wrapV) {
  11597. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11598. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11599. break;
  11600. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11601. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11602. break;
  11603. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11604. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11605. break;
  11606. }
  11607. }
  11608. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11609. }
  11610. else if (internalTexture && internalTexture.isCube) {
  11611. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11612. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11613. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11614. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11615. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11616. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11617. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11618. }
  11619. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11620. }
  11621. else {
  11622. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11623. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11624. internalTexture._cachedWrapU = texture.wrapU;
  11625. switch (texture.wrapU) {
  11626. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11627. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11628. break;
  11629. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11630. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11631. break;
  11632. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11633. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11634. break;
  11635. }
  11636. }
  11637. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11638. internalTexture._cachedWrapV = texture.wrapV;
  11639. switch (texture.wrapV) {
  11640. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11641. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11642. break;
  11643. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11644. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11645. break;
  11646. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11647. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11648. break;
  11649. }
  11650. }
  11651. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11652. }
  11653. return true;
  11654. };
  11655. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11656. if (channel < 0 || !uniform) {
  11657. return;
  11658. }
  11659. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11660. this._textureUnits = new Int32Array(textures.length);
  11661. }
  11662. for (var i = 0; i < textures.length; i++) {
  11663. this._textureUnits[i] = channel + i;
  11664. }
  11665. this._gl.uniform1iv(uniform, this._textureUnits);
  11666. for (var index = 0; index < textures.length; index++) {
  11667. this._setTexture(channel + index, textures[index]);
  11668. }
  11669. };
  11670. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11671. var internalTexture = texture.getInternalTexture();
  11672. if (!internalTexture) {
  11673. return;
  11674. }
  11675. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11676. var value = texture.anisotropicFilteringLevel;
  11677. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11678. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11679. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11680. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11681. }
  11682. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11683. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11684. internalTexture._cachedAnisotropicFilteringLevel = value;
  11685. }
  11686. };
  11687. Engine.prototype.readPixels = function (x, y, width, height) {
  11688. var data = new Uint8Array(height * width * 4);
  11689. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11690. return data;
  11691. };
  11692. /**
  11693. * Add an externaly attached data from its key.
  11694. * This method call will fail and return false, if such key already exists.
  11695. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11696. * @param key the unique key that identifies the data
  11697. * @param data the data object to associate to the key for this Engine instance
  11698. * @return true if no such key were already present and the data was added successfully, false otherwise
  11699. */
  11700. Engine.prototype.addExternalData = function (key, data) {
  11701. if (!this._externalData) {
  11702. this._externalData = new BABYLON.StringDictionary();
  11703. }
  11704. return this._externalData.add(key, data);
  11705. };
  11706. /**
  11707. * Get an externaly attached data from its key
  11708. * @param key the unique key that identifies the data
  11709. * @return the associated data, if present (can be null), or undefined if not present
  11710. */
  11711. Engine.prototype.getExternalData = function (key) {
  11712. if (!this._externalData) {
  11713. this._externalData = new BABYLON.StringDictionary();
  11714. }
  11715. return this._externalData.get(key);
  11716. };
  11717. /**
  11718. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11719. * @param key the unique key that identifies the data
  11720. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11721. * @return the associated data, can be null if the factory returned null.
  11722. */
  11723. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11724. if (!this._externalData) {
  11725. this._externalData = new BABYLON.StringDictionary();
  11726. }
  11727. return this._externalData.getOrAddWithFactory(key, factory);
  11728. };
  11729. /**
  11730. * Remove an externaly attached data from the Engine instance
  11731. * @param key the unique key that identifies the data
  11732. * @return true if the data was successfully removed, false if it doesn't exist
  11733. */
  11734. Engine.prototype.removeExternalData = function (key) {
  11735. if (!this._externalData) {
  11736. this._externalData = new BABYLON.StringDictionary();
  11737. }
  11738. return this._externalData.remove(key);
  11739. };
  11740. Engine.prototype.unbindAllAttributes = function () {
  11741. if (this._mustWipeVertexAttributes) {
  11742. this._mustWipeVertexAttributes = false;
  11743. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11744. this._gl.disableVertexAttribArray(i);
  11745. this._vertexAttribArraysEnabled[i] = false;
  11746. this._currentBufferPointers[i].active = false;
  11747. }
  11748. return;
  11749. }
  11750. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11751. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11752. continue;
  11753. }
  11754. this._gl.disableVertexAttribArray(i);
  11755. this._vertexAttribArraysEnabled[i] = false;
  11756. this._currentBufferPointers[i].active = false;
  11757. }
  11758. };
  11759. Engine.prototype.releaseEffects = function () {
  11760. for (var name in this._compiledEffects) {
  11761. this._deleteProgram(this._compiledEffects[name]._program);
  11762. }
  11763. this._compiledEffects = {};
  11764. };
  11765. // Dispose
  11766. Engine.prototype.dispose = function () {
  11767. this.hideLoadingUI();
  11768. this.stopRenderLoop();
  11769. // Release postProcesses
  11770. while (this.postProcesses.length) {
  11771. this.postProcesses[0].dispose();
  11772. }
  11773. // Empty texture
  11774. if (this._emptyTexture) {
  11775. this._releaseTexture(this._emptyTexture);
  11776. this._emptyTexture = null;
  11777. }
  11778. if (this._emptyCubeTexture) {
  11779. this._releaseTexture(this._emptyCubeTexture);
  11780. this._emptyCubeTexture = null;
  11781. }
  11782. // Rescale PP
  11783. if (this._rescalePostProcess) {
  11784. this._rescalePostProcess.dispose();
  11785. }
  11786. // Release scenes
  11787. while (this.scenes.length) {
  11788. this.scenes[0].dispose();
  11789. }
  11790. // Release audio engine
  11791. if (Engine.audioEngine) {
  11792. Engine.audioEngine.dispose();
  11793. }
  11794. // Release effects
  11795. this.releaseEffects();
  11796. // Unbind
  11797. this.unbindAllAttributes();
  11798. if (this._dummyFramebuffer) {
  11799. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11800. }
  11801. //WebVR
  11802. this.disableVR();
  11803. // Events
  11804. if (BABYLON.Tools.IsWindowObjectExist()) {
  11805. window.removeEventListener("blur", this._onBlur);
  11806. window.removeEventListener("focus", this._onFocus);
  11807. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11808. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11809. if (this._renderingCanvas) {
  11810. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11811. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11812. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11813. if (!this._doNotHandleContextLost) {
  11814. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11815. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11816. }
  11817. }
  11818. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11819. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11820. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11821. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11822. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11823. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11824. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11825. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11826. if (this._onVrDisplayConnect) {
  11827. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11828. if (this._onVrDisplayDisconnect) {
  11829. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11830. }
  11831. if (this._onVrDisplayPresentChange) {
  11832. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11833. }
  11834. this._onVrDisplayConnect = null;
  11835. this._onVrDisplayDisconnect = null;
  11836. }
  11837. }
  11838. // Remove from Instances
  11839. var index = Engine.Instances.indexOf(this);
  11840. if (index >= 0) {
  11841. Engine.Instances.splice(index, 1);
  11842. }
  11843. this._workingCanvas = null;
  11844. this._workingContext = null;
  11845. this._currentBufferPointers = [];
  11846. this._renderingCanvas = null;
  11847. this._currentProgram = null;
  11848. this.onResizeObservable.clear();
  11849. this.onCanvasBlurObservable.clear();
  11850. this.onCanvasFocusObservable.clear();
  11851. this.onCanvasPointerOutObservable.clear();
  11852. this.onBeginFrameObservable.clear();
  11853. this.onEndFrameObservable.clear();
  11854. BABYLON.Effect.ResetCache();
  11855. };
  11856. // Loading screen
  11857. Engine.prototype.displayLoadingUI = function () {
  11858. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11859. return;
  11860. }
  11861. var loadingScreen = this.loadingScreen;
  11862. if (loadingScreen) {
  11863. loadingScreen.displayLoadingUI();
  11864. }
  11865. };
  11866. Engine.prototype.hideLoadingUI = function () {
  11867. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11868. return;
  11869. }
  11870. var loadingScreen = this.loadingScreen;
  11871. if (loadingScreen) {
  11872. loadingScreen.hideLoadingUI();
  11873. }
  11874. };
  11875. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11876. get: function () {
  11877. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11878. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11879. return this._loadingScreen;
  11880. },
  11881. set: function (loadingScreen) {
  11882. this._loadingScreen = loadingScreen;
  11883. },
  11884. enumerable: true,
  11885. configurable: true
  11886. });
  11887. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11888. set: function (text) {
  11889. this.loadingScreen.loadingUIText = text;
  11890. },
  11891. enumerable: true,
  11892. configurable: true
  11893. });
  11894. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11895. set: function (color) {
  11896. this.loadingScreen.loadingUIBackgroundColor = color;
  11897. },
  11898. enumerable: true,
  11899. configurable: true
  11900. });
  11901. Engine.prototype.attachContextLostEvent = function (callback) {
  11902. if (this._renderingCanvas) {
  11903. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11904. }
  11905. };
  11906. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11907. if (this._renderingCanvas) {
  11908. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11909. }
  11910. };
  11911. Engine.prototype.getVertexShaderSource = function (program) {
  11912. var shaders = this._gl.getAttachedShaders(program);
  11913. if (!shaders) {
  11914. return null;
  11915. }
  11916. return this._gl.getShaderSource(shaders[0]);
  11917. };
  11918. Engine.prototype.getFragmentShaderSource = function (program) {
  11919. var shaders = this._gl.getAttachedShaders(program);
  11920. if (!shaders) {
  11921. return null;
  11922. }
  11923. return this._gl.getShaderSource(shaders[1]);
  11924. };
  11925. Engine.prototype.getError = function () {
  11926. return this._gl.getError();
  11927. };
  11928. // FPS
  11929. Engine.prototype.getFps = function () {
  11930. return this._fps;
  11931. };
  11932. Engine.prototype.getDeltaTime = function () {
  11933. return this._deltaTime;
  11934. };
  11935. Engine.prototype._measureFps = function () {
  11936. this._performanceMonitor.sampleFrame();
  11937. this._fps = this._performanceMonitor.averageFPS;
  11938. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11939. };
  11940. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11941. if (faceIndex === void 0) { faceIndex = -1; }
  11942. var gl = this._gl;
  11943. if (!this._dummyFramebuffer) {
  11944. var dummy = gl.createFramebuffer();
  11945. if (!dummy) {
  11946. throw new Error("Unable to create dummy framebuffer");
  11947. }
  11948. this._dummyFramebuffer = dummy;
  11949. }
  11950. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11951. if (faceIndex > -1) {
  11952. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11953. }
  11954. else {
  11955. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11956. }
  11957. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11958. var buffer;
  11959. switch (readType) {
  11960. case gl.UNSIGNED_BYTE:
  11961. buffer = new Uint8Array(4 * width * height);
  11962. readType = gl.UNSIGNED_BYTE;
  11963. break;
  11964. default:
  11965. buffer = new Float32Array(4 * width * height);
  11966. readType = gl.FLOAT;
  11967. break;
  11968. }
  11969. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11970. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11971. return buffer;
  11972. };
  11973. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11974. if (this._webGLVersion > 1) {
  11975. return this._caps.colorBufferFloat;
  11976. }
  11977. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11978. };
  11979. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11980. if (this._webGLVersion > 1) {
  11981. return this._caps.colorBufferFloat;
  11982. }
  11983. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11984. };
  11985. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11986. Engine.prototype._canRenderToFramebuffer = function (type) {
  11987. var gl = this._gl;
  11988. //clear existing errors
  11989. while (gl.getError() !== gl.NO_ERROR) { }
  11990. var successful = true;
  11991. var texture = gl.createTexture();
  11992. gl.bindTexture(gl.TEXTURE_2D, texture);
  11993. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11994. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11995. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11996. var fb = gl.createFramebuffer();
  11997. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11998. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11999. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  12000. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  12001. successful = successful && (gl.getError() === gl.NO_ERROR);
  12002. //try render by clearing frame buffer's color buffer
  12003. if (successful) {
  12004. gl.clear(gl.COLOR_BUFFER_BIT);
  12005. successful = successful && (gl.getError() === gl.NO_ERROR);
  12006. }
  12007. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  12008. if (successful) {
  12009. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  12010. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12011. var readFormat = gl.RGBA;
  12012. var readType = gl.UNSIGNED_BYTE;
  12013. var buffer = new Uint8Array(4);
  12014. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  12015. successful = successful && (gl.getError() === gl.NO_ERROR);
  12016. }
  12017. //clean up
  12018. gl.deleteTexture(texture);
  12019. gl.deleteFramebuffer(fb);
  12020. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12021. //clear accumulated errors
  12022. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  12023. return successful;
  12024. };
  12025. Engine.prototype._getWebGLTextureType = function (type) {
  12026. if (type === Engine.TEXTURETYPE_FLOAT) {
  12027. return this._gl.FLOAT;
  12028. }
  12029. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12030. // Add Half Float Constant.
  12031. return this._gl.HALF_FLOAT_OES;
  12032. }
  12033. return this._gl.UNSIGNED_BYTE;
  12034. };
  12035. ;
  12036. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  12037. if (this._webGLVersion === 1) {
  12038. return this._gl.RGBA;
  12039. }
  12040. if (type === Engine.TEXTURETYPE_FLOAT) {
  12041. return this._gl.RGBA32F;
  12042. }
  12043. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12044. return this._gl.RGBA16F;
  12045. }
  12046. return this._gl.RGBA;
  12047. };
  12048. ;
  12049. Engine.prototype.createQuery = function () {
  12050. return this._gl.createQuery();
  12051. };
  12052. Engine.prototype.deleteQuery = function (query) {
  12053. this._gl.deleteQuery(query);
  12054. return this;
  12055. };
  12056. Engine.prototype.isQueryResultAvailable = function (query) {
  12057. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  12058. };
  12059. Engine.prototype.getQueryResult = function (query) {
  12060. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  12061. };
  12062. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  12063. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12064. this._gl.beginQuery(glAlgorithm, query);
  12065. return this;
  12066. };
  12067. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  12068. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12069. this._gl.endQuery(glAlgorithm);
  12070. return this;
  12071. };
  12072. /* Time queries */
  12073. Engine.prototype._createTimeQuery = function () {
  12074. var timerQuery = this._caps.timerQuery;
  12075. if (timerQuery.createQueryEXT) {
  12076. return timerQuery.createQueryEXT();
  12077. }
  12078. return this.createQuery();
  12079. };
  12080. Engine.prototype._deleteTimeQuery = function (query) {
  12081. var timerQuery = this._caps.timerQuery;
  12082. if (timerQuery.deleteQueryEXT) {
  12083. timerQuery.deleteQueryEXT(query);
  12084. return;
  12085. }
  12086. this.deleteQuery(query);
  12087. };
  12088. Engine.prototype._getTimeQueryResult = function (query) {
  12089. var timerQuery = this._caps.timerQuery;
  12090. if (timerQuery.getQueryObjectEXT) {
  12091. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  12092. }
  12093. return this.getQueryResult(query);
  12094. };
  12095. Engine.prototype._getTimeQueryAvailability = function (query) {
  12096. var timerQuery = this._caps.timerQuery;
  12097. if (timerQuery.getQueryObjectEXT) {
  12098. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  12099. }
  12100. return this.isQueryResultAvailable(query);
  12101. };
  12102. Engine.prototype.startTimeQuery = function () {
  12103. var timerQuery = this._caps.timerQuery;
  12104. if (!timerQuery) {
  12105. return null;
  12106. }
  12107. var token = new BABYLON._TimeToken();
  12108. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12109. if (this._caps.canUseTimestampForTimerQuery) {
  12110. token._startTimeQuery = this._createTimeQuery();
  12111. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  12112. }
  12113. else {
  12114. if (this._currentNonTimestampToken) {
  12115. return this._currentNonTimestampToken;
  12116. }
  12117. token._timeElapsedQuery = this._createTimeQuery();
  12118. if (timerQuery.beginQueryEXT) {
  12119. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12120. }
  12121. else {
  12122. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12123. }
  12124. this._currentNonTimestampToken = token;
  12125. }
  12126. return token;
  12127. };
  12128. Engine.prototype.endTimeQuery = function (token) {
  12129. var timerQuery = this._caps.timerQuery;
  12130. if (!timerQuery || !token) {
  12131. return -1;
  12132. }
  12133. if (this._caps.canUseTimestampForTimerQuery) {
  12134. if (!token._startTimeQuery) {
  12135. return -1;
  12136. }
  12137. if (!token._endTimeQuery) {
  12138. token._endTimeQuery = this._createTimeQuery();
  12139. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12140. }
  12141. }
  12142. else if (!token._timeElapsedQueryEnded) {
  12143. if (!token._timeElapsedQuery) {
  12144. return -1;
  12145. }
  12146. if (timerQuery.endQueryEXT) {
  12147. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12148. }
  12149. else {
  12150. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12151. }
  12152. token._timeElapsedQueryEnded = true;
  12153. }
  12154. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12155. var available = false;
  12156. if (token._endTimeQuery) {
  12157. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12158. }
  12159. else if (token._timeElapsedQuery) {
  12160. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12161. }
  12162. if (available && !disjoint) {
  12163. var result = 0;
  12164. if (this._caps.canUseTimestampForTimerQuery) {
  12165. if (!token._startTimeQuery || !token._endTimeQuery) {
  12166. return -1;
  12167. }
  12168. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12169. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12170. result = timeEnd - timeStart;
  12171. this._deleteTimeQuery(token._startTimeQuery);
  12172. this._deleteTimeQuery(token._endTimeQuery);
  12173. token._startTimeQuery = null;
  12174. token._endTimeQuery = null;
  12175. }
  12176. else {
  12177. if (!token._timeElapsedQuery) {
  12178. return -1;
  12179. }
  12180. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12181. this._deleteTimeQuery(token._timeElapsedQuery);
  12182. token._timeElapsedQuery = null;
  12183. token._timeElapsedQueryEnded = false;
  12184. this._currentNonTimestampToken = null;
  12185. }
  12186. return result;
  12187. }
  12188. return -1;
  12189. };
  12190. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12191. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12192. };
  12193. // Transform feedback
  12194. Engine.prototype.createTransformFeedback = function () {
  12195. return this._gl.createTransformFeedback();
  12196. };
  12197. Engine.prototype.deleteTransformFeedback = function (value) {
  12198. this._gl.deleteTransformFeedback(value);
  12199. };
  12200. Engine.prototype.bindTransformFeedback = function (value) {
  12201. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12202. };
  12203. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12204. if (usePoints === void 0) { usePoints = true; }
  12205. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12206. };
  12207. Engine.prototype.endTransformFeedback = function () {
  12208. this._gl.endTransformFeedback();
  12209. };
  12210. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12211. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12212. };
  12213. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12214. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12215. };
  12216. // Statics
  12217. Engine.isSupported = function () {
  12218. try {
  12219. var tempcanvas = document.createElement("canvas");
  12220. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12221. return gl != null && !!window.WebGLRenderingContext;
  12222. }
  12223. catch (e) {
  12224. return false;
  12225. }
  12226. };
  12227. Engine.Instances = new Array();
  12228. // Const statics
  12229. Engine._ALPHA_DISABLE = 0;
  12230. Engine._ALPHA_ADD = 1;
  12231. Engine._ALPHA_COMBINE = 2;
  12232. Engine._ALPHA_SUBTRACT = 3;
  12233. Engine._ALPHA_MULTIPLY = 4;
  12234. Engine._ALPHA_MAXIMIZED = 5;
  12235. Engine._ALPHA_ONEONE = 6;
  12236. Engine._ALPHA_PREMULTIPLIED = 7;
  12237. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12238. Engine._ALPHA_INTERPOLATE = 9;
  12239. Engine._ALPHA_SCREENMODE = 10;
  12240. Engine._DELAYLOADSTATE_NONE = 0;
  12241. Engine._DELAYLOADSTATE_LOADED = 1;
  12242. Engine._DELAYLOADSTATE_LOADING = 2;
  12243. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12244. Engine._TEXTUREFORMAT_ALPHA = 0;
  12245. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12246. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12247. Engine._TEXTUREFORMAT_RGB = 4;
  12248. Engine._TEXTUREFORMAT_RGBA = 5;
  12249. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12250. Engine._TEXTURETYPE_FLOAT = 1;
  12251. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12252. // Depht or Stencil test Constants.
  12253. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12254. 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.
  12255. 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.
  12256. 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.
  12257. 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.
  12258. 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.
  12259. 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.
  12260. 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.
  12261. // Stencil Actions Constants.
  12262. Engine._KEEP = 0x1E00;
  12263. Engine._REPLACE = 0x1E01;
  12264. Engine._INCR = 0x1E02;
  12265. Engine._DECR = 0x1E03;
  12266. Engine._INVERT = 0x150A;
  12267. Engine._INCR_WRAP = 0x8507;
  12268. Engine._DECR_WRAP = 0x8508;
  12269. // Texture rescaling mode
  12270. Engine._SCALEMODE_FLOOR = 1;
  12271. Engine._SCALEMODE_NEAREST = 2;
  12272. Engine._SCALEMODE_CEILING = 3;
  12273. // Updatable statics so stick with vars here
  12274. Engine.CollisionsEpsilon = 0.001;
  12275. Engine.CodeRepository = "src/";
  12276. Engine.ShadersRepository = "src/Shaders/";
  12277. return Engine;
  12278. }());
  12279. BABYLON.Engine = Engine;
  12280. })(BABYLON || (BABYLON = {}));
  12281. //# sourceMappingURL=babylon.engine.js.map
  12282. var BABYLON;
  12283. (function (BABYLON) {
  12284. /**
  12285. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12286. */
  12287. var Node = /** @class */ (function () {
  12288. /**
  12289. * @constructor
  12290. * @param {string} name - the name and id to be given to this node
  12291. * @param {BABYLON.Scene} the scene this node will be added to
  12292. */
  12293. function Node(name, scene) {
  12294. if (scene === void 0) { scene = null; }
  12295. this.state = "";
  12296. this.metadata = null;
  12297. this.doNotSerialize = false;
  12298. this.animations = new Array();
  12299. this._ranges = {};
  12300. this._isEnabled = true;
  12301. this._isReady = true;
  12302. this._currentRenderId = -1;
  12303. this._parentRenderId = -1;
  12304. /**
  12305. * An event triggered when the mesh is disposed.
  12306. * @type {BABYLON.Observable}
  12307. */
  12308. this.onDisposeObservable = new BABYLON.Observable();
  12309. // Behaviors
  12310. this._behaviors = new Array();
  12311. this.name = name;
  12312. this.id = name;
  12313. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12314. this.uniqueId = this._scene.getUniqueId();
  12315. this._initCache();
  12316. }
  12317. Object.defineProperty(Node.prototype, "parent", {
  12318. get: function () {
  12319. return this._parentNode;
  12320. },
  12321. set: function (parent) {
  12322. if (this._parentNode === parent) {
  12323. return;
  12324. }
  12325. if (this._parentNode) {
  12326. var index = this._parentNode._children.indexOf(this);
  12327. if (index !== -1) {
  12328. this._parentNode._children.splice(index, 1);
  12329. }
  12330. }
  12331. this._parentNode = parent;
  12332. if (this._parentNode) {
  12333. if (!this._parentNode._children) {
  12334. this._parentNode._children = new Array();
  12335. }
  12336. this._parentNode._children.push(this);
  12337. }
  12338. },
  12339. enumerable: true,
  12340. configurable: true
  12341. });
  12342. Node.prototype.getClassName = function () {
  12343. return "Node";
  12344. };
  12345. Object.defineProperty(Node.prototype, "onDispose", {
  12346. set: function (callback) {
  12347. if (this._onDisposeObserver) {
  12348. this.onDisposeObservable.remove(this._onDisposeObserver);
  12349. }
  12350. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12351. },
  12352. enumerable: true,
  12353. configurable: true
  12354. });
  12355. Node.prototype.getScene = function () {
  12356. return this._scene;
  12357. };
  12358. Node.prototype.getEngine = function () {
  12359. return this._scene.getEngine();
  12360. };
  12361. Node.prototype.addBehavior = function (behavior) {
  12362. var _this = this;
  12363. var index = this._behaviors.indexOf(behavior);
  12364. if (index !== -1) {
  12365. return this;
  12366. }
  12367. behavior.init();
  12368. if (this._scene.isLoading) {
  12369. // We defer the attach when the scene will be loaded
  12370. var observer = this._scene.onDataLoadedObservable.add(function () {
  12371. behavior.attach(_this);
  12372. _this._scene.onDataLoadedObservable.remove(observer);
  12373. });
  12374. }
  12375. else {
  12376. behavior.attach(this);
  12377. }
  12378. this._behaviors.push(behavior);
  12379. return this;
  12380. };
  12381. Node.prototype.removeBehavior = function (behavior) {
  12382. var index = this._behaviors.indexOf(behavior);
  12383. if (index === -1) {
  12384. return this;
  12385. }
  12386. this._behaviors[index].detach();
  12387. this._behaviors.splice(index, 1);
  12388. return this;
  12389. };
  12390. Object.defineProperty(Node.prototype, "behaviors", {
  12391. get: function () {
  12392. return this._behaviors;
  12393. },
  12394. enumerable: true,
  12395. configurable: true
  12396. });
  12397. Node.prototype.getBehaviorByName = function (name) {
  12398. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12399. var behavior = _a[_i];
  12400. if (behavior.name === name) {
  12401. return behavior;
  12402. }
  12403. }
  12404. return null;
  12405. };
  12406. // override it in derived class
  12407. Node.prototype.getWorldMatrix = function () {
  12408. return BABYLON.Matrix.Identity();
  12409. };
  12410. // override it in derived class if you add new variables to the cache
  12411. // and call the parent class method
  12412. Node.prototype._initCache = function () {
  12413. this._cache = {};
  12414. this._cache.parent = undefined;
  12415. };
  12416. Node.prototype.updateCache = function (force) {
  12417. if (!force && this.isSynchronized())
  12418. return;
  12419. this._cache.parent = this.parent;
  12420. this._updateCache();
  12421. };
  12422. // override it in derived class if you add new variables to the cache
  12423. // and call the parent class method if !ignoreParentClass
  12424. Node.prototype._updateCache = function (ignoreParentClass) {
  12425. };
  12426. // override it in derived class if you add new variables to the cache
  12427. Node.prototype._isSynchronized = function () {
  12428. return true;
  12429. };
  12430. Node.prototype._markSyncedWithParent = function () {
  12431. if (this.parent) {
  12432. this._parentRenderId = this.parent._currentRenderId;
  12433. }
  12434. };
  12435. Node.prototype.isSynchronizedWithParent = function () {
  12436. if (!this.parent) {
  12437. return true;
  12438. }
  12439. if (this._parentRenderId !== this.parent._currentRenderId) {
  12440. return false;
  12441. }
  12442. return this.parent.isSynchronized();
  12443. };
  12444. Node.prototype.isSynchronized = function (updateCache) {
  12445. var check = this.hasNewParent();
  12446. check = check || !this.isSynchronizedWithParent();
  12447. check = check || !this._isSynchronized();
  12448. if (updateCache)
  12449. this.updateCache(true);
  12450. return !check;
  12451. };
  12452. Node.prototype.hasNewParent = function (update) {
  12453. if (this._cache.parent === this.parent)
  12454. return false;
  12455. if (update)
  12456. this._cache.parent = this.parent;
  12457. return true;
  12458. };
  12459. /**
  12460. * Is this node ready to be used/rendered
  12461. * @return {boolean} is it ready
  12462. */
  12463. Node.prototype.isReady = function () {
  12464. return this._isReady;
  12465. };
  12466. /**
  12467. * Is this node enabled.
  12468. * If the node has a parent and is enabled, the parent will be inspected as well.
  12469. * @return {boolean} whether this node (and its parent) is enabled.
  12470. * @see setEnabled
  12471. */
  12472. Node.prototype.isEnabled = function () {
  12473. if (!this._isEnabled) {
  12474. return false;
  12475. }
  12476. if (this.parent) {
  12477. return this.parent.isEnabled();
  12478. }
  12479. return true;
  12480. };
  12481. /**
  12482. * Set the enabled state of this node.
  12483. * @param {boolean} value - the new enabled state
  12484. * @see isEnabled
  12485. */
  12486. Node.prototype.setEnabled = function (value) {
  12487. this._isEnabled = value;
  12488. };
  12489. /**
  12490. * Is this node a descendant of the given node.
  12491. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12492. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12493. * @see parent
  12494. */
  12495. Node.prototype.isDescendantOf = function (ancestor) {
  12496. if (this.parent) {
  12497. if (this.parent === ancestor) {
  12498. return true;
  12499. }
  12500. return this.parent.isDescendantOf(ancestor);
  12501. }
  12502. return false;
  12503. };
  12504. /**
  12505. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12506. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12507. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  12508. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  12509. */
  12510. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12511. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12512. if (!this._children) {
  12513. return;
  12514. }
  12515. for (var index = 0; index < this._children.length; index++) {
  12516. var item = this._children[index];
  12517. if (!predicate || predicate(item)) {
  12518. results.push(item);
  12519. }
  12520. if (!directDescendantsOnly) {
  12521. item._getDescendants(results, false, predicate);
  12522. }
  12523. }
  12524. };
  12525. /**
  12526. * Will return all nodes that have this node as ascendant.
  12527. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  12528. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  12529. * @return {BABYLON.Node[]} all children nodes of all types.
  12530. */
  12531. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12532. var results = new Array();
  12533. this._getDescendants(results, directDescendantsOnly, predicate);
  12534. return results;
  12535. };
  12536. /**
  12537. * Get all child-meshes of this node.
  12538. */
  12539. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  12540. var results = [];
  12541. this._getDescendants(results, directDescendantsOnly, function (node) {
  12542. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12543. });
  12544. return results;
  12545. };
  12546. /**
  12547. * Get all child-transformNodes of this node.
  12548. */
  12549. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  12550. var results = [];
  12551. this._getDescendants(results, directDescendantsOnly, function (node) {
  12552. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  12553. });
  12554. return results;
  12555. };
  12556. /**
  12557. * Get all direct children of this node.
  12558. */
  12559. Node.prototype.getChildren = function (predicate) {
  12560. return this.getDescendants(true, predicate);
  12561. };
  12562. Node.prototype._setReady = function (state) {
  12563. if (state === this._isReady) {
  12564. return;
  12565. }
  12566. if (!state) {
  12567. this._isReady = false;
  12568. return;
  12569. }
  12570. this._isReady = true;
  12571. if (this.onReady) {
  12572. this.onReady(this);
  12573. }
  12574. };
  12575. Node.prototype.getAnimationByName = function (name) {
  12576. for (var i = 0; i < this.animations.length; i++) {
  12577. var animation = this.animations[i];
  12578. if (animation.name === name) {
  12579. return animation;
  12580. }
  12581. }
  12582. return null;
  12583. };
  12584. Node.prototype.createAnimationRange = function (name, from, to) {
  12585. // check name not already in use
  12586. if (!this._ranges[name]) {
  12587. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12588. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12589. if (this.animations[i]) {
  12590. this.animations[i].createRange(name, from, to);
  12591. }
  12592. }
  12593. }
  12594. };
  12595. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12596. if (deleteFrames === void 0) { deleteFrames = true; }
  12597. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12598. if (this.animations[i]) {
  12599. this.animations[i].deleteRange(name, deleteFrames);
  12600. }
  12601. }
  12602. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12603. };
  12604. Node.prototype.getAnimationRange = function (name) {
  12605. return this._ranges[name];
  12606. };
  12607. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12608. var range = this.getAnimationRange(name);
  12609. if (!range) {
  12610. return;
  12611. }
  12612. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12613. };
  12614. Node.prototype.serializeAnimationRanges = function () {
  12615. var serializationRanges = [];
  12616. for (var name in this._ranges) {
  12617. var localRange = this._ranges[name];
  12618. if (!localRange) {
  12619. continue;
  12620. }
  12621. var range = {};
  12622. range.name = name;
  12623. range.from = localRange.from;
  12624. range.to = localRange.to;
  12625. serializationRanges.push(range);
  12626. }
  12627. return serializationRanges;
  12628. };
  12629. Node.prototype.dispose = function () {
  12630. this.parent = null;
  12631. // Callback
  12632. this.onDisposeObservable.notifyObservers(this);
  12633. this.onDisposeObservable.clear();
  12634. // Behaviors
  12635. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12636. var behavior = _a[_i];
  12637. behavior.detach();
  12638. }
  12639. this._behaviors = [];
  12640. };
  12641. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12642. if (parsedNode.ranges) {
  12643. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12644. var data = parsedNode.ranges[index];
  12645. node.createAnimationRange(data.name, data.from, data.to);
  12646. }
  12647. }
  12648. };
  12649. __decorate([
  12650. BABYLON.serialize()
  12651. ], Node.prototype, "name", void 0);
  12652. __decorate([
  12653. BABYLON.serialize()
  12654. ], Node.prototype, "id", void 0);
  12655. __decorate([
  12656. BABYLON.serialize()
  12657. ], Node.prototype, "uniqueId", void 0);
  12658. __decorate([
  12659. BABYLON.serialize()
  12660. ], Node.prototype, "state", void 0);
  12661. __decorate([
  12662. BABYLON.serialize()
  12663. ], Node.prototype, "metadata", void 0);
  12664. return Node;
  12665. }());
  12666. BABYLON.Node = Node;
  12667. })(BABYLON || (BABYLON = {}));
  12668. //# sourceMappingURL=babylon.node.js.map
  12669. var BABYLON;
  12670. (function (BABYLON) {
  12671. var BoundingSphere = /** @class */ (function () {
  12672. function BoundingSphere(minimum, maximum) {
  12673. this.minimum = minimum;
  12674. this.maximum = maximum;
  12675. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12676. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12677. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12678. this.radius = distance * 0.5;
  12679. this.centerWorld = BABYLON.Vector3.Zero();
  12680. this._update(BABYLON.Matrix.Identity());
  12681. }
  12682. // Methods
  12683. BoundingSphere.prototype._update = function (world) {
  12684. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12685. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12686. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12687. };
  12688. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12689. for (var i = 0; i < 6; i++) {
  12690. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12691. return false;
  12692. }
  12693. return true;
  12694. };
  12695. BoundingSphere.prototype.intersectsPoint = function (point) {
  12696. var x = this.centerWorld.x - point.x;
  12697. var y = this.centerWorld.y - point.y;
  12698. var z = this.centerWorld.z - point.z;
  12699. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12700. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12701. return false;
  12702. return true;
  12703. };
  12704. // Statics
  12705. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12706. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12707. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12708. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12709. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12710. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12711. return false;
  12712. return true;
  12713. };
  12714. return BoundingSphere;
  12715. }());
  12716. BABYLON.BoundingSphere = BoundingSphere;
  12717. })(BABYLON || (BABYLON = {}));
  12718. //# sourceMappingURL=babylon.boundingSphere.js.map
  12719. var BABYLON;
  12720. (function (BABYLON) {
  12721. var BoundingBox = /** @class */ (function () {
  12722. function BoundingBox(minimum, maximum) {
  12723. this.minimum = minimum;
  12724. this.maximum = maximum;
  12725. this.vectors = new Array();
  12726. this.vectorsWorld = new Array();
  12727. // Bounding vectors
  12728. this.vectors.push(this.minimum.clone());
  12729. this.vectors.push(this.maximum.clone());
  12730. this.vectors.push(this.minimum.clone());
  12731. this.vectors[2].x = this.maximum.x;
  12732. this.vectors.push(this.minimum.clone());
  12733. this.vectors[3].y = this.maximum.y;
  12734. this.vectors.push(this.minimum.clone());
  12735. this.vectors[4].z = this.maximum.z;
  12736. this.vectors.push(this.maximum.clone());
  12737. this.vectors[5].z = this.minimum.z;
  12738. this.vectors.push(this.maximum.clone());
  12739. this.vectors[6].x = this.minimum.x;
  12740. this.vectors.push(this.maximum.clone());
  12741. this.vectors[7].y = this.minimum.y;
  12742. // OBB
  12743. this.center = this.maximum.add(this.minimum).scale(0.5);
  12744. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12745. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12746. // World
  12747. for (var index = 0; index < this.vectors.length; index++) {
  12748. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12749. }
  12750. this.minimumWorld = BABYLON.Vector3.Zero();
  12751. this.maximumWorld = BABYLON.Vector3.Zero();
  12752. this.centerWorld = BABYLON.Vector3.Zero();
  12753. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12754. this._update(BABYLON.Matrix.Identity());
  12755. }
  12756. // Methods
  12757. BoundingBox.prototype.getWorldMatrix = function () {
  12758. return this._worldMatrix;
  12759. };
  12760. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12761. this._worldMatrix.copyFrom(matrix);
  12762. return this;
  12763. };
  12764. BoundingBox.prototype._update = function (world) {
  12765. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12766. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12767. for (var index = 0; index < this.vectors.length; index++) {
  12768. var v = this.vectorsWorld[index];
  12769. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12770. if (v.x < this.minimumWorld.x)
  12771. this.minimumWorld.x = v.x;
  12772. if (v.y < this.minimumWorld.y)
  12773. this.minimumWorld.y = v.y;
  12774. if (v.z < this.minimumWorld.z)
  12775. this.minimumWorld.z = v.z;
  12776. if (v.x > this.maximumWorld.x)
  12777. this.maximumWorld.x = v.x;
  12778. if (v.y > this.maximumWorld.y)
  12779. this.maximumWorld.y = v.y;
  12780. if (v.z > this.maximumWorld.z)
  12781. this.maximumWorld.z = v.z;
  12782. }
  12783. // Extend
  12784. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12785. this.extendSizeWorld.scaleInPlace(0.5);
  12786. // OBB
  12787. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12788. this.centerWorld.scaleInPlace(0.5);
  12789. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12790. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12791. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12792. this._worldMatrix = world;
  12793. };
  12794. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12795. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12796. };
  12797. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12798. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12799. };
  12800. BoundingBox.prototype.intersectsPoint = function (point) {
  12801. var delta = -BABYLON.Epsilon;
  12802. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12803. return false;
  12804. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12805. return false;
  12806. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12807. return false;
  12808. return true;
  12809. };
  12810. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12811. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12812. };
  12813. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12814. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12815. return false;
  12816. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12817. return false;
  12818. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12819. return false;
  12820. return true;
  12821. };
  12822. // Statics
  12823. BoundingBox.Intersects = function (box0, box1) {
  12824. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12825. return false;
  12826. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12827. return false;
  12828. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12829. return false;
  12830. return true;
  12831. };
  12832. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12833. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12834. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12835. return (num <= (sphereRadius * sphereRadius));
  12836. };
  12837. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12838. for (var p = 0; p < 6; p++) {
  12839. for (var i = 0; i < 8; i++) {
  12840. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12841. return false;
  12842. }
  12843. }
  12844. }
  12845. return true;
  12846. };
  12847. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12848. for (var p = 0; p < 6; p++) {
  12849. var inCount = 8;
  12850. for (var i = 0; i < 8; i++) {
  12851. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12852. --inCount;
  12853. }
  12854. else {
  12855. break;
  12856. }
  12857. }
  12858. if (inCount === 0)
  12859. return false;
  12860. }
  12861. return true;
  12862. };
  12863. return BoundingBox;
  12864. }());
  12865. BABYLON.BoundingBox = BoundingBox;
  12866. })(BABYLON || (BABYLON = {}));
  12867. //# sourceMappingURL=babylon.boundingBox.js.map
  12868. var BABYLON;
  12869. (function (BABYLON) {
  12870. var computeBoxExtents = function (axis, box) {
  12871. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12872. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12873. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12874. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12875. var r = r0 + r1 + r2;
  12876. return {
  12877. min: p - r,
  12878. max: p + r
  12879. };
  12880. };
  12881. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12882. var axisOverlap = function (axis, box0, box1) {
  12883. var result0 = computeBoxExtents(axis, box0);
  12884. var result1 = computeBoxExtents(axis, box1);
  12885. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12886. };
  12887. var BoundingInfo = /** @class */ (function () {
  12888. function BoundingInfo(minimum, maximum) {
  12889. this.minimum = minimum;
  12890. this.maximum = maximum;
  12891. this._isLocked = false;
  12892. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12893. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12894. }
  12895. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12896. get: function () {
  12897. return this._isLocked;
  12898. },
  12899. set: function (value) {
  12900. this._isLocked = value;
  12901. },
  12902. enumerable: true,
  12903. configurable: true
  12904. });
  12905. // Methods
  12906. BoundingInfo.prototype.update = function (world) {
  12907. if (this._isLocked) {
  12908. return;
  12909. }
  12910. this.boundingBox._update(world);
  12911. this.boundingSphere._update(world);
  12912. };
  12913. /**
  12914. * Recreate the bounding info to be centered around a specific point given a specific extend.
  12915. * @param center New center of the bounding info
  12916. * @param extend New extend of the bounding info
  12917. */
  12918. BoundingInfo.prototype.centerOn = function (center, extend) {
  12919. this.minimum = center.subtract(extend);
  12920. this.maximum = center.add(extend);
  12921. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  12922. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  12923. return this;
  12924. };
  12925. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12926. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12927. return false;
  12928. return this.boundingBox.isInFrustum(frustumPlanes);
  12929. };
  12930. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12931. /**
  12932. * Gets the world distance between the min and max points of the bounding box
  12933. */
  12934. get: function () {
  12935. var boundingBox = this.boundingBox;
  12936. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12937. return size.length();
  12938. },
  12939. enumerable: true,
  12940. configurable: true
  12941. });
  12942. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12943. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12944. };
  12945. BoundingInfo.prototype._checkCollision = function (collider) {
  12946. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12947. };
  12948. BoundingInfo.prototype.intersectsPoint = function (point) {
  12949. if (!this.boundingSphere.centerWorld) {
  12950. return false;
  12951. }
  12952. if (!this.boundingSphere.intersectsPoint(point)) {
  12953. return false;
  12954. }
  12955. if (!this.boundingBox.intersectsPoint(point)) {
  12956. return false;
  12957. }
  12958. return true;
  12959. };
  12960. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12961. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12962. return false;
  12963. }
  12964. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12965. return false;
  12966. }
  12967. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12968. return false;
  12969. }
  12970. if (!precise) {
  12971. return true;
  12972. }
  12973. var box0 = this.boundingBox;
  12974. var box1 = boundingInfo.boundingBox;
  12975. if (!axisOverlap(box0.directions[0], box0, box1))
  12976. return false;
  12977. if (!axisOverlap(box0.directions[1], box0, box1))
  12978. return false;
  12979. if (!axisOverlap(box0.directions[2], box0, box1))
  12980. return false;
  12981. if (!axisOverlap(box1.directions[0], box0, box1))
  12982. return false;
  12983. if (!axisOverlap(box1.directions[1], box0, box1))
  12984. return false;
  12985. if (!axisOverlap(box1.directions[2], box0, box1))
  12986. return false;
  12987. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12988. return false;
  12989. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12990. return false;
  12991. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12992. return false;
  12993. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12994. return false;
  12995. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12996. return false;
  12997. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12998. return false;
  12999. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  13000. return false;
  13001. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  13002. return false;
  13003. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  13004. return false;
  13005. return true;
  13006. };
  13007. return BoundingInfo;
  13008. }());
  13009. BABYLON.BoundingInfo = BoundingInfo;
  13010. })(BABYLON || (BABYLON = {}));
  13011. //# sourceMappingURL=babylon.boundingInfo.js.map
  13012. var BABYLON;
  13013. (function (BABYLON) {
  13014. var TransformNode = /** @class */ (function (_super) {
  13015. __extends(TransformNode, _super);
  13016. function TransformNode(name, scene, isPure) {
  13017. if (scene === void 0) { scene = null; }
  13018. if (isPure === void 0) { isPure = true; }
  13019. var _this = _super.call(this, name, scene) || this;
  13020. // Properties
  13021. _this._rotation = BABYLON.Vector3.Zero();
  13022. _this._scaling = BABYLON.Vector3.One();
  13023. _this._isDirty = false;
  13024. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  13025. _this.scalingDeterminant = 1;
  13026. _this.infiniteDistance = false;
  13027. _this.position = BABYLON.Vector3.Zero();
  13028. _this._localWorld = BABYLON.Matrix.Zero();
  13029. _this._worldMatrix = BABYLON.Matrix.Zero();
  13030. _this._absolutePosition = BABYLON.Vector3.Zero();
  13031. _this._pivotMatrix = BABYLON.Matrix.Identity();
  13032. _this._postMultiplyPivotMatrix = false;
  13033. _this._isWorldMatrixFrozen = false;
  13034. /**
  13035. * An event triggered after the world matrix is updated
  13036. * @type {BABYLON.Observable}
  13037. */
  13038. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  13039. _this._nonUniformScaling = false;
  13040. if (isPure) {
  13041. _this.getScene().addTransformNode(_this);
  13042. }
  13043. return _this;
  13044. }
  13045. Object.defineProperty(TransformNode.prototype, "rotation", {
  13046. /**
  13047. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13048. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13049. * Default : (0.0, 0.0, 0.0)
  13050. */
  13051. get: function () {
  13052. return this._rotation;
  13053. },
  13054. set: function (newRotation) {
  13055. this._rotation = newRotation;
  13056. },
  13057. enumerable: true,
  13058. configurable: true
  13059. });
  13060. Object.defineProperty(TransformNode.prototype, "scaling", {
  13061. /**
  13062. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13063. * Default : (1.0, 1.0, 1.0)
  13064. */
  13065. get: function () {
  13066. return this._scaling;
  13067. },
  13068. /**
  13069. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13070. * Default : (1.0, 1.0, 1.0)
  13071. */
  13072. set: function (newScaling) {
  13073. this._scaling = newScaling;
  13074. },
  13075. enumerable: true,
  13076. configurable: true
  13077. });
  13078. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  13079. /**
  13080. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13081. * It's null by default.
  13082. * 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)
  13083. */
  13084. get: function () {
  13085. return this._rotationQuaternion;
  13086. },
  13087. set: function (quaternion) {
  13088. this._rotationQuaternion = quaternion;
  13089. //reset the rotation vector.
  13090. if (quaternion && this.rotation.length()) {
  13091. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13092. }
  13093. },
  13094. enumerable: true,
  13095. configurable: true
  13096. });
  13097. /**
  13098. * Returns the latest update of the World matrix
  13099. * Returns a Matrix.
  13100. */
  13101. TransformNode.prototype.getWorldMatrix = function () {
  13102. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13103. this.computeWorldMatrix();
  13104. }
  13105. return this._worldMatrix;
  13106. };
  13107. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  13108. /**
  13109. * Returns directly the latest state of the mesh World matrix.
  13110. * A Matrix is returned.
  13111. */
  13112. get: function () {
  13113. return this._worldMatrix;
  13114. },
  13115. enumerable: true,
  13116. configurable: true
  13117. });
  13118. /**
  13119. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13120. * Returns the AbstractMesh.
  13121. */
  13122. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  13123. this._poseMatrix.copyFrom(matrix);
  13124. return this;
  13125. };
  13126. /**
  13127. * Returns the mesh Pose matrix.
  13128. * Returned object : Matrix
  13129. */
  13130. TransformNode.prototype.getPoseMatrix = function () {
  13131. return this._poseMatrix;
  13132. };
  13133. TransformNode.prototype._isSynchronized = function () {
  13134. if (this._isDirty) {
  13135. return false;
  13136. }
  13137. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  13138. return false;
  13139. if (this._cache.pivotMatrixUpdated) {
  13140. return false;
  13141. }
  13142. if (this.infiniteDistance) {
  13143. return false;
  13144. }
  13145. if (!this._cache.position.equals(this.position))
  13146. return false;
  13147. if (this.rotationQuaternion) {
  13148. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13149. return false;
  13150. }
  13151. if (!this._cache.rotation.equals(this.rotation))
  13152. return false;
  13153. if (!this._cache.scaling.equals(this.scaling))
  13154. return false;
  13155. return true;
  13156. };
  13157. TransformNode.prototype._initCache = function () {
  13158. _super.prototype._initCache.call(this);
  13159. this._cache.localMatrixUpdated = false;
  13160. this._cache.position = BABYLON.Vector3.Zero();
  13161. this._cache.scaling = BABYLON.Vector3.Zero();
  13162. this._cache.rotation = BABYLON.Vector3.Zero();
  13163. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13164. this._cache.billboardMode = -1;
  13165. };
  13166. TransformNode.prototype.markAsDirty = function (property) {
  13167. if (property === "rotation") {
  13168. this.rotationQuaternion = null;
  13169. }
  13170. this._currentRenderId = Number.MAX_VALUE;
  13171. this._isDirty = true;
  13172. return this;
  13173. };
  13174. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  13175. /**
  13176. * Returns the current mesh absolute position.
  13177. * Retuns a Vector3.
  13178. */
  13179. get: function () {
  13180. return this._absolutePosition;
  13181. },
  13182. enumerable: true,
  13183. configurable: true
  13184. });
  13185. /**
  13186. * Sets a new pivot matrix to the mesh.
  13187. * Returns the AbstractMesh.
  13188. */
  13189. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13190. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13191. this._pivotMatrix = matrix.clone();
  13192. this._cache.pivotMatrixUpdated = true;
  13193. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13194. if (this._postMultiplyPivotMatrix) {
  13195. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13196. }
  13197. return this;
  13198. };
  13199. /**
  13200. * Returns the mesh pivot matrix.
  13201. * Default : Identity.
  13202. * A Matrix is returned.
  13203. */
  13204. TransformNode.prototype.getPivotMatrix = function () {
  13205. return this._pivotMatrix;
  13206. };
  13207. /**
  13208. * Prevents the World matrix to be computed any longer.
  13209. * Returns the AbstractMesh.
  13210. */
  13211. TransformNode.prototype.freezeWorldMatrix = function () {
  13212. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13213. this.computeWorldMatrix(true);
  13214. this._isWorldMatrixFrozen = true;
  13215. return this;
  13216. };
  13217. /**
  13218. * Allows back the World matrix computation.
  13219. * Returns the AbstractMesh.
  13220. */
  13221. TransformNode.prototype.unfreezeWorldMatrix = function () {
  13222. this._isWorldMatrixFrozen = false;
  13223. this.computeWorldMatrix(true);
  13224. return this;
  13225. };
  13226. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  13227. /**
  13228. * True if the World matrix has been frozen.
  13229. * Returns a boolean.
  13230. */
  13231. get: function () {
  13232. return this._isWorldMatrixFrozen;
  13233. },
  13234. enumerable: true,
  13235. configurable: true
  13236. });
  13237. /**
  13238. * Retuns the mesh absolute position in the World.
  13239. * Returns a Vector3.
  13240. */
  13241. TransformNode.prototype.getAbsolutePosition = function () {
  13242. this.computeWorldMatrix();
  13243. return this._absolutePosition;
  13244. };
  13245. /**
  13246. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13247. * Returns the AbstractMesh.
  13248. */
  13249. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  13250. if (!absolutePosition) {
  13251. return this;
  13252. }
  13253. var absolutePositionX;
  13254. var absolutePositionY;
  13255. var absolutePositionZ;
  13256. if (absolutePosition.x === undefined) {
  13257. if (arguments.length < 3) {
  13258. return this;
  13259. }
  13260. absolutePositionX = arguments[0];
  13261. absolutePositionY = arguments[1];
  13262. absolutePositionZ = arguments[2];
  13263. }
  13264. else {
  13265. absolutePositionX = absolutePosition.x;
  13266. absolutePositionY = absolutePosition.y;
  13267. absolutePositionZ = absolutePosition.z;
  13268. }
  13269. if (this.parent) {
  13270. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13271. invertParentWorldMatrix.invert();
  13272. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13273. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13274. }
  13275. else {
  13276. this.position.x = absolutePositionX;
  13277. this.position.y = absolutePositionY;
  13278. this.position.z = absolutePositionZ;
  13279. }
  13280. return this;
  13281. };
  13282. /**
  13283. * Sets the mesh position in its local space.
  13284. * Returns the AbstractMesh.
  13285. */
  13286. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  13287. this.computeWorldMatrix();
  13288. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13289. return this;
  13290. };
  13291. /**
  13292. * Returns the mesh position in the local space from the current World matrix values.
  13293. * Returns a new Vector3.
  13294. */
  13295. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  13296. this.computeWorldMatrix();
  13297. var invLocalWorldMatrix = this._localWorld.clone();
  13298. invLocalWorldMatrix.invert();
  13299. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13300. };
  13301. /**
  13302. * Translates the mesh along the passed Vector3 in its local space.
  13303. * Returns the AbstractMesh.
  13304. */
  13305. TransformNode.prototype.locallyTranslate = function (vector3) {
  13306. this.computeWorldMatrix(true);
  13307. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13308. return this;
  13309. };
  13310. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13311. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13312. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13313. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13314. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13315. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13316. /// <returns>Mesh oriented towards targetMesh</returns>
  13317. if (yawCor === void 0) { yawCor = 0; }
  13318. if (pitchCor === void 0) { pitchCor = 0; }
  13319. if (rollCor === void 0) { rollCor = 0; }
  13320. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13321. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  13322. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13323. targetPoint.subtractToRef(pos, dv);
  13324. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13325. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13326. var pitch = Math.atan2(dv.y, len);
  13327. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13328. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13329. return this;
  13330. };
  13331. /**
  13332. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13333. * This Vector3 is expressed in the World space.
  13334. */
  13335. TransformNode.prototype.getDirection = function (localAxis) {
  13336. var result = BABYLON.Vector3.Zero();
  13337. this.getDirectionToRef(localAxis, result);
  13338. return result;
  13339. };
  13340. /**
  13341. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13342. * localAxis is expressed in the mesh local space.
  13343. * result is computed in the Wordl space from the mesh World matrix.
  13344. * Returns the AbstractMesh.
  13345. */
  13346. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  13347. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13348. return this;
  13349. };
  13350. TransformNode.prototype.setPivotPoint = function (point, space) {
  13351. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13352. if (this.getScene().getRenderId() == 0) {
  13353. this.computeWorldMatrix(true);
  13354. }
  13355. var wm = this.getWorldMatrix();
  13356. if (space == BABYLON.Space.WORLD) {
  13357. var tmat = BABYLON.Tmp.Matrix[0];
  13358. wm.invertToRef(tmat);
  13359. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13360. }
  13361. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13362. this._pivotMatrix.m[12] = -point.x;
  13363. this._pivotMatrix.m[13] = -point.y;
  13364. this._pivotMatrix.m[14] = -point.z;
  13365. this._cache.pivotMatrixUpdated = true;
  13366. return this;
  13367. };
  13368. /**
  13369. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13370. */
  13371. TransformNode.prototype.getPivotPoint = function () {
  13372. var point = BABYLON.Vector3.Zero();
  13373. this.getPivotPointToRef(point);
  13374. return point;
  13375. };
  13376. /**
  13377. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13378. * Returns the AbstractMesh.
  13379. */
  13380. TransformNode.prototype.getPivotPointToRef = function (result) {
  13381. result.x = -this._pivotMatrix.m[12];
  13382. result.y = -this._pivotMatrix.m[13];
  13383. result.z = -this._pivotMatrix.m[14];
  13384. return this;
  13385. };
  13386. /**
  13387. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13388. */
  13389. TransformNode.prototype.getAbsolutePivotPoint = function () {
  13390. var point = BABYLON.Vector3.Zero();
  13391. this.getAbsolutePivotPointToRef(point);
  13392. return point;
  13393. };
  13394. /**
  13395. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13396. * Returns the AbstractMesh.
  13397. */
  13398. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  13399. result.x = this._pivotMatrix.m[12];
  13400. result.y = this._pivotMatrix.m[13];
  13401. result.z = this._pivotMatrix.m[14];
  13402. this.getPivotPointToRef(result);
  13403. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13404. return this;
  13405. };
  13406. /**
  13407. * Defines the passed node as the parent of the current node.
  13408. * Returns the TransformNode.
  13409. */
  13410. TransformNode.prototype.setParent = function (node) {
  13411. if (node == null) {
  13412. var rotation = BABYLON.Tmp.Quaternion[0];
  13413. var position = BABYLON.Tmp.Vector3[0];
  13414. var scale = BABYLON.Tmp.Vector3[1];
  13415. if (this.parent && this.parent.computeWorldMatrix) {
  13416. this.parent.computeWorldMatrix(true);
  13417. }
  13418. this.computeWorldMatrix(true);
  13419. this.getWorldMatrix().decompose(scale, rotation, position);
  13420. if (this.rotationQuaternion) {
  13421. this.rotationQuaternion.copyFrom(rotation);
  13422. }
  13423. else {
  13424. rotation.toEulerAnglesToRef(this.rotation);
  13425. }
  13426. this.position.x = position.x;
  13427. this.position.y = position.y;
  13428. this.position.z = position.z;
  13429. }
  13430. else {
  13431. var rotation = BABYLON.Tmp.Quaternion[0];
  13432. var position = BABYLON.Tmp.Vector3[0];
  13433. var scale = BABYLON.Tmp.Vector3[1];
  13434. var m0 = BABYLON.Tmp.Matrix[0];
  13435. var m1 = BABYLON.Tmp.Matrix[1];
  13436. var invParentMatrix = BABYLON.Tmp.Matrix[2];
  13437. node.computeWorldMatrix(true);
  13438. node.getWorldMatrix().decompose(scale, rotation, position);
  13439. rotation.toRotationMatrix(m0);
  13440. m1.setTranslation(position);
  13441. m1.multiplyToRef(m0, m0);
  13442. m0.invertToRef(invParentMatrix);
  13443. this.getWorldMatrix().multiplyToRef(invParentMatrix, m0);
  13444. m0.decompose(scale, rotation, position);
  13445. if (this.rotationQuaternion) {
  13446. this.rotationQuaternion.copyFrom(rotation);
  13447. }
  13448. else {
  13449. rotation.toEulerAnglesToRef(this.rotation);
  13450. }
  13451. node.getWorldMatrix().invertToRef(invParentMatrix);
  13452. this.getWorldMatrix().multiplyToRef(invParentMatrix, m0);
  13453. m0.decompose(scale, rotation, position);
  13454. this.position.x = position.x;
  13455. this.position.y = position.y;
  13456. this.position.z = position.z;
  13457. }
  13458. this.parent = node;
  13459. return this;
  13460. };
  13461. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  13462. get: function () {
  13463. return this._nonUniformScaling;
  13464. },
  13465. enumerable: true,
  13466. configurable: true
  13467. });
  13468. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  13469. if (this._nonUniformScaling === value) {
  13470. return false;
  13471. }
  13472. this._nonUniformScaling = true;
  13473. return true;
  13474. };
  13475. /**
  13476. * Attach the current TransformNode to another TransformNode associated with a bone
  13477. * @param bone Bone affecting the TransformNode
  13478. * @param affectedTransformNode TransformNode associated with the bone
  13479. */
  13480. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  13481. this._transformToBoneReferal = affectedTransformNode;
  13482. this.parent = bone;
  13483. if (bone.getWorldMatrix().determinant() < 0) {
  13484. this.scalingDeterminant *= -1;
  13485. }
  13486. return this;
  13487. };
  13488. TransformNode.prototype.detachFromBone = function () {
  13489. if (!this.parent) {
  13490. return this;
  13491. }
  13492. if (this.parent.getWorldMatrix().determinant() < 0) {
  13493. this.scalingDeterminant *= -1;
  13494. }
  13495. this._transformToBoneReferal = null;
  13496. this.parent = null;
  13497. return this;
  13498. };
  13499. /**
  13500. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13501. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13502. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13503. * The passed axis is also normalized.
  13504. * Returns the AbstractMesh.
  13505. */
  13506. TransformNode.prototype.rotate = function (axis, amount, space) {
  13507. axis.normalize();
  13508. if (!this.rotationQuaternion) {
  13509. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13510. this.rotation = BABYLON.Vector3.Zero();
  13511. }
  13512. var rotationQuaternion;
  13513. if (!space || space === BABYLON.Space.LOCAL) {
  13514. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13515. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13516. }
  13517. else {
  13518. if (this.parent) {
  13519. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13520. invertParentWorldMatrix.invert();
  13521. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13522. }
  13523. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13524. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13525. }
  13526. return this;
  13527. };
  13528. /**
  13529. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13530. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13531. * The passed axis is also normalized.
  13532. * Returns the AbstractMesh.
  13533. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13534. */
  13535. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  13536. axis.normalize();
  13537. if (!this.rotationQuaternion) {
  13538. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13539. this.rotation.copyFromFloats(0, 0, 0);
  13540. }
  13541. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13542. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13543. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13544. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13545. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13546. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13547. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13548. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13549. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13550. return this;
  13551. };
  13552. /**
  13553. * Translates the mesh along the axis vector for the passed distance in the given space.
  13554. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13555. * Returns the AbstractMesh.
  13556. */
  13557. TransformNode.prototype.translate = function (axis, distance, space) {
  13558. var displacementVector = axis.scale(distance);
  13559. if (!space || space === BABYLON.Space.LOCAL) {
  13560. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13561. this.setPositionWithLocalVector(tempV3);
  13562. }
  13563. else {
  13564. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13565. }
  13566. return this;
  13567. };
  13568. /**
  13569. * Adds a rotation step to the mesh current rotation.
  13570. * x, y, z are Euler angles expressed in radians.
  13571. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13572. * This means this rotation is made in the mesh local space only.
  13573. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13574. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13575. * ```javascript
  13576. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13577. * ```
  13578. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13579. * 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.
  13580. * Returns the AbstractMesh.
  13581. */
  13582. TransformNode.prototype.addRotation = function (x, y, z) {
  13583. var rotationQuaternion;
  13584. if (this.rotationQuaternion) {
  13585. rotationQuaternion = this.rotationQuaternion;
  13586. }
  13587. else {
  13588. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13589. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13590. }
  13591. var accumulation = BABYLON.Tmp.Quaternion[0];
  13592. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13593. rotationQuaternion.multiplyInPlace(accumulation);
  13594. if (!this.rotationQuaternion) {
  13595. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13596. }
  13597. return this;
  13598. };
  13599. /**
  13600. * Computes the mesh World matrix and returns it.
  13601. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13602. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13603. * If the parameter `force`is set to `true`, the actual computation is done.
  13604. * Returns the mesh World Matrix.
  13605. */
  13606. TransformNode.prototype.computeWorldMatrix = function (force) {
  13607. if (this._isWorldMatrixFrozen) {
  13608. return this._worldMatrix;
  13609. }
  13610. if (!force && this.isSynchronized(true)) {
  13611. return this._worldMatrix;
  13612. }
  13613. this._cache.position.copyFrom(this.position);
  13614. this._cache.scaling.copyFrom(this.scaling);
  13615. this._cache.pivotMatrixUpdated = false;
  13616. this._cache.billboardMode = this.billboardMode;
  13617. this._currentRenderId = this.getScene().getRenderId();
  13618. this._isDirty = false;
  13619. // Scaling
  13620. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13621. // Rotation
  13622. //rotate, if quaternion is set and rotation was used
  13623. if (this.rotationQuaternion) {
  13624. var len = this.rotation.length();
  13625. if (len) {
  13626. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13627. this.rotation.copyFromFloats(0, 0, 0);
  13628. }
  13629. }
  13630. if (this.rotationQuaternion) {
  13631. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13632. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13633. }
  13634. else {
  13635. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13636. this._cache.rotation.copyFrom(this.rotation);
  13637. }
  13638. // Translation
  13639. var camera = this.getScene().activeCamera;
  13640. if (this.infiniteDistance && !this.parent && camera) {
  13641. var cameraWorldMatrix = camera.getWorldMatrix();
  13642. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13643. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13644. }
  13645. else {
  13646. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13647. }
  13648. // Composing transformations
  13649. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13650. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13651. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13652. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  13653. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  13654. // Need to decompose each rotation here
  13655. var currentPosition = BABYLON.Tmp.Vector3[3];
  13656. if (this.parent && this.parent.getWorldMatrix) {
  13657. if (this._transformToBoneReferal) {
  13658. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13659. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13660. }
  13661. else {
  13662. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13663. }
  13664. }
  13665. else {
  13666. currentPosition.copyFrom(this.position);
  13667. }
  13668. currentPosition.subtractInPlace(camera.globalPosition);
  13669. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13670. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  13671. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13672. }
  13673. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  13674. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13675. }
  13676. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  13677. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13678. }
  13679. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13680. }
  13681. else {
  13682. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  13683. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13684. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13685. }
  13686. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13687. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13688. }
  13689. // Local world
  13690. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13691. // Parent
  13692. if (this.parent && this.parent.getWorldMatrix) {
  13693. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  13694. if (this._transformToBoneReferal) {
  13695. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13696. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13697. }
  13698. else {
  13699. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13700. }
  13701. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13702. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13703. this._worldMatrix.copyFrom(this._localWorld);
  13704. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13705. }
  13706. else {
  13707. if (this._transformToBoneReferal) {
  13708. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13709. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13710. }
  13711. else {
  13712. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13713. }
  13714. }
  13715. this._markSyncedWithParent();
  13716. }
  13717. else {
  13718. this._worldMatrix.copyFrom(this._localWorld);
  13719. }
  13720. // Post multiply inverse of pivotMatrix
  13721. if (this._postMultiplyPivotMatrix) {
  13722. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  13723. }
  13724. // Normal matrix
  13725. if (this.scaling.isNonUniform) {
  13726. this._updateNonUniformScalingState(true);
  13727. }
  13728. else if (this.parent && this.parent._nonUniformScaling) {
  13729. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  13730. }
  13731. else {
  13732. this._updateNonUniformScalingState(false);
  13733. }
  13734. this._afterComputeWorldMatrix();
  13735. // Absolute position
  13736. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13737. // Callbacks
  13738. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13739. if (!this._poseMatrix) {
  13740. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13741. }
  13742. return this._worldMatrix;
  13743. };
  13744. TransformNode.prototype._afterComputeWorldMatrix = function () {
  13745. };
  13746. /**
  13747. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13748. * @param func: callback function to add
  13749. *
  13750. * Returns the TransformNode.
  13751. */
  13752. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13753. this.onAfterWorldMatrixUpdateObservable.add(func);
  13754. return this;
  13755. };
  13756. /**
  13757. * Removes a registered callback function.
  13758. * Returns the TransformNode.
  13759. */
  13760. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13761. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13762. return this;
  13763. };
  13764. TransformNode.prototype.clone = function (name, newParent) {
  13765. var _this = this;
  13766. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  13767. result.name = name;
  13768. result.id = name;
  13769. if (newParent) {
  13770. result.parent = newParent;
  13771. }
  13772. return result;
  13773. };
  13774. TransformNode.prototype.serialize = function (serializationObject) {
  13775. if (serializationObject === void 0) { serializationObject = null; }
  13776. if (!serializationObject) {
  13777. serializationObject = {};
  13778. }
  13779. serializationObject.name = this.name;
  13780. serializationObject.id = this.id;
  13781. serializationObject.type = this.getClassName();
  13782. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  13783. serializationObject.tags = BABYLON.Tags.GetTags(this);
  13784. }
  13785. serializationObject.position = this.position.asArray();
  13786. if (this.rotationQuaternion) {
  13787. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  13788. }
  13789. else if (this.rotation) {
  13790. serializationObject.rotation = this.rotation.asArray();
  13791. }
  13792. serializationObject.scaling = this.scaling.asArray();
  13793. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  13794. serializationObject.isEnabled = this.isEnabled();
  13795. serializationObject.infiniteDistance = this.infiniteDistance;
  13796. serializationObject.billboardMode = this.billboardMode;
  13797. // Parent
  13798. if (this.parent) {
  13799. serializationObject.parentId = this.parent.id;
  13800. }
  13801. // Metadata
  13802. if (this.metadata) {
  13803. serializationObject.metadata = this.metadata;
  13804. }
  13805. return serializationObject;
  13806. };
  13807. // Statics
  13808. /**
  13809. * Returns a new TransformNode object parsed from the source provided.
  13810. * The parameter `parsedMesh` is the source.
  13811. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  13812. */
  13813. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  13814. var transformNode = new TransformNode(parsedTransformNode.name, scene);
  13815. transformNode.id = parsedTransformNode.id;
  13816. if (BABYLON.Tags) {
  13817. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  13818. }
  13819. transformNode.position = BABYLON.Vector3.FromArray(parsedTransformNode.position);
  13820. if (parsedTransformNode.metadata !== undefined) {
  13821. transformNode.metadata = parsedTransformNode.metadata;
  13822. }
  13823. if (parsedTransformNode.rotationQuaternion) {
  13824. transformNode.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedTransformNode.rotationQuaternion);
  13825. }
  13826. else if (parsedTransformNode.rotation) {
  13827. transformNode.rotation = BABYLON.Vector3.FromArray(parsedTransformNode.rotation);
  13828. }
  13829. transformNode.scaling = BABYLON.Vector3.FromArray(parsedTransformNode.scaling);
  13830. if (parsedTransformNode.localMatrix) {
  13831. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  13832. }
  13833. else if (parsedTransformNode.pivotMatrix) {
  13834. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  13835. }
  13836. transformNode.setEnabled(parsedTransformNode.isEnabled);
  13837. transformNode.infiniteDistance = parsedTransformNode.infiniteDistance;
  13838. transformNode.billboardMode = parsedTransformNode.billboardMode;
  13839. // Parent
  13840. if (parsedTransformNode.parentId) {
  13841. transformNode._waitingParentId = parsedTransformNode.parentId;
  13842. }
  13843. return transformNode;
  13844. };
  13845. /**
  13846. * Disposes the TransformNode.
  13847. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13848. * Returns nothing.
  13849. */
  13850. TransformNode.prototype.dispose = function (doNotRecurse) {
  13851. // Animations
  13852. this.getScene().stopAnimation(this);
  13853. // Remove from scene
  13854. this.getScene().removeTransformNode(this);
  13855. this._cache = null;
  13856. if (!doNotRecurse) {
  13857. // Children
  13858. var objects = this.getDescendants(true);
  13859. for (var index = 0; index < objects.length; index++) {
  13860. objects[index].dispose();
  13861. }
  13862. }
  13863. else {
  13864. var childMeshes = this.getChildMeshes(true);
  13865. for (index = 0; index < childMeshes.length; index++) {
  13866. var child = childMeshes[index];
  13867. child.parent = null;
  13868. child.computeWorldMatrix(true);
  13869. }
  13870. }
  13871. this.onAfterWorldMatrixUpdateObservable.clear();
  13872. _super.prototype.dispose.call(this);
  13873. };
  13874. // Statics
  13875. TransformNode.BILLBOARDMODE_NONE = 0;
  13876. TransformNode.BILLBOARDMODE_X = 1;
  13877. TransformNode.BILLBOARDMODE_Y = 2;
  13878. TransformNode.BILLBOARDMODE_Z = 4;
  13879. TransformNode.BILLBOARDMODE_ALL = 7;
  13880. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13881. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  13882. __decorate([
  13883. BABYLON.serializeAsVector3()
  13884. ], TransformNode.prototype, "_rotation", void 0);
  13885. __decorate([
  13886. BABYLON.serializeAsQuaternion()
  13887. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  13888. __decorate([
  13889. BABYLON.serializeAsVector3()
  13890. ], TransformNode.prototype, "_scaling", void 0);
  13891. __decorate([
  13892. BABYLON.serialize()
  13893. ], TransformNode.prototype, "billboardMode", void 0);
  13894. __decorate([
  13895. BABYLON.serialize()
  13896. ], TransformNode.prototype, "scalingDeterminant", void 0);
  13897. __decorate([
  13898. BABYLON.serialize()
  13899. ], TransformNode.prototype, "infiniteDistance", void 0);
  13900. __decorate([
  13901. BABYLON.serializeAsVector3()
  13902. ], TransformNode.prototype, "position", void 0);
  13903. return TransformNode;
  13904. }(BABYLON.Node));
  13905. BABYLON.TransformNode = TransformNode;
  13906. })(BABYLON || (BABYLON = {}));
  13907. //# sourceMappingURL=babylon.transformNode.js.map
  13908. var BABYLON;
  13909. (function (BABYLON) {
  13910. var AbstractMesh = /** @class */ (function (_super) {
  13911. __extends(AbstractMesh, _super);
  13912. // Constructor
  13913. function AbstractMesh(name, scene) {
  13914. if (scene === void 0) { scene = null; }
  13915. var _this = _super.call(this, name, scene, false) || this;
  13916. _this._facetNb = 0; // facet number
  13917. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  13918. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  13919. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  13920. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  13921. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  13922. _this._subDiv = {
  13923. max: 1,
  13924. X: 1,
  13925. Y: 1,
  13926. Z: 1
  13927. };
  13928. _this._facetDepthSort = false; // is the facet depth sort to be computed
  13929. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  13930. // Events
  13931. /**
  13932. * An event triggered when this mesh collides with another one
  13933. * @type {BABYLON.Observable}
  13934. */
  13935. _this.onCollideObservable = new BABYLON.Observable();
  13936. /**
  13937. * An event triggered when the collision's position changes
  13938. * @type {BABYLON.Observable}
  13939. */
  13940. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  13941. /**
  13942. * An event triggered when material is changed
  13943. * @type {BABYLON.Observable}
  13944. */
  13945. _this.onMaterialChangedObservable = new BABYLON.Observable();
  13946. // Properties
  13947. _this.definedFacingForward = true; // orientation for POV movement & rotation
  13948. /**
  13949. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  13950. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  13951. * or
  13952. * 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.
  13953. * for more info check WebGl documentations
  13954. */
  13955. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  13956. /**
  13957. * 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:
  13958. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  13959. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  13960. * 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.
  13961. */
  13962. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  13963. /**
  13964. * 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.
  13965. * The default value is -1 which means don't break the query and wait till the result.
  13966. */
  13967. _this.occlusionRetryCount = -1;
  13968. _this._occlusionInternalRetryCounter = 0;
  13969. _this._isOccluded = false;
  13970. _this._isOcclusionQueryInProgress = false;
  13971. _this.visibility = 1.0;
  13972. _this.alphaIndex = Number.MAX_VALUE;
  13973. _this.isVisible = true;
  13974. _this.isPickable = true;
  13975. _this.showBoundingBox = false;
  13976. _this.showSubMeshesBoundingBox = false;
  13977. _this.isBlocker = false;
  13978. _this.enablePointerMoveEvents = false;
  13979. _this.renderingGroupId = 0;
  13980. _this._receiveShadows = false;
  13981. _this.renderOutline = false;
  13982. _this.outlineColor = BABYLON.Color3.Red();
  13983. _this.outlineWidth = 0.02;
  13984. _this.renderOverlay = false;
  13985. _this.overlayColor = BABYLON.Color3.Red();
  13986. _this.overlayAlpha = 0.5;
  13987. _this._hasVertexAlpha = false;
  13988. _this._useVertexColors = true;
  13989. _this._computeBonesUsingShaders = true;
  13990. _this._numBoneInfluencers = 4;
  13991. _this._applyFog = true;
  13992. _this.useOctreeForRenderingSelection = true;
  13993. _this.useOctreeForPicking = true;
  13994. _this.useOctreeForCollisions = true;
  13995. _this._layerMask = 0x0FFFFFFF;
  13996. /**
  13997. * True if the mesh must be rendered in any case.
  13998. */
  13999. _this.alwaysSelectAsActiveMesh = false;
  14000. // Collisions
  14001. _this._checkCollisions = false;
  14002. _this._collisionMask = -1;
  14003. _this._collisionGroup = -1;
  14004. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14005. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  14006. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14007. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14008. // Edges
  14009. _this.edgesWidth = 1;
  14010. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  14011. // Cache
  14012. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  14013. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  14014. _this._isDisposed = false;
  14015. _this._renderId = 0;
  14016. _this._intersectionsInProgress = new Array();
  14017. _this._unIndexed = false;
  14018. _this._lightSources = new Array();
  14019. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14020. if (collidedMesh === void 0) { collidedMesh = null; }
  14021. //TODO move this to the collision coordinator!
  14022. if (_this.getScene().workerCollisions)
  14023. newPosition.multiplyInPlace(_this._collider.radius);
  14024. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  14025. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  14026. _this.position.addInPlace(_this._diffPositionForCollisions);
  14027. }
  14028. if (collidedMesh) {
  14029. _this.onCollideObservable.notifyObservers(collidedMesh);
  14030. }
  14031. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  14032. };
  14033. _this.getScene().addMesh(_this);
  14034. _this._resyncLightSources();
  14035. return _this;
  14036. }
  14037. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  14038. get: function () {
  14039. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  14040. },
  14041. enumerable: true,
  14042. configurable: true
  14043. });
  14044. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  14045. get: function () {
  14046. return BABYLON.TransformNode.BILLBOARDMODE_X;
  14047. },
  14048. enumerable: true,
  14049. configurable: true
  14050. });
  14051. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  14052. get: function () {
  14053. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  14054. },
  14055. enumerable: true,
  14056. configurable: true
  14057. });
  14058. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  14059. get: function () {
  14060. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  14061. },
  14062. enumerable: true,
  14063. configurable: true
  14064. });
  14065. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  14066. get: function () {
  14067. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  14068. },
  14069. enumerable: true,
  14070. configurable: true
  14071. });
  14072. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  14073. /**
  14074. * Read-only : the number of facets in the mesh
  14075. */
  14076. get: function () {
  14077. return this._facetNb;
  14078. },
  14079. enumerable: true,
  14080. configurable: true
  14081. });
  14082. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  14083. /**
  14084. * The number (integer) of subdivisions per axis in the partioning space
  14085. */
  14086. get: function () {
  14087. return this._partitioningSubdivisions;
  14088. },
  14089. set: function (nb) {
  14090. this._partitioningSubdivisions = nb;
  14091. },
  14092. enumerable: true,
  14093. configurable: true
  14094. });
  14095. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  14096. /**
  14097. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  14098. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  14099. */
  14100. get: function () {
  14101. return this._partitioningBBoxRatio;
  14102. },
  14103. set: function (ratio) {
  14104. this._partitioningBBoxRatio = ratio;
  14105. },
  14106. enumerable: true,
  14107. configurable: true
  14108. });
  14109. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  14110. /**
  14111. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  14112. * Works only for updatable meshes.
  14113. * Doesn't work with multi-materials.
  14114. */
  14115. get: function () {
  14116. return this._facetDepthSort;
  14117. },
  14118. set: function (sort) {
  14119. this._facetDepthSort = sort;
  14120. },
  14121. enumerable: true,
  14122. configurable: true
  14123. });
  14124. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  14125. /**
  14126. * The location (Vector3) where the facet depth sort must be computed from.
  14127. * By default, the active camera position.
  14128. * Used only when facet depth sort is enabled.
  14129. */
  14130. get: function () {
  14131. return this._facetDepthSortFrom;
  14132. },
  14133. set: function (location) {
  14134. this._facetDepthSortFrom = location;
  14135. },
  14136. enumerable: true,
  14137. configurable: true
  14138. });
  14139. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  14140. /**
  14141. * Read-only boolean : is the feature facetData enabled ?
  14142. */
  14143. get: function () {
  14144. return this._facetDataEnabled;
  14145. },
  14146. enumerable: true,
  14147. configurable: true
  14148. });
  14149. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  14150. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  14151. return false;
  14152. }
  14153. this._markSubMeshesAsMiscDirty();
  14154. return true;
  14155. };
  14156. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  14157. set: function (callback) {
  14158. if (this._onCollideObserver) {
  14159. this.onCollideObservable.remove(this._onCollideObserver);
  14160. }
  14161. this._onCollideObserver = this.onCollideObservable.add(callback);
  14162. },
  14163. enumerable: true,
  14164. configurable: true
  14165. });
  14166. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  14167. set: function (callback) {
  14168. if (this._onCollisionPositionChangeObserver) {
  14169. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  14170. }
  14171. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  14172. },
  14173. enumerable: true,
  14174. configurable: true
  14175. });
  14176. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  14177. /**
  14178. * 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.
  14179. */
  14180. get: function () {
  14181. return this._isOccluded;
  14182. },
  14183. set: function (value) {
  14184. this._isOccluded = value;
  14185. },
  14186. enumerable: true,
  14187. configurable: true
  14188. });
  14189. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  14190. /**
  14191. * Flag to check the progress status of the query
  14192. */
  14193. get: function () {
  14194. return this._isOcclusionQueryInProgress;
  14195. },
  14196. enumerable: true,
  14197. configurable: true
  14198. });
  14199. Object.defineProperty(AbstractMesh.prototype, "material", {
  14200. get: function () {
  14201. return this._material;
  14202. },
  14203. set: function (value) {
  14204. if (this._material === value) {
  14205. return;
  14206. }
  14207. this._material = value;
  14208. if (this.onMaterialChangedObservable.hasObservers) {
  14209. this.onMaterialChangedObservable.notifyObservers(this);
  14210. }
  14211. if (!this.subMeshes) {
  14212. return;
  14213. }
  14214. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14215. var subMesh = _a[_i];
  14216. subMesh.setEffect(null);
  14217. }
  14218. },
  14219. enumerable: true,
  14220. configurable: true
  14221. });
  14222. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  14223. get: function () {
  14224. return this._receiveShadows;
  14225. },
  14226. set: function (value) {
  14227. if (this._receiveShadows === value) {
  14228. return;
  14229. }
  14230. this._receiveShadows = value;
  14231. this._markSubMeshesAsLightDirty();
  14232. },
  14233. enumerable: true,
  14234. configurable: true
  14235. });
  14236. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  14237. get: function () {
  14238. return this._hasVertexAlpha;
  14239. },
  14240. set: function (value) {
  14241. if (this._hasVertexAlpha === value) {
  14242. return;
  14243. }
  14244. this._hasVertexAlpha = value;
  14245. this._markSubMeshesAsAttributesDirty();
  14246. },
  14247. enumerable: true,
  14248. configurable: true
  14249. });
  14250. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  14251. get: function () {
  14252. return this._useVertexColors;
  14253. },
  14254. set: function (value) {
  14255. if (this._useVertexColors === value) {
  14256. return;
  14257. }
  14258. this._useVertexColors = value;
  14259. this._markSubMeshesAsAttributesDirty();
  14260. },
  14261. enumerable: true,
  14262. configurable: true
  14263. });
  14264. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  14265. get: function () {
  14266. return this._computeBonesUsingShaders;
  14267. },
  14268. set: function (value) {
  14269. if (this._computeBonesUsingShaders === value) {
  14270. return;
  14271. }
  14272. this._computeBonesUsingShaders = value;
  14273. this._markSubMeshesAsAttributesDirty();
  14274. },
  14275. enumerable: true,
  14276. configurable: true
  14277. });
  14278. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  14279. get: function () {
  14280. return this._numBoneInfluencers;
  14281. },
  14282. set: function (value) {
  14283. if (this._numBoneInfluencers === value) {
  14284. return;
  14285. }
  14286. this._numBoneInfluencers = value;
  14287. this._markSubMeshesAsAttributesDirty();
  14288. },
  14289. enumerable: true,
  14290. configurable: true
  14291. });
  14292. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  14293. get: function () {
  14294. return this._applyFog;
  14295. },
  14296. set: function (value) {
  14297. if (this._applyFog === value) {
  14298. return;
  14299. }
  14300. this._applyFog = value;
  14301. this._markSubMeshesAsMiscDirty();
  14302. },
  14303. enumerable: true,
  14304. configurable: true
  14305. });
  14306. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  14307. get: function () {
  14308. return this._layerMask;
  14309. },
  14310. set: function (value) {
  14311. if (value === this._layerMask) {
  14312. return;
  14313. }
  14314. this._layerMask = value;
  14315. this._resyncLightSources();
  14316. },
  14317. enumerable: true,
  14318. configurable: true
  14319. });
  14320. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  14321. get: function () {
  14322. return this._collisionMask;
  14323. },
  14324. set: function (mask) {
  14325. this._collisionMask = !isNaN(mask) ? mask : -1;
  14326. },
  14327. enumerable: true,
  14328. configurable: true
  14329. });
  14330. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  14331. get: function () {
  14332. return this._collisionGroup;
  14333. },
  14334. set: function (mask) {
  14335. this._collisionGroup = !isNaN(mask) ? mask : -1;
  14336. },
  14337. enumerable: true,
  14338. configurable: true
  14339. });
  14340. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  14341. get: function () {
  14342. return null;
  14343. },
  14344. enumerable: true,
  14345. configurable: true
  14346. });
  14347. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  14348. get: function () {
  14349. return this._skeleton;
  14350. },
  14351. set: function (value) {
  14352. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  14353. this._skeleton._unregisterMeshWithPoseMatrix(this);
  14354. }
  14355. if (value && value.needInitialSkinMatrix) {
  14356. value._registerMeshWithPoseMatrix(this);
  14357. }
  14358. this._skeleton = value;
  14359. if (!this._skeleton) {
  14360. this._bonesTransformMatrices = null;
  14361. }
  14362. this._markSubMeshesAsAttributesDirty();
  14363. },
  14364. enumerable: true,
  14365. configurable: true
  14366. });
  14367. /**
  14368. * Boolean : true if the mesh has been disposed.
  14369. */
  14370. AbstractMesh.prototype.isDisposed = function () {
  14371. return this._isDisposed;
  14372. };
  14373. /**
  14374. * Returns the string "AbstractMesh"
  14375. */
  14376. AbstractMesh.prototype.getClassName = function () {
  14377. return "AbstractMesh";
  14378. };
  14379. /**
  14380. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14381. */
  14382. AbstractMesh.prototype.toString = function (fullDetails) {
  14383. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  14384. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  14385. if (this._skeleton) {
  14386. ret += ", skeleton: " + this._skeleton.name;
  14387. }
  14388. if (fullDetails) {
  14389. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  14390. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  14391. }
  14392. return ret;
  14393. };
  14394. AbstractMesh.prototype._rebuild = function () {
  14395. if (this._occlusionQuery) {
  14396. this._occlusionQuery = null;
  14397. }
  14398. if (this._edgesRenderer) {
  14399. this._edgesRenderer._rebuild();
  14400. }
  14401. if (!this.subMeshes) {
  14402. return;
  14403. }
  14404. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14405. var subMesh = _a[_i];
  14406. subMesh._rebuild();
  14407. }
  14408. };
  14409. AbstractMesh.prototype._resyncLightSources = function () {
  14410. this._lightSources.length = 0;
  14411. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  14412. var light = _a[_i];
  14413. if (!light.isEnabled()) {
  14414. continue;
  14415. }
  14416. if (light.canAffectMesh(this)) {
  14417. this._lightSources.push(light);
  14418. }
  14419. }
  14420. this._markSubMeshesAsLightDirty();
  14421. };
  14422. AbstractMesh.prototype._resyncLighSource = function (light) {
  14423. var isIn = light.isEnabled() && light.canAffectMesh(this);
  14424. var index = this._lightSources.indexOf(light);
  14425. if (index === -1) {
  14426. if (!isIn) {
  14427. return;
  14428. }
  14429. this._lightSources.push(light);
  14430. }
  14431. else {
  14432. if (isIn) {
  14433. return;
  14434. }
  14435. this._lightSources.splice(index, 1);
  14436. }
  14437. this._markSubMeshesAsLightDirty();
  14438. };
  14439. AbstractMesh.prototype._removeLightSource = function (light) {
  14440. var index = this._lightSources.indexOf(light);
  14441. if (index === -1) {
  14442. return;
  14443. }
  14444. this._lightSources.splice(index, 1);
  14445. };
  14446. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  14447. if (!this.subMeshes) {
  14448. return;
  14449. }
  14450. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14451. var subMesh = _a[_i];
  14452. if (subMesh._materialDefines) {
  14453. func(subMesh._materialDefines);
  14454. }
  14455. }
  14456. };
  14457. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  14458. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  14459. };
  14460. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  14461. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  14462. };
  14463. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  14464. if (!this.subMeshes) {
  14465. return;
  14466. }
  14467. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14468. var subMesh = _a[_i];
  14469. var material = subMesh.getMaterial();
  14470. if (material) {
  14471. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  14472. }
  14473. }
  14474. };
  14475. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  14476. /**
  14477. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14478. * Default : (1.0, 1.0, 1.0)
  14479. */
  14480. get: function () {
  14481. return this._scaling;
  14482. },
  14483. /**
  14484. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14485. * Default : (1.0, 1.0, 1.0)
  14486. */
  14487. set: function (newScaling) {
  14488. this._scaling = newScaling;
  14489. if (this.physicsImpostor) {
  14490. this.physicsImpostor.forceUpdate();
  14491. }
  14492. },
  14493. enumerable: true,
  14494. configurable: true
  14495. });
  14496. // Methods
  14497. /**
  14498. * Disables the mesh edger rendering mode.
  14499. * Returns the AbstractMesh.
  14500. */
  14501. AbstractMesh.prototype.disableEdgesRendering = function () {
  14502. if (this._edgesRenderer) {
  14503. this._edgesRenderer.dispose();
  14504. this._edgesRenderer = null;
  14505. }
  14506. return this;
  14507. };
  14508. /**
  14509. * Enables the edge rendering mode on the mesh.
  14510. * This mode makes the mesh edges visible.
  14511. * Returns the AbstractMesh.
  14512. */
  14513. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  14514. if (epsilon === void 0) { epsilon = 0.95; }
  14515. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  14516. this.disableEdgesRendering();
  14517. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  14518. return this;
  14519. };
  14520. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  14521. /**
  14522. * Returns true if the mesh is blocked. Used by the class Mesh.
  14523. * Returns the boolean `false` by default.
  14524. */
  14525. get: function () {
  14526. return false;
  14527. },
  14528. enumerable: true,
  14529. configurable: true
  14530. });
  14531. /**
  14532. * Returns the mesh itself by default, used by the class Mesh.
  14533. * Returned type : AbstractMesh
  14534. */
  14535. AbstractMesh.prototype.getLOD = function (camera) {
  14536. return this;
  14537. };
  14538. /**
  14539. * Returns 0 by default, used by the class Mesh.
  14540. * Returns an integer.
  14541. */
  14542. AbstractMesh.prototype.getTotalVertices = function () {
  14543. return 0;
  14544. };
  14545. /**
  14546. * Returns null by default, used by the class Mesh.
  14547. * Returned type : integer array
  14548. */
  14549. AbstractMesh.prototype.getIndices = function () {
  14550. return null;
  14551. };
  14552. /**
  14553. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  14554. * Returned type : float array or Float32Array
  14555. */
  14556. AbstractMesh.prototype.getVerticesData = function (kind) {
  14557. return null;
  14558. };
  14559. /**
  14560. * Sets the vertex data of the mesh geometry for the requested `kind`.
  14561. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  14562. * The `data` are either a numeric array either a Float32Array.
  14563. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  14564. * 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).
  14565. * Note that a new underlying VertexBuffer object is created each call.
  14566. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  14567. *
  14568. * Possible `kind` values :
  14569. * - BABYLON.VertexBuffer.PositionKind
  14570. * - BABYLON.VertexBuffer.UVKind
  14571. * - BABYLON.VertexBuffer.UV2Kind
  14572. * - BABYLON.VertexBuffer.UV3Kind
  14573. * - BABYLON.VertexBuffer.UV4Kind
  14574. * - BABYLON.VertexBuffer.UV5Kind
  14575. * - BABYLON.VertexBuffer.UV6Kind
  14576. * - BABYLON.VertexBuffer.ColorKind
  14577. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14578. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14579. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14580. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14581. *
  14582. * Returns the Mesh.
  14583. */
  14584. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14585. return this;
  14586. };
  14587. /**
  14588. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  14589. * If the mesh has no geometry, it is simply returned as it is.
  14590. * The `data` are either a numeric array either a Float32Array.
  14591. * No new underlying VertexBuffer object is created.
  14592. * 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.
  14593. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  14594. *
  14595. * Possible `kind` values :
  14596. * - BABYLON.VertexBuffer.PositionKind
  14597. * - BABYLON.VertexBuffer.UVKind
  14598. * - BABYLON.VertexBuffer.UV2Kind
  14599. * - BABYLON.VertexBuffer.UV3Kind
  14600. * - BABYLON.VertexBuffer.UV4Kind
  14601. * - BABYLON.VertexBuffer.UV5Kind
  14602. * - BABYLON.VertexBuffer.UV6Kind
  14603. * - BABYLON.VertexBuffer.ColorKind
  14604. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14605. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14606. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14607. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14608. *
  14609. * Returns the Mesh.
  14610. */
  14611. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14612. return this;
  14613. };
  14614. /**
  14615. * Sets the mesh indices.
  14616. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  14617. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  14618. * This method creates a new index buffer each call.
  14619. * Returns the Mesh.
  14620. */
  14621. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  14622. return this;
  14623. };
  14624. /** Returns false by default, used by the class Mesh.
  14625. * Returns a boolean
  14626. */
  14627. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  14628. return false;
  14629. };
  14630. /**
  14631. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  14632. * Returns a BoundingInfo
  14633. */
  14634. AbstractMesh.prototype.getBoundingInfo = function () {
  14635. if (this._masterMesh) {
  14636. return this._masterMesh.getBoundingInfo();
  14637. }
  14638. if (!this._boundingInfo) {
  14639. // this._boundingInfo is being created here
  14640. this._updateBoundingInfo();
  14641. }
  14642. // cannot be null.
  14643. return this._boundingInfo;
  14644. };
  14645. /**
  14646. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  14647. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  14648. */
  14649. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  14650. if (includeDescendants === void 0) { includeDescendants = true; }
  14651. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  14652. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  14653. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  14654. if (maxDimension === 0) {
  14655. return this;
  14656. }
  14657. var scale = 1 / maxDimension;
  14658. this.scaling.scaleInPlace(scale);
  14659. return this;
  14660. };
  14661. /**
  14662. * Sets a mesh new object BoundingInfo.
  14663. * Returns the AbstractMesh.
  14664. */
  14665. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  14666. this._boundingInfo = boundingInfo;
  14667. return this;
  14668. };
  14669. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  14670. get: function () {
  14671. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  14672. },
  14673. enumerable: true,
  14674. configurable: true
  14675. });
  14676. AbstractMesh.prototype._preActivate = function () {
  14677. };
  14678. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  14679. };
  14680. AbstractMesh.prototype._activate = function (renderId) {
  14681. this._renderId = renderId;
  14682. };
  14683. /**
  14684. * Returns the latest update of the World matrix
  14685. * Returns a Matrix.
  14686. */
  14687. AbstractMesh.prototype.getWorldMatrix = function () {
  14688. if (this._masterMesh) {
  14689. return this._masterMesh.getWorldMatrix();
  14690. }
  14691. return _super.prototype.getWorldMatrix.call(this);
  14692. };
  14693. // ================================== Point of View Movement =================================
  14694. /**
  14695. * Perform relative position change from the point of view of behind the front of the mesh.
  14696. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14697. * Supports definition of mesh facing forward or backward.
  14698. * @param {number} amountRight
  14699. * @param {number} amountUp
  14700. * @param {number} amountForward
  14701. *
  14702. * Returns the AbstractMesh.
  14703. */
  14704. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  14705. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  14706. return this;
  14707. };
  14708. /**
  14709. * Calculate relative position change from the point of view of behind the front of the mesh.
  14710. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14711. * Supports definition of mesh facing forward or backward.
  14712. * @param {number} amountRight
  14713. * @param {number} amountUp
  14714. * @param {number} amountForward
  14715. *
  14716. * Returns a new Vector3.
  14717. */
  14718. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  14719. var rotMatrix = new BABYLON.Matrix();
  14720. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14721. rotQuaternion.toRotationMatrix(rotMatrix);
  14722. var translationDelta = BABYLON.Vector3.Zero();
  14723. var defForwardMult = this.definedFacingForward ? -1 : 1;
  14724. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  14725. return translationDelta;
  14726. };
  14727. // ================================== Point of View Rotation =================================
  14728. /**
  14729. * Perform relative rotation change from the point of view of behind the front of the mesh.
  14730. * Supports definition of mesh facing forward or backward.
  14731. * @param {number} flipBack
  14732. * @param {number} twirlClockwise
  14733. * @param {number} tiltRight
  14734. *
  14735. * Returns the AbstractMesh.
  14736. */
  14737. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14738. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  14739. return this;
  14740. };
  14741. /**
  14742. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  14743. * Supports definition of mesh facing forward or backward.
  14744. * @param {number} flipBack
  14745. * @param {number} twirlClockwise
  14746. * @param {number} tiltRight
  14747. *
  14748. * Returns a new Vector3.
  14749. */
  14750. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14751. var defForwardMult = this.definedFacingForward ? 1 : -1;
  14752. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  14753. };
  14754. /**
  14755. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  14756. * @param includeDescendants Include bounding info from descendants as well (true by default).
  14757. */
  14758. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  14759. if (includeDescendants === void 0) { includeDescendants = true; }
  14760. this.computeWorldMatrix(true);
  14761. var min;
  14762. var max;
  14763. var boundingInfo = this.getBoundingInfo();
  14764. if (!this.subMeshes) {
  14765. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14766. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14767. }
  14768. else {
  14769. min = boundingInfo.boundingBox.minimumWorld;
  14770. max = boundingInfo.boundingBox.maximumWorld;
  14771. }
  14772. if (includeDescendants) {
  14773. var descendants = this.getDescendants(false);
  14774. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  14775. var descendant = descendants_1[_i];
  14776. var childMesh = descendant;
  14777. childMesh.computeWorldMatrix(true);
  14778. var childBoundingInfo = childMesh.getBoundingInfo();
  14779. if (childMesh.getTotalVertices() === 0) {
  14780. continue;
  14781. }
  14782. var boundingBox = childBoundingInfo.boundingBox;
  14783. var minBox = boundingBox.minimumWorld;
  14784. var maxBox = boundingBox.maximumWorld;
  14785. BABYLON.Tools.CheckExtends(minBox, min, max);
  14786. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14787. }
  14788. }
  14789. return {
  14790. min: min,
  14791. max: max
  14792. };
  14793. };
  14794. /**
  14795. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  14796. * Returns the AbstractMesh.
  14797. */
  14798. AbstractMesh.prototype._updateBoundingInfo = function () {
  14799. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  14800. this._boundingInfo.update(this.worldMatrixFromCache);
  14801. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14802. return this;
  14803. };
  14804. /**
  14805. * Update a mesh's children BoundingInfo objects only.
  14806. * Returns the AbstractMesh.
  14807. */
  14808. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  14809. if (!this.subMeshes) {
  14810. return this;
  14811. }
  14812. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  14813. var subMesh = this.subMeshes[subIndex];
  14814. if (!subMesh.IsGlobal) {
  14815. subMesh.updateBoundingInfo(matrix);
  14816. }
  14817. }
  14818. return this;
  14819. };
  14820. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  14821. // Bounding info
  14822. this._updateBoundingInfo();
  14823. };
  14824. /**
  14825. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14826. * A mesh is in the frustum if its bounding box intersects the frustum.
  14827. * Boolean returned.
  14828. */
  14829. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14830. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14831. };
  14832. /**
  14833. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14834. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14835. * Boolean returned.
  14836. */
  14837. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14838. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14839. ;
  14840. };
  14841. /**
  14842. * True if the mesh intersects another mesh or a SolidParticle object.
  14843. * 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)
  14844. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14845. * Returns a boolean.
  14846. */
  14847. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14848. if (precise === void 0) { precise = false; }
  14849. if (!this._boundingInfo || !mesh._boundingInfo) {
  14850. return false;
  14851. }
  14852. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14853. return true;
  14854. }
  14855. if (includeDescendants) {
  14856. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14857. var child = _a[_i];
  14858. if (child.intersectsMesh(mesh, precise, true)) {
  14859. return true;
  14860. }
  14861. }
  14862. }
  14863. return false;
  14864. };
  14865. /**
  14866. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14867. * Returns a boolean.
  14868. */
  14869. AbstractMesh.prototype.intersectsPoint = function (point) {
  14870. if (!this._boundingInfo) {
  14871. return false;
  14872. }
  14873. return this._boundingInfo.intersectsPoint(point);
  14874. };
  14875. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14876. return this.physicsImpostor;
  14877. };
  14878. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14879. if (camera === void 0) { camera = null; }
  14880. if (!camera) {
  14881. camera = this.getScene().activeCamera;
  14882. }
  14883. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14884. };
  14885. /**
  14886. * Returns the distance from the mesh to the active camera.
  14887. * Returns a float.
  14888. */
  14889. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14890. if (camera === void 0) { camera = null; }
  14891. if (!camera) {
  14892. camera = this.getScene().activeCamera;
  14893. }
  14894. return this.absolutePosition.subtract(camera.position).length();
  14895. };
  14896. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14897. if (!this.physicsImpostor) {
  14898. return this;
  14899. }
  14900. this.physicsImpostor.applyImpulse(force, contactPoint);
  14901. return this;
  14902. };
  14903. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14904. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14905. return this;
  14906. }
  14907. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14908. mainPivot: pivot1,
  14909. connectedPivot: pivot2,
  14910. nativeParams: options
  14911. });
  14912. return this;
  14913. };
  14914. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14915. // Collisions
  14916. /**
  14917. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14918. * Default `false`.
  14919. */
  14920. get: function () {
  14921. return this._checkCollisions;
  14922. },
  14923. set: function (collisionEnabled) {
  14924. this._checkCollisions = collisionEnabled;
  14925. if (this.getScene().workerCollisions) {
  14926. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14927. }
  14928. },
  14929. enumerable: true,
  14930. configurable: true
  14931. });
  14932. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14933. var globalPosition = this.getAbsolutePosition();
  14934. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14935. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14936. if (!this._collider) {
  14937. this._collider = new BABYLON.Collider();
  14938. }
  14939. this._collider.radius = this.ellipsoid;
  14940. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14941. return this;
  14942. };
  14943. // Submeshes octree
  14944. /**
  14945. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14946. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14947. * Returns an Octree of submeshes.
  14948. */
  14949. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14950. if (maxCapacity === void 0) { maxCapacity = 64; }
  14951. if (maxDepth === void 0) { maxDepth = 2; }
  14952. if (!this._submeshesOctree) {
  14953. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14954. }
  14955. this.computeWorldMatrix(true);
  14956. var boundingInfo = this.getBoundingInfo();
  14957. // Update octree
  14958. var bbox = boundingInfo.boundingBox;
  14959. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14960. return this._submeshesOctree;
  14961. };
  14962. // Collisions
  14963. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  14964. this._generatePointsArray();
  14965. if (!this._positions) {
  14966. return this;
  14967. }
  14968. // Transformation
  14969. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  14970. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  14971. subMesh._lastColliderWorldVertices = [];
  14972. subMesh._trianglePlanes = [];
  14973. var start = subMesh.verticesStart;
  14974. var end = (subMesh.verticesStart + subMesh.verticesCount);
  14975. for (var i = start; i < end; i++) {
  14976. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  14977. }
  14978. }
  14979. // Collide
  14980. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  14981. if (collider.collisionFound) {
  14982. collider.collidedMesh = this;
  14983. }
  14984. return this;
  14985. };
  14986. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  14987. var subMeshes;
  14988. var len;
  14989. // Octrees
  14990. if (this._submeshesOctree && this.useOctreeForCollisions) {
  14991. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  14992. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  14993. len = intersections.length;
  14994. subMeshes = intersections.data;
  14995. }
  14996. else {
  14997. subMeshes = this.subMeshes;
  14998. len = subMeshes.length;
  14999. }
  15000. for (var index = 0; index < len; index++) {
  15001. var subMesh = subMeshes[index];
  15002. // Bounding test
  15003. if (len > 1 && !subMesh._checkCollision(collider))
  15004. continue;
  15005. this._collideForSubMesh(subMesh, transformMatrix, collider);
  15006. }
  15007. return this;
  15008. };
  15009. AbstractMesh.prototype._checkCollision = function (collider) {
  15010. // Bounding box test
  15011. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  15012. return this;
  15013. // Transformation matrix
  15014. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  15015. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  15016. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  15017. return this;
  15018. };
  15019. // Picking
  15020. AbstractMesh.prototype._generatePointsArray = function () {
  15021. return false;
  15022. };
  15023. /**
  15024. * Checks if the passed Ray intersects with the mesh.
  15025. * Returns an object PickingInfo.
  15026. */
  15027. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  15028. var pickingInfo = new BABYLON.PickingInfo();
  15029. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  15030. return pickingInfo;
  15031. }
  15032. if (!this._generatePointsArray()) {
  15033. return pickingInfo;
  15034. }
  15035. var intersectInfo = null;
  15036. // Octrees
  15037. var subMeshes;
  15038. var len;
  15039. if (this._submeshesOctree && this.useOctreeForPicking) {
  15040. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  15041. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  15042. len = intersections.length;
  15043. subMeshes = intersections.data;
  15044. }
  15045. else {
  15046. subMeshes = this.subMeshes;
  15047. len = subMeshes.length;
  15048. }
  15049. for (var index = 0; index < len; index++) {
  15050. var subMesh = subMeshes[index];
  15051. // Bounding test
  15052. if (len > 1 && !subMesh.canIntersects(ray))
  15053. continue;
  15054. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  15055. if (currentIntersectInfo) {
  15056. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15057. intersectInfo = currentIntersectInfo;
  15058. intersectInfo.subMeshId = index;
  15059. if (fastCheck) {
  15060. break;
  15061. }
  15062. }
  15063. }
  15064. }
  15065. if (intersectInfo) {
  15066. // Get picked point
  15067. var world = this.getWorldMatrix();
  15068. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  15069. var direction = ray.direction.clone();
  15070. direction = direction.scale(intersectInfo.distance);
  15071. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  15072. var pickedPoint = worldOrigin.add(worldDirection);
  15073. // Return result
  15074. pickingInfo.hit = true;
  15075. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  15076. pickingInfo.pickedPoint = pickedPoint;
  15077. pickingInfo.pickedMesh = this;
  15078. pickingInfo.bu = intersectInfo.bu || 0;
  15079. pickingInfo.bv = intersectInfo.bv || 0;
  15080. pickingInfo.faceId = intersectInfo.faceId;
  15081. pickingInfo.subMeshId = intersectInfo.subMeshId;
  15082. return pickingInfo;
  15083. }
  15084. return pickingInfo;
  15085. };
  15086. /**
  15087. * Clones the mesh, used by the class Mesh.
  15088. * Just returns `null` for an AbstractMesh.
  15089. */
  15090. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15091. return null;
  15092. };
  15093. /**
  15094. * Disposes all the mesh submeshes.
  15095. * Returns the AbstractMesh.
  15096. */
  15097. AbstractMesh.prototype.releaseSubMeshes = function () {
  15098. if (this.subMeshes) {
  15099. while (this.subMeshes.length) {
  15100. this.subMeshes[0].dispose();
  15101. }
  15102. }
  15103. else {
  15104. this.subMeshes = new Array();
  15105. }
  15106. return this;
  15107. };
  15108. /**
  15109. * Disposes the AbstractMesh.
  15110. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15111. * Returns nothing.
  15112. */
  15113. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15114. var _this = this;
  15115. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15116. var index;
  15117. // Action manager
  15118. if (this.actionManager) {
  15119. this.actionManager.dispose();
  15120. this.actionManager = null;
  15121. }
  15122. // Skeleton
  15123. this.skeleton = null;
  15124. // Physics
  15125. if (this.physicsImpostor) {
  15126. this.physicsImpostor.dispose();
  15127. }
  15128. // Intersections in progress
  15129. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  15130. var other = this._intersectionsInProgress[index];
  15131. var pos = other._intersectionsInProgress.indexOf(this);
  15132. other._intersectionsInProgress.splice(pos, 1);
  15133. }
  15134. this._intersectionsInProgress = [];
  15135. // Lights
  15136. var lights = this.getScene().lights;
  15137. lights.forEach(function (light) {
  15138. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  15139. if (meshIndex !== -1) {
  15140. light.includedOnlyMeshes.splice(meshIndex, 1);
  15141. }
  15142. meshIndex = light.excludedMeshes.indexOf(_this);
  15143. if (meshIndex !== -1) {
  15144. light.excludedMeshes.splice(meshIndex, 1);
  15145. }
  15146. // Shadow generators
  15147. var generator = light.getShadowGenerator();
  15148. if (generator) {
  15149. var shadowMap = generator.getShadowMap();
  15150. if (shadowMap && shadowMap.renderList) {
  15151. meshIndex = shadowMap.renderList.indexOf(_this);
  15152. if (meshIndex !== -1) {
  15153. shadowMap.renderList.splice(meshIndex, 1);
  15154. }
  15155. }
  15156. }
  15157. });
  15158. // Edges
  15159. if (this._edgesRenderer) {
  15160. this._edgesRenderer.dispose();
  15161. this._edgesRenderer = null;
  15162. }
  15163. // SubMeshes
  15164. if (this.getClassName() !== "InstancedMesh") {
  15165. this.releaseSubMeshes();
  15166. }
  15167. // Octree
  15168. var sceneOctree = this.getScene().selectionOctree;
  15169. if (sceneOctree) {
  15170. var index = sceneOctree.dynamicContent.indexOf(this);
  15171. if (index !== -1) {
  15172. sceneOctree.dynamicContent.splice(index, 1);
  15173. }
  15174. }
  15175. // Query
  15176. var engine = this.getScene().getEngine();
  15177. if (this._occlusionQuery) {
  15178. this._isOcclusionQueryInProgress = false;
  15179. engine.deleteQuery(this._occlusionQuery);
  15180. this._occlusionQuery = null;
  15181. }
  15182. // Engine
  15183. engine.wipeCaches();
  15184. // Remove from scene
  15185. this.getScene().removeMesh(this);
  15186. if (disposeMaterialAndTextures) {
  15187. if (this.material) {
  15188. this.material.dispose(false, true);
  15189. }
  15190. }
  15191. if (!doNotRecurse) {
  15192. // Particles
  15193. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  15194. if (this.getScene().particleSystems[index].emitter === this) {
  15195. this.getScene().particleSystems[index].dispose();
  15196. index--;
  15197. }
  15198. }
  15199. }
  15200. // facet data
  15201. if (this._facetDataEnabled) {
  15202. this.disableFacetData();
  15203. }
  15204. this.onAfterWorldMatrixUpdateObservable.clear();
  15205. this.onCollideObservable.clear();
  15206. this.onCollisionPositionChangeObservable.clear();
  15207. this._isDisposed = true;
  15208. _super.prototype.dispose.call(this, doNotRecurse);
  15209. };
  15210. /**
  15211. * Adds the passed mesh as a child to the current mesh.
  15212. * Returns the AbstractMesh.
  15213. */
  15214. AbstractMesh.prototype.addChild = function (mesh) {
  15215. mesh.setParent(this);
  15216. return this;
  15217. };
  15218. /**
  15219. * Removes the passed mesh from the current mesh children list.
  15220. * Returns the AbstractMesh.
  15221. */
  15222. AbstractMesh.prototype.removeChild = function (mesh) {
  15223. mesh.setParent(null);
  15224. return this;
  15225. };
  15226. // Facet data
  15227. /**
  15228. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  15229. * Returns the AbstractMesh.
  15230. */
  15231. AbstractMesh.prototype._initFacetData = function () {
  15232. if (!this._facetNormals) {
  15233. this._facetNormals = new Array();
  15234. }
  15235. if (!this._facetPositions) {
  15236. this._facetPositions = new Array();
  15237. }
  15238. if (!this._facetPartitioning) {
  15239. this._facetPartitioning = new Array();
  15240. }
  15241. this._facetNb = (this.getIndices().length / 3) | 0;
  15242. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  15243. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  15244. for (var f = 0; f < this._facetNb; f++) {
  15245. this._facetNormals[f] = BABYLON.Vector3.Zero();
  15246. this._facetPositions[f] = BABYLON.Vector3.Zero();
  15247. }
  15248. this._facetDataEnabled = true;
  15249. return this;
  15250. };
  15251. /**
  15252. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  15253. * This method can be called within the render loop.
  15254. * 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.
  15255. * Returns the AbstractMesh.
  15256. */
  15257. AbstractMesh.prototype.updateFacetData = function () {
  15258. if (!this._facetDataEnabled) {
  15259. this._initFacetData();
  15260. }
  15261. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15262. var indices = this.getIndices();
  15263. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15264. var bInfo = this.getBoundingInfo();
  15265. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  15266. // init arrays, matrix and sort function on first call
  15267. this._facetDepthSortEnabled = true;
  15268. if (indices instanceof Uint16Array) {
  15269. this._depthSortedIndices = new Uint16Array(indices);
  15270. }
  15271. else if (indices instanceof Uint32Array) {
  15272. this._depthSortedIndices = new Uint32Array(indices);
  15273. }
  15274. else {
  15275. var needs32bits = false;
  15276. for (var i = 0; i < indices.length; i++) {
  15277. if (indices[i] > 65535) {
  15278. needs32bits = true;
  15279. break;
  15280. }
  15281. }
  15282. if (needs32bits) {
  15283. this._depthSortedIndices = new Uint32Array(indices);
  15284. }
  15285. else {
  15286. this._depthSortedIndices = new Uint16Array(indices);
  15287. }
  15288. }
  15289. this._facetDepthSortFunction = function (f1, f2) {
  15290. return (f2.sqDistance - f1.sqDistance);
  15291. };
  15292. if (!this._facetDepthSortFrom) {
  15293. var camera = this.getScene().activeCamera;
  15294. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  15295. }
  15296. this._depthSortedFacets = [];
  15297. for (var f = 0; f < this._facetNb; f++) {
  15298. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  15299. this._depthSortedFacets.push(depthSortedFacet);
  15300. }
  15301. this._invertedMatrix = BABYLON.Matrix.Identity();
  15302. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  15303. }
  15304. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  15305. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  15306. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  15307. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  15308. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  15309. this._subDiv.max = this._partitioningSubdivisions;
  15310. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  15311. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  15312. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  15313. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  15314. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  15315. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  15316. // set the parameters for ComputeNormals()
  15317. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  15318. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  15319. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  15320. this._facetParameters.bInfo = bInfo;
  15321. this._facetParameters.bbSize = this._bbSize;
  15322. this._facetParameters.subDiv = this._subDiv;
  15323. this._facetParameters.ratio = this.partitioningBBoxRatio;
  15324. this._facetParameters.depthSort = this._facetDepthSort;
  15325. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15326. this.computeWorldMatrix(true);
  15327. this._worldMatrix.invertToRef(this._invertedMatrix);
  15328. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  15329. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  15330. }
  15331. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  15332. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  15333. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15334. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  15335. var l = (this._depthSortedIndices.length / 3) | 0;
  15336. for (var f = 0; f < l; f++) {
  15337. var sind = this._depthSortedFacets[f].ind;
  15338. this._depthSortedIndices[f * 3] = indices[sind];
  15339. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  15340. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  15341. }
  15342. this.updateIndices(this._depthSortedIndices);
  15343. }
  15344. return this;
  15345. };
  15346. /**
  15347. * Returns the facetLocalNormals array.
  15348. * The normals are expressed in the mesh local space.
  15349. */
  15350. AbstractMesh.prototype.getFacetLocalNormals = function () {
  15351. if (!this._facetNormals) {
  15352. this.updateFacetData();
  15353. }
  15354. return this._facetNormals;
  15355. };
  15356. /**
  15357. * Returns the facetLocalPositions array.
  15358. * The facet positions are expressed in the mesh local space.
  15359. */
  15360. AbstractMesh.prototype.getFacetLocalPositions = function () {
  15361. if (!this._facetPositions) {
  15362. this.updateFacetData();
  15363. }
  15364. return this._facetPositions;
  15365. };
  15366. /**
  15367. * Returns the facetLocalPartioning array.
  15368. */
  15369. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  15370. if (!this._facetPartitioning) {
  15371. this.updateFacetData();
  15372. }
  15373. return this._facetPartitioning;
  15374. };
  15375. /**
  15376. * Returns the i-th facet position in the world system.
  15377. * This method allocates a new Vector3 per call.
  15378. */
  15379. AbstractMesh.prototype.getFacetPosition = function (i) {
  15380. var pos = BABYLON.Vector3.Zero();
  15381. this.getFacetPositionToRef(i, pos);
  15382. return pos;
  15383. };
  15384. /**
  15385. * Sets the reference Vector3 with the i-th facet position in the world system.
  15386. * Returns the AbstractMesh.
  15387. */
  15388. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  15389. var localPos = (this.getFacetLocalPositions())[i];
  15390. var world = this.getWorldMatrix();
  15391. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  15392. return this;
  15393. };
  15394. /**
  15395. * Returns the i-th facet normal in the world system.
  15396. * This method allocates a new Vector3 per call.
  15397. */
  15398. AbstractMesh.prototype.getFacetNormal = function (i) {
  15399. var norm = BABYLON.Vector3.Zero();
  15400. this.getFacetNormalToRef(i, norm);
  15401. return norm;
  15402. };
  15403. /**
  15404. * Sets the reference Vector3 with the i-th facet normal in the world system.
  15405. * Returns the AbstractMesh.
  15406. */
  15407. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  15408. var localNorm = (this.getFacetLocalNormals())[i];
  15409. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  15410. return this;
  15411. };
  15412. /**
  15413. * 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).
  15414. */
  15415. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  15416. var bInfo = this.getBoundingInfo();
  15417. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  15418. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  15419. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  15420. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  15421. return null;
  15422. }
  15423. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  15424. };
  15425. /**
  15426. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  15427. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  15428. * 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.
  15429. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15430. * 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.
  15431. */
  15432. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  15433. if (checkFace === void 0) { checkFace = false; }
  15434. if (facing === void 0) { facing = true; }
  15435. var world = this.getWorldMatrix();
  15436. var invMat = BABYLON.Tmp.Matrix[5];
  15437. world.invertToRef(invMat);
  15438. var invVect = BABYLON.Tmp.Vector3[8];
  15439. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  15440. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  15441. if (projected) {
  15442. // tranform the local computed projected vector to world coordinates
  15443. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  15444. }
  15445. return closest;
  15446. };
  15447. /**
  15448. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  15449. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  15450. * 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.
  15451. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15452. * 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.
  15453. */
  15454. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  15455. if (checkFace === void 0) { checkFace = false; }
  15456. if (facing === void 0) { facing = true; }
  15457. var closest = null;
  15458. var tmpx = 0.0;
  15459. var tmpy = 0.0;
  15460. var tmpz = 0.0;
  15461. var d = 0.0; // tmp dot facet normal * facet position
  15462. var t0 = 0.0;
  15463. var projx = 0.0;
  15464. var projy = 0.0;
  15465. var projz = 0.0;
  15466. // Get all the facets in the same partitioning block than (x, y, z)
  15467. var facetPositions = this.getFacetLocalPositions();
  15468. var facetNormals = this.getFacetLocalNormals();
  15469. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15470. if (!facetsInBlock) {
  15471. return null;
  15472. }
  15473. // Get the closest facet to (x, y, z)
  15474. var shortest = Number.MAX_VALUE; // init distance vars
  15475. var tmpDistance = shortest;
  15476. var fib; // current facet in the block
  15477. var norm; // current facet normal
  15478. var p0; // current facet barycenter position
  15479. // loop on all the facets in the current partitioning block
  15480. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15481. fib = facetsInBlock[idx];
  15482. norm = facetNormals[fib];
  15483. p0 = facetPositions[fib];
  15484. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15485. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15486. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15487. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15488. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15489. projx = x + norm.x * t0;
  15490. projy = y + norm.y * t0;
  15491. projz = z + norm.z * t0;
  15492. tmpx = projx - x;
  15493. tmpy = projy - y;
  15494. tmpz = projz - z;
  15495. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15496. if (tmpDistance < shortest) {
  15497. shortest = tmpDistance;
  15498. closest = fib;
  15499. if (projected) {
  15500. projected.x = projx;
  15501. projected.y = projy;
  15502. projected.z = projz;
  15503. }
  15504. }
  15505. }
  15506. }
  15507. return closest;
  15508. };
  15509. /**
  15510. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15511. */
  15512. AbstractMesh.prototype.getFacetDataParameters = function () {
  15513. return this._facetParameters;
  15514. };
  15515. /**
  15516. * Disables the feature FacetData and frees the related memory.
  15517. * Returns the AbstractMesh.
  15518. */
  15519. AbstractMesh.prototype.disableFacetData = function () {
  15520. if (this._facetDataEnabled) {
  15521. this._facetDataEnabled = false;
  15522. this._facetPositions = new Array();
  15523. this._facetNormals = new Array();
  15524. this._facetPartitioning = new Array();
  15525. this._facetParameters = null;
  15526. this._depthSortedIndices = new Uint32Array(0);
  15527. }
  15528. return this;
  15529. };
  15530. /**
  15531. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  15532. * Returns the mesh.
  15533. */
  15534. AbstractMesh.prototype.updateIndices = function (indices) {
  15535. return this;
  15536. };
  15537. /**
  15538. * The mesh Geometry. Actually used by the Mesh object.
  15539. * Returns a blank geometry object.
  15540. */
  15541. /**
  15542. * Creates new normals data for the mesh.
  15543. * @param updatable.
  15544. */
  15545. AbstractMesh.prototype.createNormals = function (updatable) {
  15546. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15547. var indices = this.getIndices();
  15548. var normals;
  15549. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15550. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15551. }
  15552. else {
  15553. normals = [];
  15554. }
  15555. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15556. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15557. };
  15558. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15559. var engine = this.getEngine();
  15560. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15561. this._isOccluded = false;
  15562. return;
  15563. }
  15564. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15565. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15566. if (isOcclusionQueryAvailable) {
  15567. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15568. this._isOcclusionQueryInProgress = false;
  15569. this._occlusionInternalRetryCounter = 0;
  15570. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15571. }
  15572. else {
  15573. this._occlusionInternalRetryCounter++;
  15574. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15575. this._isOcclusionQueryInProgress = false;
  15576. this._occlusionInternalRetryCounter = 0;
  15577. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15578. // if strict continue the last state of the object.
  15579. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15580. }
  15581. else {
  15582. return;
  15583. }
  15584. }
  15585. }
  15586. var scene = this.getScene();
  15587. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15588. if (!this._occlusionQuery) {
  15589. this._occlusionQuery = engine.createQuery();
  15590. }
  15591. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15592. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15593. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15594. this._isOcclusionQueryInProgress = true;
  15595. };
  15596. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15597. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15598. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15599. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15600. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15601. return AbstractMesh;
  15602. }(BABYLON.TransformNode));
  15603. BABYLON.AbstractMesh = AbstractMesh;
  15604. })(BABYLON || (BABYLON = {}));
  15605. //# sourceMappingURL=babylon.abstractMesh.js.map
  15606. var BABYLON;
  15607. (function (BABYLON) {
  15608. var Light = /** @class */ (function (_super) {
  15609. __extends(Light, _super);
  15610. /**
  15611. * Creates a Light object in the scene.
  15612. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15613. */
  15614. function Light(name, scene) {
  15615. var _this = _super.call(this, name, scene) || this;
  15616. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15617. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15618. _this.intensity = 1.0;
  15619. _this.range = Number.MAX_VALUE;
  15620. /**
  15621. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15622. * of light.
  15623. */
  15624. _this._photometricScale = 1.0;
  15625. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15626. _this._radius = 0.00001;
  15627. _this.renderPriority = 0;
  15628. /**
  15629. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15630. * the current shadow generator.
  15631. */
  15632. _this.shadowEnabled = true;
  15633. _this._excludeWithLayerMask = 0;
  15634. _this._includeOnlyWithLayerMask = 0;
  15635. _this._lightmapMode = 0;
  15636. _this._excludedMeshesIds = new Array();
  15637. _this._includedOnlyMeshesIds = new Array();
  15638. _this.getScene().addLight(_this);
  15639. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15640. _this._buildUniformLayout();
  15641. _this.includedOnlyMeshes = new Array();
  15642. _this.excludedMeshes = new Array();
  15643. _this._resyncMeshes();
  15644. return _this;
  15645. }
  15646. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15647. /**
  15648. * If every light affecting the material is in this lightmapMode,
  15649. * material.lightmapTexture adds or multiplies
  15650. * (depends on material.useLightmapAsShadowmap)
  15651. * after every other light calculations.
  15652. */
  15653. get: function () {
  15654. return Light._LIGHTMAP_DEFAULT;
  15655. },
  15656. enumerable: true,
  15657. configurable: true
  15658. });
  15659. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15660. /**
  15661. * material.lightmapTexture as only diffuse lighting from this light
  15662. * adds pnly specular lighting from this light
  15663. * adds dynamic shadows
  15664. */
  15665. get: function () {
  15666. return Light._LIGHTMAP_SPECULAR;
  15667. },
  15668. enumerable: true,
  15669. configurable: true
  15670. });
  15671. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15672. /**
  15673. * material.lightmapTexture as only lighting
  15674. * no light calculation from this light
  15675. * only adds dynamic shadows from this light
  15676. */
  15677. get: function () {
  15678. return Light._LIGHTMAP_SHADOWSONLY;
  15679. },
  15680. enumerable: true,
  15681. configurable: true
  15682. });
  15683. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15684. /**
  15685. * Each light type uses the default quantity according to its type:
  15686. * point/spot lights use luminous intensity
  15687. * directional lights use illuminance
  15688. */
  15689. get: function () {
  15690. return Light._INTENSITYMODE_AUTOMATIC;
  15691. },
  15692. enumerable: true,
  15693. configurable: true
  15694. });
  15695. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15696. /**
  15697. * lumen (lm)
  15698. */
  15699. get: function () {
  15700. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15701. },
  15702. enumerable: true,
  15703. configurable: true
  15704. });
  15705. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15706. /**
  15707. * candela (lm/sr)
  15708. */
  15709. get: function () {
  15710. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15711. },
  15712. enumerable: true,
  15713. configurable: true
  15714. });
  15715. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15716. /**
  15717. * lux (lm/m^2)
  15718. */
  15719. get: function () {
  15720. return Light._INTENSITYMODE_ILLUMINANCE;
  15721. },
  15722. enumerable: true,
  15723. configurable: true
  15724. });
  15725. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15726. /**
  15727. * nit (cd/m^2)
  15728. */
  15729. get: function () {
  15730. return Light._INTENSITYMODE_LUMINANCE;
  15731. },
  15732. enumerable: true,
  15733. configurable: true
  15734. });
  15735. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15736. /**
  15737. * Light type const id of the point light.
  15738. */
  15739. get: function () {
  15740. return Light._LIGHTTYPEID_POINTLIGHT;
  15741. },
  15742. enumerable: true,
  15743. configurable: true
  15744. });
  15745. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15746. /**
  15747. * Light type const id of the directional light.
  15748. */
  15749. get: function () {
  15750. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15751. },
  15752. enumerable: true,
  15753. configurable: true
  15754. });
  15755. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15756. /**
  15757. * Light type const id of the spot light.
  15758. */
  15759. get: function () {
  15760. return Light._LIGHTTYPEID_SPOTLIGHT;
  15761. },
  15762. enumerable: true,
  15763. configurable: true
  15764. });
  15765. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15766. /**
  15767. * Light type const id of the hemispheric light.
  15768. */
  15769. get: function () {
  15770. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15771. },
  15772. enumerable: true,
  15773. configurable: true
  15774. });
  15775. Object.defineProperty(Light.prototype, "intensityMode", {
  15776. /**
  15777. * Gets the photometric scale used to interpret the intensity.
  15778. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15779. */
  15780. get: function () {
  15781. return this._intensityMode;
  15782. },
  15783. /**
  15784. * Sets the photometric scale used to interpret the intensity.
  15785. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15786. */
  15787. set: function (value) {
  15788. this._intensityMode = value;
  15789. this._computePhotometricScale();
  15790. },
  15791. enumerable: true,
  15792. configurable: true
  15793. });
  15794. ;
  15795. ;
  15796. Object.defineProperty(Light.prototype, "radius", {
  15797. /**
  15798. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15799. */
  15800. get: function () {
  15801. return this._radius;
  15802. },
  15803. /**
  15804. * sets the light radius used by PBR Materials to simulate soft area lights.
  15805. */
  15806. set: function (value) {
  15807. this._radius = value;
  15808. this._computePhotometricScale();
  15809. },
  15810. enumerable: true,
  15811. configurable: true
  15812. });
  15813. ;
  15814. ;
  15815. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15816. get: function () {
  15817. return this._includedOnlyMeshes;
  15818. },
  15819. set: function (value) {
  15820. this._includedOnlyMeshes = value;
  15821. this._hookArrayForIncludedOnly(value);
  15822. },
  15823. enumerable: true,
  15824. configurable: true
  15825. });
  15826. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15827. get: function () {
  15828. return this._excludedMeshes;
  15829. },
  15830. set: function (value) {
  15831. this._excludedMeshes = value;
  15832. this._hookArrayForExcluded(value);
  15833. },
  15834. enumerable: true,
  15835. configurable: true
  15836. });
  15837. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15838. get: function () {
  15839. return this._excludeWithLayerMask;
  15840. },
  15841. set: function (value) {
  15842. this._excludeWithLayerMask = value;
  15843. this._resyncMeshes();
  15844. },
  15845. enumerable: true,
  15846. configurable: true
  15847. });
  15848. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15849. get: function () {
  15850. return this._includeOnlyWithLayerMask;
  15851. },
  15852. set: function (value) {
  15853. this._includeOnlyWithLayerMask = value;
  15854. this._resyncMeshes();
  15855. },
  15856. enumerable: true,
  15857. configurable: true
  15858. });
  15859. Object.defineProperty(Light.prototype, "lightmapMode", {
  15860. get: function () {
  15861. return this._lightmapMode;
  15862. },
  15863. set: function (value) {
  15864. if (this._lightmapMode === value) {
  15865. return;
  15866. }
  15867. this._lightmapMode = value;
  15868. this._markMeshesAsLightDirty();
  15869. },
  15870. enumerable: true,
  15871. configurable: true
  15872. });
  15873. Light.prototype._buildUniformLayout = function () {
  15874. // Overridden
  15875. };
  15876. /**
  15877. * Returns the string "Light".
  15878. */
  15879. Light.prototype.getClassName = function () {
  15880. return "Light";
  15881. };
  15882. /**
  15883. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15884. */
  15885. Light.prototype.toString = function (fullDetails) {
  15886. var ret = "Name: " + this.name;
  15887. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15888. if (this.animations) {
  15889. for (var i = 0; i < this.animations.length; i++) {
  15890. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15891. }
  15892. }
  15893. if (fullDetails) {
  15894. }
  15895. return ret;
  15896. };
  15897. /**
  15898. * Set the enabled state of this node.
  15899. * @param {boolean} value - the new enabled state
  15900. * @see isEnabled
  15901. */
  15902. Light.prototype.setEnabled = function (value) {
  15903. _super.prototype.setEnabled.call(this, value);
  15904. this._resyncMeshes();
  15905. };
  15906. /**
  15907. * Returns the Light associated shadow generator.
  15908. */
  15909. Light.prototype.getShadowGenerator = function () {
  15910. return this._shadowGenerator;
  15911. };
  15912. /**
  15913. * Returns a Vector3, the absolute light position in the World.
  15914. */
  15915. Light.prototype.getAbsolutePosition = function () {
  15916. return BABYLON.Vector3.Zero();
  15917. };
  15918. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15919. };
  15920. Light.prototype._getWorldMatrix = function () {
  15921. return BABYLON.Matrix.Identity();
  15922. };
  15923. /**
  15924. * Boolean : True if the light will affect the passed mesh.
  15925. */
  15926. Light.prototype.canAffectMesh = function (mesh) {
  15927. if (!mesh) {
  15928. return true;
  15929. }
  15930. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15931. return false;
  15932. }
  15933. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15934. return false;
  15935. }
  15936. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15937. return false;
  15938. }
  15939. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15940. return false;
  15941. }
  15942. return true;
  15943. };
  15944. /**
  15945. * Returns the light World matrix.
  15946. */
  15947. Light.prototype.getWorldMatrix = function () {
  15948. this._currentRenderId = this.getScene().getRenderId();
  15949. var worldMatrix = this._getWorldMatrix();
  15950. if (this.parent && this.parent.getWorldMatrix) {
  15951. if (!this._parentedWorldMatrix) {
  15952. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  15953. }
  15954. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  15955. this._markSyncedWithParent();
  15956. return this._parentedWorldMatrix;
  15957. }
  15958. return worldMatrix;
  15959. };
  15960. /**
  15961. * Sort function to order lights for rendering.
  15962. * @param a First Light object to compare to second.
  15963. * @param b Second Light object to compare first.
  15964. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  15965. */
  15966. Light.compareLightsPriority = function (a, b) {
  15967. //shadow-casting lights have priority over non-shadow-casting lights
  15968. //the renderPrioirty is a secondary sort criterion
  15969. if (a.shadowEnabled !== b.shadowEnabled) {
  15970. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  15971. }
  15972. return b.renderPriority - a.renderPriority;
  15973. };
  15974. /**
  15975. * Disposes the light.
  15976. */
  15977. Light.prototype.dispose = function () {
  15978. if (this._shadowGenerator) {
  15979. this._shadowGenerator.dispose();
  15980. this._shadowGenerator = null;
  15981. }
  15982. // Animations
  15983. this.getScene().stopAnimation(this);
  15984. // Remove from meshes
  15985. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15986. var mesh = _a[_i];
  15987. mesh._removeLightSource(this);
  15988. }
  15989. this._uniformBuffer.dispose();
  15990. // Remove from scene
  15991. this.getScene().removeLight(this);
  15992. _super.prototype.dispose.call(this);
  15993. };
  15994. /**
  15995. * Returns the light type ID (integer).
  15996. */
  15997. Light.prototype.getTypeID = function () {
  15998. return 0;
  15999. };
  16000. /**
  16001. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  16002. */
  16003. Light.prototype.getScaledIntensity = function () {
  16004. return this._photometricScale * this.intensity;
  16005. };
  16006. /**
  16007. * Returns a new Light object, named "name", from the current one.
  16008. */
  16009. Light.prototype.clone = function (name) {
  16010. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  16011. if (!constructor) {
  16012. return null;
  16013. }
  16014. return BABYLON.SerializationHelper.Clone(constructor, this);
  16015. };
  16016. /**
  16017. * Serializes the current light into a Serialization object.
  16018. * Returns the serialized object.
  16019. */
  16020. Light.prototype.serialize = function () {
  16021. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16022. // Type
  16023. serializationObject.type = this.getTypeID();
  16024. // Parent
  16025. if (this.parent) {
  16026. serializationObject.parentId = this.parent.id;
  16027. }
  16028. // Inclusion / exclusions
  16029. if (this.excludedMeshes.length > 0) {
  16030. serializationObject.excludedMeshesIds = [];
  16031. this.excludedMeshes.forEach(function (mesh) {
  16032. serializationObject.excludedMeshesIds.push(mesh.id);
  16033. });
  16034. }
  16035. if (this.includedOnlyMeshes.length > 0) {
  16036. serializationObject.includedOnlyMeshesIds = [];
  16037. this.includedOnlyMeshes.forEach(function (mesh) {
  16038. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  16039. });
  16040. }
  16041. // Animations
  16042. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16043. serializationObject.ranges = this.serializeAnimationRanges();
  16044. return serializationObject;
  16045. };
  16046. /**
  16047. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  16048. * This new light is named "name" and added to the passed scene.
  16049. */
  16050. Light.GetConstructorFromName = function (type, name, scene) {
  16051. switch (type) {
  16052. case 0:
  16053. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  16054. case 1:
  16055. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  16056. case 2:
  16057. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  16058. case 3:
  16059. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  16060. }
  16061. return null;
  16062. };
  16063. /**
  16064. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  16065. */
  16066. Light.Parse = function (parsedLight, scene) {
  16067. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  16068. if (!constructor) {
  16069. return null;
  16070. }
  16071. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  16072. // Inclusion / exclusions
  16073. if (parsedLight.excludedMeshesIds) {
  16074. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  16075. }
  16076. if (parsedLight.includedOnlyMeshesIds) {
  16077. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  16078. }
  16079. // Parent
  16080. if (parsedLight.parentId) {
  16081. light._waitingParentId = parsedLight.parentId;
  16082. }
  16083. // Animations
  16084. if (parsedLight.animations) {
  16085. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  16086. var parsedAnimation = parsedLight.animations[animationIndex];
  16087. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16088. }
  16089. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  16090. }
  16091. if (parsedLight.autoAnimate) {
  16092. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  16093. }
  16094. return light;
  16095. };
  16096. Light.prototype._hookArrayForExcluded = function (array) {
  16097. var _this = this;
  16098. var oldPush = array.push;
  16099. array.push = function () {
  16100. var items = [];
  16101. for (var _i = 0; _i < arguments.length; _i++) {
  16102. items[_i] = arguments[_i];
  16103. }
  16104. var result = oldPush.apply(array, items);
  16105. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  16106. var item = items_1[_a];
  16107. item._resyncLighSource(_this);
  16108. }
  16109. return result;
  16110. };
  16111. var oldSplice = array.splice;
  16112. array.splice = function (index, deleteCount) {
  16113. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16114. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  16115. var item = deleted_1[_i];
  16116. item._resyncLighSource(_this);
  16117. }
  16118. return deleted;
  16119. };
  16120. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  16121. var item = array_1[_i];
  16122. item._resyncLighSource(this);
  16123. }
  16124. };
  16125. Light.prototype._hookArrayForIncludedOnly = function (array) {
  16126. var _this = this;
  16127. var oldPush = array.push;
  16128. array.push = function () {
  16129. var items = [];
  16130. for (var _i = 0; _i < arguments.length; _i++) {
  16131. items[_i] = arguments[_i];
  16132. }
  16133. var result = oldPush.apply(array, items);
  16134. _this._resyncMeshes();
  16135. return result;
  16136. };
  16137. var oldSplice = array.splice;
  16138. array.splice = function (index, deleteCount) {
  16139. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16140. _this._resyncMeshes();
  16141. return deleted;
  16142. };
  16143. this._resyncMeshes();
  16144. };
  16145. Light.prototype._resyncMeshes = function () {
  16146. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16147. var mesh = _a[_i];
  16148. mesh._resyncLighSource(this);
  16149. }
  16150. };
  16151. Light.prototype._markMeshesAsLightDirty = function () {
  16152. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16153. var mesh = _a[_i];
  16154. if (mesh._lightSources.indexOf(this) !== -1) {
  16155. mesh._markSubMeshesAsLightDirty();
  16156. }
  16157. }
  16158. };
  16159. /**
  16160. * Recomputes the cached photometric scale if needed.
  16161. */
  16162. Light.prototype._computePhotometricScale = function () {
  16163. this._photometricScale = this._getPhotometricScale();
  16164. this.getScene().resetCachedMaterial();
  16165. };
  16166. /**
  16167. * Returns the Photometric Scale according to the light type and intensity mode.
  16168. */
  16169. Light.prototype._getPhotometricScale = function () {
  16170. var photometricScale = 0.0;
  16171. var lightTypeID = this.getTypeID();
  16172. //get photometric mode
  16173. var photometricMode = this.intensityMode;
  16174. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  16175. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  16176. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  16177. }
  16178. else {
  16179. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  16180. }
  16181. }
  16182. //compute photometric scale
  16183. switch (lightTypeID) {
  16184. case Light.LIGHTTYPEID_POINTLIGHT:
  16185. case Light.LIGHTTYPEID_SPOTLIGHT:
  16186. switch (photometricMode) {
  16187. case Light.INTENSITYMODE_LUMINOUSPOWER:
  16188. photometricScale = 1.0 / (4.0 * Math.PI);
  16189. break;
  16190. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  16191. photometricScale = 1.0;
  16192. break;
  16193. case Light.INTENSITYMODE_LUMINANCE:
  16194. photometricScale = this.radius * this.radius;
  16195. break;
  16196. }
  16197. break;
  16198. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  16199. switch (photometricMode) {
  16200. case Light.INTENSITYMODE_ILLUMINANCE:
  16201. photometricScale = 1.0;
  16202. break;
  16203. case Light.INTENSITYMODE_LUMINANCE:
  16204. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  16205. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  16206. var apexAngleRadians = this.radius;
  16207. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  16208. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  16209. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  16210. photometricScale = solidAngle;
  16211. break;
  16212. }
  16213. break;
  16214. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  16215. // No fall off in hemisperic light.
  16216. photometricScale = 1.0;
  16217. break;
  16218. }
  16219. return photometricScale;
  16220. };
  16221. Light.prototype._reorderLightsInScene = function () {
  16222. var scene = this.getScene();
  16223. if (this._renderPriority != 0) {
  16224. scene.requireLightSorting = true;
  16225. }
  16226. this.getScene().sortLightsByPriority();
  16227. };
  16228. //lightmapMode Consts
  16229. Light._LIGHTMAP_DEFAULT = 0;
  16230. Light._LIGHTMAP_SPECULAR = 1;
  16231. Light._LIGHTMAP_SHADOWSONLY = 2;
  16232. // Intensity Mode Consts
  16233. Light._INTENSITYMODE_AUTOMATIC = 0;
  16234. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  16235. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  16236. Light._INTENSITYMODE_ILLUMINANCE = 3;
  16237. Light._INTENSITYMODE_LUMINANCE = 4;
  16238. // Light types ids const.
  16239. Light._LIGHTTYPEID_POINTLIGHT = 0;
  16240. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  16241. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  16242. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  16243. __decorate([
  16244. BABYLON.serializeAsColor3()
  16245. ], Light.prototype, "diffuse", void 0);
  16246. __decorate([
  16247. BABYLON.serializeAsColor3()
  16248. ], Light.prototype, "specular", void 0);
  16249. __decorate([
  16250. BABYLON.serialize()
  16251. ], Light.prototype, "intensity", void 0);
  16252. __decorate([
  16253. BABYLON.serialize()
  16254. ], Light.prototype, "range", void 0);
  16255. __decorate([
  16256. BABYLON.serialize()
  16257. ], Light.prototype, "intensityMode", null);
  16258. __decorate([
  16259. BABYLON.serialize()
  16260. ], Light.prototype, "radius", null);
  16261. __decorate([
  16262. BABYLON.serialize()
  16263. ], Light.prototype, "_renderPriority", void 0);
  16264. __decorate([
  16265. BABYLON.expandToProperty("_reorderLightsInScene")
  16266. ], Light.prototype, "renderPriority", void 0);
  16267. __decorate([
  16268. BABYLON.serialize()
  16269. ], Light.prototype, "shadowEnabled", void 0);
  16270. __decorate([
  16271. BABYLON.serialize("excludeWithLayerMask")
  16272. ], Light.prototype, "_excludeWithLayerMask", void 0);
  16273. __decorate([
  16274. BABYLON.serialize("includeOnlyWithLayerMask")
  16275. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  16276. __decorate([
  16277. BABYLON.serialize("lightmapMode")
  16278. ], Light.prototype, "_lightmapMode", void 0);
  16279. return Light;
  16280. }(BABYLON.Node));
  16281. BABYLON.Light = Light;
  16282. })(BABYLON || (BABYLON = {}));
  16283. //# sourceMappingURL=babylon.light.js.map
  16284. var BABYLON;
  16285. (function (BABYLON) {
  16286. var Camera = /** @class */ (function (_super) {
  16287. __extends(Camera, _super);
  16288. function Camera(name, position, scene) {
  16289. var _this = _super.call(this, name, scene) || this;
  16290. _this.upVector = BABYLON.Vector3.Up();
  16291. _this.orthoLeft = null;
  16292. _this.orthoRight = null;
  16293. _this.orthoBottom = null;
  16294. _this.orthoTop = null;
  16295. _this.fov = 0.8;
  16296. _this.minZ = 1;
  16297. _this.maxZ = 10000.0;
  16298. _this.inertia = 0.9;
  16299. _this.mode = Camera.PERSPECTIVE_CAMERA;
  16300. _this.isIntermediate = false;
  16301. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  16302. _this.layerMask = 0x0FFFFFFF;
  16303. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  16304. // Camera rig members
  16305. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  16306. _this._rigCameras = new Array();
  16307. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  16308. _this._skipRendering = false;
  16309. _this.customRenderTargets = new Array();
  16310. // Observables
  16311. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  16312. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  16313. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  16314. _this.onRestoreStateObservable = new BABYLON.Observable();
  16315. // Cache
  16316. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  16317. _this._projectionMatrix = new BABYLON.Matrix();
  16318. _this._doNotComputeProjectionMatrix = false;
  16319. _this._postProcesses = new Array();
  16320. _this._transformMatrix = BABYLON.Matrix.Zero();
  16321. _this._activeMeshes = new BABYLON.SmartArray(256);
  16322. _this._globalPosition = BABYLON.Vector3.Zero();
  16323. _this._refreshFrustumPlanes = true;
  16324. _this.getScene().addCamera(_this);
  16325. if (!_this.getScene().activeCamera) {
  16326. _this.getScene().activeCamera = _this;
  16327. }
  16328. _this.position = position;
  16329. return _this;
  16330. }
  16331. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  16332. get: function () {
  16333. return Camera._PERSPECTIVE_CAMERA;
  16334. },
  16335. enumerable: true,
  16336. configurable: true
  16337. });
  16338. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  16339. get: function () {
  16340. return Camera._ORTHOGRAPHIC_CAMERA;
  16341. },
  16342. enumerable: true,
  16343. configurable: true
  16344. });
  16345. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  16346. get: function () {
  16347. return Camera._FOVMODE_VERTICAL_FIXED;
  16348. },
  16349. enumerable: true,
  16350. configurable: true
  16351. });
  16352. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  16353. get: function () {
  16354. return Camera._FOVMODE_HORIZONTAL_FIXED;
  16355. },
  16356. enumerable: true,
  16357. configurable: true
  16358. });
  16359. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  16360. get: function () {
  16361. return Camera._RIG_MODE_NONE;
  16362. },
  16363. enumerable: true,
  16364. configurable: true
  16365. });
  16366. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  16367. get: function () {
  16368. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  16369. },
  16370. enumerable: true,
  16371. configurable: true
  16372. });
  16373. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  16374. get: function () {
  16375. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  16376. },
  16377. enumerable: true,
  16378. configurable: true
  16379. });
  16380. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  16381. get: function () {
  16382. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16383. },
  16384. enumerable: true,
  16385. configurable: true
  16386. });
  16387. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  16388. get: function () {
  16389. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  16390. },
  16391. enumerable: true,
  16392. configurable: true
  16393. });
  16394. Object.defineProperty(Camera, "RIG_MODE_VR", {
  16395. get: function () {
  16396. return Camera._RIG_MODE_VR;
  16397. },
  16398. enumerable: true,
  16399. configurable: true
  16400. });
  16401. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  16402. get: function () {
  16403. return Camera._RIG_MODE_WEBVR;
  16404. },
  16405. enumerable: true,
  16406. configurable: true
  16407. });
  16408. /**
  16409. * Store current camera state (fov, position, etc..)
  16410. */
  16411. Camera.prototype.storeState = function () {
  16412. this._stateStored = true;
  16413. this._storedFov = this.fov;
  16414. return this;
  16415. };
  16416. /**
  16417. * Restores the camera state values if it has been stored. You must call storeState() first
  16418. */
  16419. Camera.prototype._restoreStateValues = function () {
  16420. if (!this._stateStored) {
  16421. return false;
  16422. }
  16423. this.fov = this._storedFov;
  16424. return true;
  16425. };
  16426. /**
  16427. * Restored camera state. You must call storeState() first
  16428. */
  16429. Camera.prototype.restoreState = function () {
  16430. if (this._restoreStateValues()) {
  16431. this.onRestoreStateObservable.notifyObservers(this);
  16432. return true;
  16433. }
  16434. return false;
  16435. };
  16436. Camera.prototype.getClassName = function () {
  16437. return "Camera";
  16438. };
  16439. /**
  16440. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16441. */
  16442. Camera.prototype.toString = function (fullDetails) {
  16443. var ret = "Name: " + this.name;
  16444. ret += ", type: " + this.getClassName();
  16445. if (this.animations) {
  16446. for (var i = 0; i < this.animations.length; i++) {
  16447. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16448. }
  16449. }
  16450. if (fullDetails) {
  16451. }
  16452. return ret;
  16453. };
  16454. Object.defineProperty(Camera.prototype, "globalPosition", {
  16455. get: function () {
  16456. return this._globalPosition;
  16457. },
  16458. enumerable: true,
  16459. configurable: true
  16460. });
  16461. Camera.prototype.getActiveMeshes = function () {
  16462. return this._activeMeshes;
  16463. };
  16464. Camera.prototype.isActiveMesh = function (mesh) {
  16465. return (this._activeMeshes.indexOf(mesh) !== -1);
  16466. };
  16467. //Cache
  16468. Camera.prototype._initCache = function () {
  16469. _super.prototype._initCache.call(this);
  16470. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16471. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16472. this._cache.mode = undefined;
  16473. this._cache.minZ = undefined;
  16474. this._cache.maxZ = undefined;
  16475. this._cache.fov = undefined;
  16476. this._cache.fovMode = undefined;
  16477. this._cache.aspectRatio = undefined;
  16478. this._cache.orthoLeft = undefined;
  16479. this._cache.orthoRight = undefined;
  16480. this._cache.orthoBottom = undefined;
  16481. this._cache.orthoTop = undefined;
  16482. this._cache.renderWidth = undefined;
  16483. this._cache.renderHeight = undefined;
  16484. };
  16485. Camera.prototype._updateCache = function (ignoreParentClass) {
  16486. if (!ignoreParentClass) {
  16487. _super.prototype._updateCache.call(this);
  16488. }
  16489. this._cache.position.copyFrom(this.position);
  16490. this._cache.upVector.copyFrom(this.upVector);
  16491. };
  16492. // Synchronized
  16493. Camera.prototype._isSynchronized = function () {
  16494. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16495. };
  16496. Camera.prototype._isSynchronizedViewMatrix = function () {
  16497. if (!_super.prototype._isSynchronized.call(this))
  16498. return false;
  16499. return this._cache.position.equals(this.position)
  16500. && this._cache.upVector.equals(this.upVector)
  16501. && this.isSynchronizedWithParent();
  16502. };
  16503. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16504. var check = this._cache.mode === this.mode
  16505. && this._cache.minZ === this.minZ
  16506. && this._cache.maxZ === this.maxZ;
  16507. if (!check) {
  16508. return false;
  16509. }
  16510. var engine = this.getEngine();
  16511. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16512. check = this._cache.fov === this.fov
  16513. && this._cache.fovMode === this.fovMode
  16514. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16515. }
  16516. else {
  16517. check = this._cache.orthoLeft === this.orthoLeft
  16518. && this._cache.orthoRight === this.orthoRight
  16519. && this._cache.orthoBottom === this.orthoBottom
  16520. && this._cache.orthoTop === this.orthoTop
  16521. && this._cache.renderWidth === engine.getRenderWidth()
  16522. && this._cache.renderHeight === engine.getRenderHeight();
  16523. }
  16524. return check;
  16525. };
  16526. // Controls
  16527. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16528. };
  16529. Camera.prototype.detachControl = function (element) {
  16530. };
  16531. Camera.prototype.update = function () {
  16532. this._checkInputs();
  16533. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16534. this._updateRigCameras();
  16535. }
  16536. };
  16537. Camera.prototype._checkInputs = function () {
  16538. this.onAfterCheckInputsObservable.notifyObservers(this);
  16539. };
  16540. Object.defineProperty(Camera.prototype, "rigCameras", {
  16541. get: function () {
  16542. return this._rigCameras;
  16543. },
  16544. enumerable: true,
  16545. configurable: true
  16546. });
  16547. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16548. get: function () {
  16549. return this._rigPostProcess;
  16550. },
  16551. enumerable: true,
  16552. configurable: true
  16553. });
  16554. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16555. // invalidate framebuffer
  16556. if (this._postProcesses.length > 0) {
  16557. this._postProcesses[0].markTextureDirty();
  16558. }
  16559. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16560. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16561. var cam = this._rigCameras[i];
  16562. var rigPostProcess = cam._rigPostProcess;
  16563. // for VR rig, there does not have to be a post process
  16564. if (rigPostProcess) {
  16565. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16566. if (isPass) {
  16567. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16568. cam.isIntermediate = this._postProcesses.length === 0;
  16569. }
  16570. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16571. rigPostProcess.markTextureDirty();
  16572. }
  16573. else {
  16574. cam._postProcesses = this._postProcesses.slice(0);
  16575. }
  16576. }
  16577. };
  16578. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16579. if (insertAt === void 0) { insertAt = null; }
  16580. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16581. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16582. return 0;
  16583. }
  16584. if (insertAt == null || insertAt < 0) {
  16585. this._postProcesses.push(postProcess);
  16586. }
  16587. else {
  16588. this._postProcesses.splice(insertAt, 0, postProcess);
  16589. }
  16590. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16591. return this._postProcesses.indexOf(postProcess);
  16592. };
  16593. Camera.prototype.detachPostProcess = function (postProcess) {
  16594. var idx = this._postProcesses.indexOf(postProcess);
  16595. if (idx !== -1) {
  16596. this._postProcesses.splice(idx, 1);
  16597. }
  16598. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16599. };
  16600. Camera.prototype.getWorldMatrix = function () {
  16601. if (!this._worldMatrix) {
  16602. this._worldMatrix = BABYLON.Matrix.Identity();
  16603. }
  16604. var viewMatrix = this.getViewMatrix();
  16605. viewMatrix.invertToRef(this._worldMatrix);
  16606. return this._worldMatrix;
  16607. };
  16608. Camera.prototype._getViewMatrix = function () {
  16609. return BABYLON.Matrix.Identity();
  16610. };
  16611. Camera.prototype.getViewMatrix = function (force) {
  16612. if (!force && this._isSynchronizedViewMatrix()) {
  16613. return this._computedViewMatrix;
  16614. }
  16615. this.updateCache();
  16616. this._computedViewMatrix = this._getViewMatrix();
  16617. this._currentRenderId = this.getScene().getRenderId();
  16618. this._refreshFrustumPlanes = true;
  16619. if (!this.parent || !this.parent.getWorldMatrix) {
  16620. this._globalPosition.copyFrom(this.position);
  16621. }
  16622. else {
  16623. if (!this._worldMatrix) {
  16624. this._worldMatrix = BABYLON.Matrix.Identity();
  16625. }
  16626. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16627. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16628. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16629. this._computedViewMatrix.invert();
  16630. this._markSyncedWithParent();
  16631. }
  16632. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16633. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16634. }
  16635. this.onViewMatrixChangedObservable.notifyObservers(this);
  16636. return this._computedViewMatrix;
  16637. };
  16638. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16639. this._doNotComputeProjectionMatrix = true;
  16640. if (projection !== undefined) {
  16641. this._projectionMatrix = projection;
  16642. }
  16643. };
  16644. ;
  16645. Camera.prototype.unfreezeProjectionMatrix = function () {
  16646. this._doNotComputeProjectionMatrix = false;
  16647. };
  16648. ;
  16649. Camera.prototype.getProjectionMatrix = function (force) {
  16650. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16651. return this._projectionMatrix;
  16652. }
  16653. // Cache
  16654. this._cache.mode = this.mode;
  16655. this._cache.minZ = this.minZ;
  16656. this._cache.maxZ = this.maxZ;
  16657. // Matrix
  16658. this._refreshFrustumPlanes = true;
  16659. var engine = this.getEngine();
  16660. var scene = this.getScene();
  16661. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16662. this._cache.fov = this.fov;
  16663. this._cache.fovMode = this.fovMode;
  16664. this._cache.aspectRatio = engine.getAspectRatio(this);
  16665. if (this.minZ <= 0) {
  16666. this.minZ = 0.1;
  16667. }
  16668. if (scene.useRightHandedSystem) {
  16669. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16670. }
  16671. else {
  16672. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16673. }
  16674. }
  16675. else {
  16676. var halfWidth = engine.getRenderWidth() / 2.0;
  16677. var halfHeight = engine.getRenderHeight() / 2.0;
  16678. if (scene.useRightHandedSystem) {
  16679. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16680. }
  16681. else {
  16682. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16683. }
  16684. this._cache.orthoLeft = this.orthoLeft;
  16685. this._cache.orthoRight = this.orthoRight;
  16686. this._cache.orthoBottom = this.orthoBottom;
  16687. this._cache.orthoTop = this.orthoTop;
  16688. this._cache.renderWidth = engine.getRenderWidth();
  16689. this._cache.renderHeight = engine.getRenderHeight();
  16690. }
  16691. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16692. return this._projectionMatrix;
  16693. };
  16694. Camera.prototype.getTranformationMatrix = function () {
  16695. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16696. return this._transformMatrix;
  16697. };
  16698. Camera.prototype.updateFrustumPlanes = function () {
  16699. if (!this._refreshFrustumPlanes) {
  16700. return;
  16701. }
  16702. this.getTranformationMatrix();
  16703. if (!this._frustumPlanes) {
  16704. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16705. }
  16706. else {
  16707. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16708. }
  16709. this._refreshFrustumPlanes = false;
  16710. };
  16711. Camera.prototype.isInFrustum = function (target) {
  16712. this.updateFrustumPlanes();
  16713. return target.isInFrustum(this._frustumPlanes);
  16714. };
  16715. Camera.prototype.isCompletelyInFrustum = function (target) {
  16716. this.updateFrustumPlanes();
  16717. return target.isCompletelyInFrustum(this._frustumPlanes);
  16718. };
  16719. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16720. if (length === void 0) { length = 100; }
  16721. if (!transform) {
  16722. transform = this.getWorldMatrix();
  16723. }
  16724. if (!origin) {
  16725. origin = this.position;
  16726. }
  16727. var forward = new BABYLON.Vector3(0, 0, 1);
  16728. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16729. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16730. return new BABYLON.Ray(origin, direction, length);
  16731. };
  16732. Camera.prototype.dispose = function () {
  16733. // Observables
  16734. this.onViewMatrixChangedObservable.clear();
  16735. this.onProjectionMatrixChangedObservable.clear();
  16736. this.onAfterCheckInputsObservable.clear();
  16737. this.onRestoreStateObservable.clear();
  16738. // Inputs
  16739. if (this.inputs) {
  16740. this.inputs.clear();
  16741. }
  16742. // Animations
  16743. this.getScene().stopAnimation(this);
  16744. // Remove from scene
  16745. this.getScene().removeCamera(this);
  16746. while (this._rigCameras.length > 0) {
  16747. var camera = this._rigCameras.pop();
  16748. if (camera) {
  16749. camera.dispose();
  16750. }
  16751. }
  16752. // Postprocesses
  16753. if (this._rigPostProcess) {
  16754. this._rigPostProcess.dispose(this);
  16755. this._rigPostProcess = null;
  16756. this._postProcesses = [];
  16757. }
  16758. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16759. this._rigPostProcess = null;
  16760. this._postProcesses = [];
  16761. }
  16762. else {
  16763. var i = this._postProcesses.length;
  16764. while (--i >= 0) {
  16765. this._postProcesses[i].dispose(this);
  16766. }
  16767. }
  16768. // Render targets
  16769. var i = this.customRenderTargets.length;
  16770. while (--i >= 0) {
  16771. this.customRenderTargets[i].dispose();
  16772. }
  16773. this.customRenderTargets = [];
  16774. // Active Meshes
  16775. this._activeMeshes.dispose();
  16776. _super.prototype.dispose.call(this);
  16777. };
  16778. Object.defineProperty(Camera.prototype, "leftCamera", {
  16779. // ---- Camera rigs section ----
  16780. get: function () {
  16781. if (this._rigCameras.length < 1) {
  16782. return null;
  16783. }
  16784. return this._rigCameras[0];
  16785. },
  16786. enumerable: true,
  16787. configurable: true
  16788. });
  16789. Object.defineProperty(Camera.prototype, "rightCamera", {
  16790. get: function () {
  16791. if (this._rigCameras.length < 2) {
  16792. return null;
  16793. }
  16794. return this._rigCameras[1];
  16795. },
  16796. enumerable: true,
  16797. configurable: true
  16798. });
  16799. Camera.prototype.getLeftTarget = function () {
  16800. if (this._rigCameras.length < 1) {
  16801. return null;
  16802. }
  16803. return this._rigCameras[0].getTarget();
  16804. };
  16805. Camera.prototype.getRightTarget = function () {
  16806. if (this._rigCameras.length < 2) {
  16807. return null;
  16808. }
  16809. return this._rigCameras[1].getTarget();
  16810. };
  16811. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16812. if (this.cameraRigMode === mode) {
  16813. return;
  16814. }
  16815. while (this._rigCameras.length > 0) {
  16816. var camera = this._rigCameras.pop();
  16817. if (camera) {
  16818. camera.dispose();
  16819. }
  16820. }
  16821. this.cameraRigMode = mode;
  16822. this._cameraRigParams = {};
  16823. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16824. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16825. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16826. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16827. // create the rig cameras, unless none
  16828. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16829. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16830. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16831. if (leftCamera && rightCamera) {
  16832. this._rigCameras.push(leftCamera);
  16833. this._rigCameras.push(rightCamera);
  16834. }
  16835. }
  16836. switch (this.cameraRigMode) {
  16837. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16838. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16839. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16840. break;
  16841. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16842. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16843. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16844. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16845. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16846. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16847. break;
  16848. case Camera.RIG_MODE_VR:
  16849. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16850. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16851. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16852. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16853. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16854. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16855. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16856. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16857. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16858. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16859. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16860. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16861. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16862. if (metrics.compensateDistortion) {
  16863. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16864. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16865. }
  16866. break;
  16867. case Camera.RIG_MODE_WEBVR:
  16868. if (rigParams.vrDisplay) {
  16869. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16870. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16871. //Left eye
  16872. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16873. this._rigCameras[0].setCameraRigParameter("left", true);
  16874. //leaving this for future reference
  16875. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16876. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16877. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16878. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16879. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16880. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16881. this._rigCameras[0].parent = this;
  16882. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16883. //Right eye
  16884. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16885. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16886. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16887. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16888. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16889. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16890. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16891. this._rigCameras[1].parent = this;
  16892. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16893. if (Camera.UseAlternateWebVRRendering) {
  16894. this._rigCameras[1]._skipRendering = true;
  16895. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16896. }
  16897. }
  16898. break;
  16899. }
  16900. this._cascadePostProcessesToRigCams();
  16901. this.update();
  16902. };
  16903. Camera.prototype._getVRProjectionMatrix = function () {
  16904. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16905. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16906. return this._projectionMatrix;
  16907. };
  16908. Camera.prototype._updateCameraRotationMatrix = function () {
  16909. //Here for WebVR
  16910. };
  16911. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16912. //Here for WebVR
  16913. };
  16914. /**
  16915. * This function MUST be overwritten by the different WebVR cameras available.
  16916. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16917. */
  16918. Camera.prototype._getWebVRProjectionMatrix = function () {
  16919. return BABYLON.Matrix.Identity();
  16920. };
  16921. /**
  16922. * This function MUST be overwritten by the different WebVR cameras available.
  16923. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16924. */
  16925. Camera.prototype._getWebVRViewMatrix = function () {
  16926. return BABYLON.Matrix.Identity();
  16927. };
  16928. Camera.prototype.setCameraRigParameter = function (name, value) {
  16929. if (!this._cameraRigParams) {
  16930. this._cameraRigParams = {};
  16931. }
  16932. this._cameraRigParams[name] = value;
  16933. //provisionnally:
  16934. if (name === "interaxialDistance") {
  16935. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16936. }
  16937. };
  16938. /**
  16939. * needs to be overridden by children so sub has required properties to be copied
  16940. */
  16941. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16942. return null;
  16943. };
  16944. /**
  16945. * May need to be overridden by children
  16946. */
  16947. Camera.prototype._updateRigCameras = function () {
  16948. for (var i = 0; i < this._rigCameras.length; i++) {
  16949. this._rigCameras[i].minZ = this.minZ;
  16950. this._rigCameras[i].maxZ = this.maxZ;
  16951. this._rigCameras[i].fov = this.fov;
  16952. }
  16953. // only update viewport when ANAGLYPH
  16954. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16955. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16956. }
  16957. };
  16958. Camera.prototype._setupInputs = function () {
  16959. };
  16960. Camera.prototype.serialize = function () {
  16961. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16962. // Type
  16963. serializationObject.type = this.getClassName();
  16964. // Parent
  16965. if (this.parent) {
  16966. serializationObject.parentId = this.parent.id;
  16967. }
  16968. if (this.inputs) {
  16969. this.inputs.serialize(serializationObject);
  16970. }
  16971. // Animations
  16972. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16973. serializationObject.ranges = this.serializeAnimationRanges();
  16974. return serializationObject;
  16975. };
  16976. Camera.prototype.clone = function (name) {
  16977. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16978. };
  16979. Camera.prototype.getDirection = function (localAxis) {
  16980. var result = BABYLON.Vector3.Zero();
  16981. this.getDirectionToRef(localAxis, result);
  16982. return result;
  16983. };
  16984. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16985. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16986. };
  16987. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16988. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16989. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16990. switch (type) {
  16991. case "ArcRotateCamera":
  16992. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16993. case "DeviceOrientationCamera":
  16994. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16995. case "FollowCamera":
  16996. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16997. case "ArcFollowCamera":
  16998. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16999. case "GamepadCamera":
  17000. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17001. case "TouchCamera":
  17002. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  17003. case "VirtualJoysticksCamera":
  17004. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  17005. case "WebVRFreeCamera":
  17006. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17007. case "WebVRGamepadCamera":
  17008. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17009. case "VRDeviceOrientationFreeCamera":
  17010. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17011. case "VRDeviceOrientationGamepadCamera":
  17012. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17013. case "AnaglyphArcRotateCamera":
  17014. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17015. case "AnaglyphFreeCamera":
  17016. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17017. case "AnaglyphGamepadCamera":
  17018. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17019. case "AnaglyphUniversalCamera":
  17020. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17021. case "StereoscopicArcRotateCamera":
  17022. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17023. case "StereoscopicFreeCamera":
  17024. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17025. case "StereoscopicGamepadCamera":
  17026. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17027. case "StereoscopicUniversalCamera":
  17028. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17029. case "FreeCamera":// Forcing Universal here
  17030. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17031. default:// Universal Camera is the default value
  17032. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17033. }
  17034. };
  17035. Camera.Parse = function (parsedCamera, scene) {
  17036. var type = parsedCamera.type;
  17037. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  17038. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  17039. // Parent
  17040. if (parsedCamera.parentId) {
  17041. camera._waitingParentId = parsedCamera.parentId;
  17042. }
  17043. //If camera has an input manager, let it parse inputs settings
  17044. if (camera.inputs) {
  17045. camera.inputs.parse(parsedCamera);
  17046. camera._setupInputs();
  17047. }
  17048. if (camera.setPosition) {
  17049. camera.position.copyFromFloats(0, 0, 0);
  17050. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  17051. }
  17052. // Target
  17053. if (parsedCamera.target) {
  17054. if (camera.setTarget) {
  17055. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17056. }
  17057. }
  17058. // Apply 3d rig, when found
  17059. if (parsedCamera.cameraRigMode) {
  17060. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  17061. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  17062. }
  17063. // Animations
  17064. if (parsedCamera.animations) {
  17065. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17066. var parsedAnimation = parsedCamera.animations[animationIndex];
  17067. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17068. }
  17069. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  17070. }
  17071. if (parsedCamera.autoAnimate) {
  17072. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  17073. }
  17074. return camera;
  17075. };
  17076. // Statics
  17077. Camera._PERSPECTIVE_CAMERA = 0;
  17078. Camera._ORTHOGRAPHIC_CAMERA = 1;
  17079. Camera._FOVMODE_VERTICAL_FIXED = 0;
  17080. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  17081. Camera._RIG_MODE_NONE = 0;
  17082. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  17083. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  17084. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  17085. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  17086. Camera._RIG_MODE_VR = 20;
  17087. Camera._RIG_MODE_WEBVR = 21;
  17088. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  17089. Camera.UseAlternateWebVRRendering = false;
  17090. __decorate([
  17091. BABYLON.serializeAsVector3()
  17092. ], Camera.prototype, "position", void 0);
  17093. __decorate([
  17094. BABYLON.serializeAsVector3()
  17095. ], Camera.prototype, "upVector", void 0);
  17096. __decorate([
  17097. BABYLON.serialize()
  17098. ], Camera.prototype, "orthoLeft", void 0);
  17099. __decorate([
  17100. BABYLON.serialize()
  17101. ], Camera.prototype, "orthoRight", void 0);
  17102. __decorate([
  17103. BABYLON.serialize()
  17104. ], Camera.prototype, "orthoBottom", void 0);
  17105. __decorate([
  17106. BABYLON.serialize()
  17107. ], Camera.prototype, "orthoTop", void 0);
  17108. __decorate([
  17109. BABYLON.serialize()
  17110. ], Camera.prototype, "fov", void 0);
  17111. __decorate([
  17112. BABYLON.serialize()
  17113. ], Camera.prototype, "minZ", void 0);
  17114. __decorate([
  17115. BABYLON.serialize()
  17116. ], Camera.prototype, "maxZ", void 0);
  17117. __decorate([
  17118. BABYLON.serialize()
  17119. ], Camera.prototype, "inertia", void 0);
  17120. __decorate([
  17121. BABYLON.serialize()
  17122. ], Camera.prototype, "mode", void 0);
  17123. __decorate([
  17124. BABYLON.serialize()
  17125. ], Camera.prototype, "layerMask", void 0);
  17126. __decorate([
  17127. BABYLON.serialize()
  17128. ], Camera.prototype, "fovMode", void 0);
  17129. __decorate([
  17130. BABYLON.serialize()
  17131. ], Camera.prototype, "cameraRigMode", void 0);
  17132. __decorate([
  17133. BABYLON.serialize()
  17134. ], Camera.prototype, "interaxialDistance", void 0);
  17135. __decorate([
  17136. BABYLON.serialize()
  17137. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  17138. return Camera;
  17139. }(BABYLON.Node));
  17140. BABYLON.Camera = Camera;
  17141. })(BABYLON || (BABYLON = {}));
  17142. //# sourceMappingURL=babylon.camera.js.map
  17143. var BABYLON;
  17144. (function (BABYLON) {
  17145. var RenderingManager = /** @class */ (function () {
  17146. function RenderingManager(scene) {
  17147. this._renderingGroups = new Array();
  17148. this._autoClearDepthStencil = {};
  17149. this._customOpaqueSortCompareFn = {};
  17150. this._customAlphaTestSortCompareFn = {};
  17151. this._customTransparentSortCompareFn = {};
  17152. this._renderinGroupInfo = null;
  17153. this._scene = scene;
  17154. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  17155. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  17156. }
  17157. }
  17158. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  17159. if (depth === void 0) { depth = true; }
  17160. if (stencil === void 0) { stencil = true; }
  17161. if (this._depthStencilBufferAlreadyCleaned) {
  17162. return;
  17163. }
  17164. this._scene.getEngine().clear(null, false, depth, stencil);
  17165. this._depthStencilBufferAlreadyCleaned = true;
  17166. };
  17167. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  17168. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  17169. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  17170. var info = null;
  17171. if (observable) {
  17172. if (!this._renderinGroupInfo) {
  17173. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  17174. }
  17175. info = this._renderinGroupInfo;
  17176. info.scene = this._scene;
  17177. info.camera = this._scene.activeCamera;
  17178. }
  17179. // Dispatch sprites
  17180. if (renderSprites) {
  17181. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  17182. var manager = this._scene.spriteManagers[index];
  17183. this.dispatchSprites(manager);
  17184. }
  17185. }
  17186. // Render
  17187. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17188. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  17189. var renderingGroup = this._renderingGroups[index];
  17190. if (!renderingGroup && !observable)
  17191. continue;
  17192. var renderingGroupMask = 0;
  17193. // Fire PRECLEAR stage
  17194. if (observable && info) {
  17195. renderingGroupMask = Math.pow(2, index);
  17196. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  17197. info.renderingGroupId = index;
  17198. observable.notifyObservers(info, renderingGroupMask);
  17199. }
  17200. // Clear depth/stencil if needed
  17201. if (RenderingManager.AUTOCLEAR) {
  17202. var autoClear = this._autoClearDepthStencil[index];
  17203. if (autoClear && autoClear.autoClear) {
  17204. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  17205. }
  17206. }
  17207. if (observable && info) {
  17208. // Fire PREOPAQUE stage
  17209. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  17210. observable.notifyObservers(info, renderingGroupMask);
  17211. // Fire PRETRANSPARENT stage
  17212. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  17213. observable.notifyObservers(info, renderingGroupMask);
  17214. }
  17215. if (renderingGroup)
  17216. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  17217. // Fire POSTTRANSPARENT stage
  17218. if (observable && info) {
  17219. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  17220. observable.notifyObservers(info, renderingGroupMask);
  17221. }
  17222. }
  17223. };
  17224. RenderingManager.prototype.reset = function () {
  17225. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17226. var renderingGroup = this._renderingGroups[index];
  17227. if (renderingGroup) {
  17228. renderingGroup.prepare();
  17229. }
  17230. }
  17231. };
  17232. RenderingManager.prototype.dispose = function () {
  17233. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17234. var renderingGroup = this._renderingGroups[index];
  17235. if (renderingGroup) {
  17236. renderingGroup.dispose();
  17237. }
  17238. }
  17239. this._renderingGroups.length = 0;
  17240. };
  17241. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  17242. if (!this._renderingGroups[renderingGroupId]) {
  17243. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  17244. }
  17245. };
  17246. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  17247. var renderingGroupId = spriteManager.renderingGroupId || 0;
  17248. this._prepareRenderingGroup(renderingGroupId);
  17249. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  17250. };
  17251. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  17252. var renderingGroupId = particleSystem.renderingGroupId || 0;
  17253. this._prepareRenderingGroup(renderingGroupId);
  17254. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  17255. };
  17256. RenderingManager.prototype.dispatch = function (subMesh) {
  17257. var mesh = subMesh.getMesh();
  17258. var renderingGroupId = mesh.renderingGroupId || 0;
  17259. this._prepareRenderingGroup(renderingGroupId);
  17260. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  17261. };
  17262. /**
  17263. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17264. * This allowed control for front to back rendering or reversly depending of the special needs.
  17265. *
  17266. * @param renderingGroupId The rendering group id corresponding to its index
  17267. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17268. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17269. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17270. */
  17271. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17272. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17273. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17274. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17275. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  17276. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  17277. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  17278. if (this._renderingGroups[renderingGroupId]) {
  17279. var group = this._renderingGroups[renderingGroupId];
  17280. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  17281. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  17282. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  17283. }
  17284. };
  17285. /**
  17286. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17287. *
  17288. * @param renderingGroupId The rendering group id corresponding to its index
  17289. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17290. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17291. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17292. */
  17293. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17294. if (depth === void 0) { depth = true; }
  17295. if (stencil === void 0) { stencil = true; }
  17296. this._autoClearDepthStencil[renderingGroupId] = {
  17297. autoClear: autoClearDepthStencil,
  17298. depth: depth,
  17299. stencil: stencil
  17300. };
  17301. };
  17302. /**
  17303. * The max id used for rendering groups (not included)
  17304. */
  17305. RenderingManager.MAX_RENDERINGGROUPS = 4;
  17306. /**
  17307. * The min id used for rendering groups (included)
  17308. */
  17309. RenderingManager.MIN_RENDERINGGROUPS = 0;
  17310. /**
  17311. * Used to globally prevent autoclearing scenes.
  17312. */
  17313. RenderingManager.AUTOCLEAR = true;
  17314. return RenderingManager;
  17315. }());
  17316. BABYLON.RenderingManager = RenderingManager;
  17317. })(BABYLON || (BABYLON = {}));
  17318. //# sourceMappingURL=babylon.renderingManager.js.map
  17319. var BABYLON;
  17320. (function (BABYLON) {
  17321. var RenderingGroup = /** @class */ (function () {
  17322. /**
  17323. * Creates a new rendering group.
  17324. * @param index The rendering group index
  17325. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  17326. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  17327. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  17328. */
  17329. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17330. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17331. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17332. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17333. this.index = index;
  17334. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  17335. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  17336. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  17337. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  17338. this._particleSystems = new BABYLON.SmartArray(256);
  17339. this._spriteManagers = new BABYLON.SmartArray(256);
  17340. this._edgesRenderers = new BABYLON.SmartArray(16);
  17341. this._scene = scene;
  17342. this.opaqueSortCompareFn = opaqueSortCompareFn;
  17343. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  17344. this.transparentSortCompareFn = transparentSortCompareFn;
  17345. }
  17346. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  17347. /**
  17348. * Set the opaque sort comparison function.
  17349. * If null the sub meshes will be render in the order they were created
  17350. */
  17351. set: function (value) {
  17352. this._opaqueSortCompareFn = value;
  17353. if (value) {
  17354. this._renderOpaque = this.renderOpaqueSorted;
  17355. }
  17356. else {
  17357. this._renderOpaque = RenderingGroup.renderUnsorted;
  17358. }
  17359. },
  17360. enumerable: true,
  17361. configurable: true
  17362. });
  17363. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  17364. /**
  17365. * Set the alpha test sort comparison function.
  17366. * If null the sub meshes will be render in the order they were created
  17367. */
  17368. set: function (value) {
  17369. this._alphaTestSortCompareFn = value;
  17370. if (value) {
  17371. this._renderAlphaTest = this.renderAlphaTestSorted;
  17372. }
  17373. else {
  17374. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  17375. }
  17376. },
  17377. enumerable: true,
  17378. configurable: true
  17379. });
  17380. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  17381. /**
  17382. * Set the transparent sort comparison function.
  17383. * If null the sub meshes will be render in the order they were created
  17384. */
  17385. set: function (value) {
  17386. if (value) {
  17387. this._transparentSortCompareFn = value;
  17388. }
  17389. else {
  17390. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  17391. }
  17392. this._renderTransparent = this.renderTransparentSorted;
  17393. },
  17394. enumerable: true,
  17395. configurable: true
  17396. });
  17397. /**
  17398. * Render all the sub meshes contained in the group.
  17399. * @param customRenderFunction Used to override the default render behaviour of the group.
  17400. * @returns true if rendered some submeshes.
  17401. */
  17402. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  17403. if (customRenderFunction) {
  17404. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  17405. return;
  17406. }
  17407. var engine = this._scene.getEngine();
  17408. // Depth only
  17409. if (this._depthOnlySubMeshes.length !== 0) {
  17410. engine.setAlphaTesting(true);
  17411. engine.setColorWrite(false);
  17412. this._renderAlphaTest(this._depthOnlySubMeshes);
  17413. engine.setAlphaTesting(false);
  17414. engine.setColorWrite(true);
  17415. }
  17416. // Opaque
  17417. if (this._opaqueSubMeshes.length !== 0) {
  17418. this._renderOpaque(this._opaqueSubMeshes);
  17419. }
  17420. // Alpha test
  17421. if (this._alphaTestSubMeshes.length !== 0) {
  17422. engine.setAlphaTesting(true);
  17423. this._renderAlphaTest(this._alphaTestSubMeshes);
  17424. engine.setAlphaTesting(false);
  17425. }
  17426. var stencilState = engine.getStencilBuffer();
  17427. engine.setStencilBuffer(false);
  17428. // Sprites
  17429. if (renderSprites) {
  17430. this._renderSprites();
  17431. }
  17432. // Particles
  17433. if (renderParticles) {
  17434. this._renderParticles(activeMeshes);
  17435. }
  17436. if (this.onBeforeTransparentRendering) {
  17437. this.onBeforeTransparentRendering();
  17438. }
  17439. // Transparent
  17440. if (this._transparentSubMeshes.length !== 0) {
  17441. this._renderTransparent(this._transparentSubMeshes);
  17442. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17443. }
  17444. // Set back stencil to false in case it changes before the edge renderer.
  17445. engine.setStencilBuffer(false);
  17446. // Edges
  17447. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17448. this._edgesRenderers.data[edgesRendererIndex].render();
  17449. }
  17450. // Restore Stencil state.
  17451. engine.setStencilBuffer(stencilState);
  17452. };
  17453. /**
  17454. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17455. * @param subMeshes The submeshes to render
  17456. */
  17457. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17458. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  17459. };
  17460. /**
  17461. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17462. * @param subMeshes The submeshes to render
  17463. */
  17464. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17465. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  17466. };
  17467. /**
  17468. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17469. * @param subMeshes The submeshes to render
  17470. */
  17471. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17472. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17473. };
  17474. /**
  17475. * Renders the submeshes in a specified order.
  17476. * @param subMeshes The submeshes to sort before render
  17477. * @param sortCompareFn The comparison function use to sort
  17478. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17479. * @param transparent Specifies to activate blending if true
  17480. */
  17481. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17482. var subIndex = 0;
  17483. var subMesh;
  17484. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17485. for (; subIndex < subMeshes.length; subIndex++) {
  17486. subMesh = subMeshes.data[subIndex];
  17487. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17488. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17489. }
  17490. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17491. if (sortCompareFn) {
  17492. sortedArray.sort(sortCompareFn);
  17493. }
  17494. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17495. subMesh = sortedArray[subIndex];
  17496. if (transparent) {
  17497. var material = subMesh.getMaterial();
  17498. if (material && material.needDepthPrePass) {
  17499. var engine = material.getScene().getEngine();
  17500. engine.setColorWrite(false);
  17501. engine.setAlphaTesting(true);
  17502. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17503. subMesh.render(false);
  17504. engine.setAlphaTesting(false);
  17505. engine.setColorWrite(true);
  17506. }
  17507. }
  17508. subMesh.render(transparent);
  17509. }
  17510. };
  17511. /**
  17512. * Renders the submeshes in the order they were dispatched (no sort applied).
  17513. * @param subMeshes The submeshes to render
  17514. */
  17515. RenderingGroup.renderUnsorted = function (subMeshes) {
  17516. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17517. var submesh = subMeshes.data[subIndex];
  17518. submesh.render(false);
  17519. }
  17520. };
  17521. /**
  17522. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17523. * are rendered back to front if in the same alpha index.
  17524. *
  17525. * @param a The first submesh
  17526. * @param b The second submesh
  17527. * @returns The result of the comparison
  17528. */
  17529. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17530. // Alpha index first
  17531. if (a._alphaIndex > b._alphaIndex) {
  17532. return 1;
  17533. }
  17534. if (a._alphaIndex < b._alphaIndex) {
  17535. return -1;
  17536. }
  17537. // Then distance to camera
  17538. return RenderingGroup.backToFrontSortCompare(a, b);
  17539. };
  17540. /**
  17541. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17542. * are rendered back to front.
  17543. *
  17544. * @param a The first submesh
  17545. * @param b The second submesh
  17546. * @returns The result of the comparison
  17547. */
  17548. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17549. // Then distance to camera
  17550. if (a._distanceToCamera < b._distanceToCamera) {
  17551. return 1;
  17552. }
  17553. if (a._distanceToCamera > b._distanceToCamera) {
  17554. return -1;
  17555. }
  17556. return 0;
  17557. };
  17558. /**
  17559. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17560. * are rendered front to back (prevent overdraw).
  17561. *
  17562. * @param a The first submesh
  17563. * @param b The second submesh
  17564. * @returns The result of the comparison
  17565. */
  17566. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17567. // Then distance to camera
  17568. if (a._distanceToCamera < b._distanceToCamera) {
  17569. return -1;
  17570. }
  17571. if (a._distanceToCamera > b._distanceToCamera) {
  17572. return 1;
  17573. }
  17574. return 0;
  17575. };
  17576. /**
  17577. * Resets the different lists of submeshes to prepare a new frame.
  17578. */
  17579. RenderingGroup.prototype.prepare = function () {
  17580. this._opaqueSubMeshes.reset();
  17581. this._transparentSubMeshes.reset();
  17582. this._alphaTestSubMeshes.reset();
  17583. this._depthOnlySubMeshes.reset();
  17584. this._particleSystems.reset();
  17585. this._spriteManagers.reset();
  17586. this._edgesRenderers.reset();
  17587. };
  17588. RenderingGroup.prototype.dispose = function () {
  17589. this._opaqueSubMeshes.dispose();
  17590. this._transparentSubMeshes.dispose();
  17591. this._alphaTestSubMeshes.dispose();
  17592. this._depthOnlySubMeshes.dispose();
  17593. this._particleSystems.dispose();
  17594. this._spriteManagers.dispose();
  17595. this._edgesRenderers.dispose();
  17596. };
  17597. /**
  17598. * Inserts the submesh in its correct queue depending on its material.
  17599. * @param subMesh The submesh to dispatch
  17600. */
  17601. RenderingGroup.prototype.dispatch = function (subMesh) {
  17602. var material = subMesh.getMaterial();
  17603. var mesh = subMesh.getMesh();
  17604. if (!material) {
  17605. return;
  17606. }
  17607. if (material.needAlphaBlendingForMesh(mesh)) {
  17608. this._transparentSubMeshes.push(subMesh);
  17609. }
  17610. else if (material.needAlphaTesting()) {
  17611. if (material.needDepthPrePass) {
  17612. this._depthOnlySubMeshes.push(subMesh);
  17613. }
  17614. this._alphaTestSubMeshes.push(subMesh);
  17615. }
  17616. else {
  17617. if (material.needDepthPrePass) {
  17618. this._depthOnlySubMeshes.push(subMesh);
  17619. }
  17620. this._opaqueSubMeshes.push(subMesh); // Opaque
  17621. }
  17622. if (mesh._edgesRenderer) {
  17623. this._edgesRenderers.push(mesh._edgesRenderer);
  17624. }
  17625. };
  17626. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17627. this._spriteManagers.push(spriteManager);
  17628. };
  17629. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17630. this._particleSystems.push(particleSystem);
  17631. };
  17632. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17633. if (this._particleSystems.length === 0) {
  17634. return;
  17635. }
  17636. // Particles
  17637. var activeCamera = this._scene.activeCamera;
  17638. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17639. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17640. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17641. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17642. continue;
  17643. }
  17644. var emitter = particleSystem.emitter;
  17645. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17646. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17647. }
  17648. }
  17649. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17650. };
  17651. RenderingGroup.prototype._renderSprites = function () {
  17652. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17653. return;
  17654. }
  17655. // Sprites
  17656. var activeCamera = this._scene.activeCamera;
  17657. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17658. for (var id = 0; id < this._spriteManagers.length; id++) {
  17659. var spriteManager = this._spriteManagers.data[id];
  17660. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17661. spriteManager.render();
  17662. }
  17663. }
  17664. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17665. };
  17666. return RenderingGroup;
  17667. }());
  17668. BABYLON.RenderingGroup = RenderingGroup;
  17669. })(BABYLON || (BABYLON = {}));
  17670. //# sourceMappingURL=babylon.renderingGroup.js.map
  17671. var BABYLON;
  17672. (function (BABYLON) {
  17673. var ClickInfo = /** @class */ (function () {
  17674. function ClickInfo() {
  17675. this._singleClick = false;
  17676. this._doubleClick = false;
  17677. this._hasSwiped = false;
  17678. this._ignore = false;
  17679. }
  17680. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17681. get: function () {
  17682. return this._singleClick;
  17683. },
  17684. set: function (b) {
  17685. this._singleClick = b;
  17686. },
  17687. enumerable: true,
  17688. configurable: true
  17689. });
  17690. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17691. get: function () {
  17692. return this._doubleClick;
  17693. },
  17694. set: function (b) {
  17695. this._doubleClick = b;
  17696. },
  17697. enumerable: true,
  17698. configurable: true
  17699. });
  17700. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17701. get: function () {
  17702. return this._hasSwiped;
  17703. },
  17704. set: function (b) {
  17705. this._hasSwiped = b;
  17706. },
  17707. enumerable: true,
  17708. configurable: true
  17709. });
  17710. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17711. get: function () {
  17712. return this._ignore;
  17713. },
  17714. set: function (b) {
  17715. this._ignore = b;
  17716. },
  17717. enumerable: true,
  17718. configurable: true
  17719. });
  17720. return ClickInfo;
  17721. }());
  17722. /**
  17723. * This class is used by the onRenderingGroupObservable
  17724. */
  17725. var RenderingGroupInfo = /** @class */ (function () {
  17726. function RenderingGroupInfo() {
  17727. }
  17728. /**
  17729. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17730. * This stage will be fired no matter what
  17731. */
  17732. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17733. /**
  17734. * Called before opaque object are rendered.
  17735. * This stage will be fired only if there's 3D Opaque content to render
  17736. */
  17737. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17738. /**
  17739. * Called after the opaque objects are rendered and before the transparent ones
  17740. * This stage will be fired only if there's 3D transparent content to render
  17741. */
  17742. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17743. /**
  17744. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17745. * This stage will be fired no matter what
  17746. */
  17747. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17748. return RenderingGroupInfo;
  17749. }());
  17750. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17751. /**
  17752. * Represents a scene to be rendered by the engine.
  17753. * @see http://doc.babylonjs.com/page.php?p=21911
  17754. */
  17755. var Scene = /** @class */ (function () {
  17756. /**
  17757. * @constructor
  17758. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17759. */
  17760. function Scene(engine) {
  17761. // Members
  17762. this.autoClear = true;
  17763. this.autoClearDepthAndStencil = true;
  17764. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17765. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17766. this.forceWireframe = false;
  17767. this._forcePointsCloud = false;
  17768. this.forceShowBoundingBoxes = false;
  17769. this.animationsEnabled = true;
  17770. this.constantlyUpdateMeshUnderPointer = false;
  17771. this.hoverCursor = "pointer";
  17772. this.defaultCursor = "";
  17773. /**
  17774. * This is used to call preventDefault() on pointer down
  17775. * in order to block unwanted artifacts like system double clicks
  17776. */
  17777. this.preventDefaultOnPointerDown = true;
  17778. // Metadata
  17779. this.metadata = null;
  17780. /**
  17781. * An event triggered when the scene is disposed.
  17782. * @type {BABYLON.Observable}
  17783. */
  17784. this.onDisposeObservable = new BABYLON.Observable();
  17785. /**
  17786. * An event triggered before rendering the scene (right after animations and physics)
  17787. * @type {BABYLON.Observable}
  17788. */
  17789. this.onBeforeRenderObservable = new BABYLON.Observable();
  17790. /**
  17791. * An event triggered after rendering the scene
  17792. * @type {BABYLON.Observable}
  17793. */
  17794. this.onAfterRenderObservable = new BABYLON.Observable();
  17795. /**
  17796. * An event triggered before animating the scene
  17797. * @type {BABYLON.Observable}
  17798. */
  17799. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  17800. /**
  17801. * An event triggered after animations processing
  17802. * @type {BABYLON.Observable}
  17803. */
  17804. this.onAfterAnimationsObservable = new BABYLON.Observable();
  17805. /**
  17806. * An event triggered before draw calls are ready to be sent
  17807. * @type {BABYLON.Observable}
  17808. */
  17809. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  17810. /**
  17811. * An event triggered after draw calls have been sent
  17812. * @type {BABYLON.Observable}
  17813. */
  17814. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  17815. /**
  17816. * An event triggered when physic simulation is about to be run
  17817. * @type {BABYLON.Observable}
  17818. */
  17819. this.onBeforePhysicsObservable = new BABYLON.Observable();
  17820. /**
  17821. * An event triggered when physic simulation has been done
  17822. * @type {BABYLON.Observable}
  17823. */
  17824. this.onAfterPhysicsObservable = new BABYLON.Observable();
  17825. /**
  17826. * An event triggered when the scene is ready
  17827. * @type {BABYLON.Observable}
  17828. */
  17829. this.onReadyObservable = new BABYLON.Observable();
  17830. /**
  17831. * An event triggered before rendering a camera
  17832. * @type {BABYLON.Observable}
  17833. */
  17834. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17835. /**
  17836. * An event triggered after rendering a camera
  17837. * @type {BABYLON.Observable}
  17838. */
  17839. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17840. /**
  17841. * An event triggered when active meshes evaluation is about to start
  17842. * @type {BABYLON.Observable}
  17843. */
  17844. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17845. /**
  17846. * An event triggered when active meshes evaluation is done
  17847. * @type {BABYLON.Observable}
  17848. */
  17849. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17850. /**
  17851. * An event triggered when particles rendering is about to start
  17852. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17853. * @type {BABYLON.Observable}
  17854. */
  17855. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  17856. /**
  17857. * An event triggered when particles rendering is done
  17858. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17859. * @type {BABYLON.Observable}
  17860. */
  17861. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  17862. /**
  17863. * An event triggered when sprites rendering is about to start
  17864. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17865. * @type {BABYLON.Observable}
  17866. */
  17867. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  17868. /**
  17869. * An event triggered when sprites rendering is done
  17870. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17871. * @type {BABYLON.Observable}
  17872. */
  17873. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  17874. /**
  17875. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  17876. * @type {BABYLON.Observable}
  17877. */
  17878. this.onDataLoadedObservable = new BABYLON.Observable();
  17879. /**
  17880. * An event triggered when a camera is created
  17881. * @type {BABYLON.Observable}
  17882. */
  17883. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17884. /**
  17885. * An event triggered when a camera is removed
  17886. * @type {BABYLON.Observable}
  17887. */
  17888. this.onCameraRemovedObservable = new BABYLON.Observable();
  17889. /**
  17890. * An event triggered when a light is created
  17891. * @type {BABYLON.Observable}
  17892. */
  17893. this.onNewLightAddedObservable = new BABYLON.Observable();
  17894. /**
  17895. * An event triggered when a light is removed
  17896. * @type {BABYLON.Observable}
  17897. */
  17898. this.onLightRemovedObservable = new BABYLON.Observable();
  17899. /**
  17900. * An event triggered when a geometry is created
  17901. * @type {BABYLON.Observable}
  17902. */
  17903. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17904. /**
  17905. * An event triggered when a geometry is removed
  17906. * @type {BABYLON.Observable}
  17907. */
  17908. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17909. /**
  17910. * An event triggered when a transform node is created
  17911. * @type {BABYLON.Observable}
  17912. */
  17913. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  17914. /**
  17915. * An event triggered when a transform node is removed
  17916. * @type {BABYLON.Observable}
  17917. */
  17918. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  17919. /**
  17920. * An event triggered when a mesh is created
  17921. * @type {BABYLON.Observable}
  17922. */
  17923. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17924. /**
  17925. * An event triggered when a mesh is removed
  17926. * @type {BABYLON.Observable}
  17927. */
  17928. this.onMeshRemovedObservable = new BABYLON.Observable();
  17929. /**
  17930. * An event triggered when render targets are about to be rendered
  17931. * Can happen multiple times per frame.
  17932. * @type {BABYLON.Observable}
  17933. */
  17934. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  17935. /**
  17936. * An event triggered when render targets were rendered.
  17937. * Can happen multiple times per frame.
  17938. * @type {BABYLON.Observable}
  17939. */
  17940. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  17941. /**
  17942. * An event triggered before calculating deterministic simulation step
  17943. * @type {BABYLON.Observable}
  17944. */
  17945. this.onBeforeStepObservable = new BABYLON.Observable();
  17946. /**
  17947. * An event triggered after calculating deterministic simulation step
  17948. * @type {BABYLON.Observable}
  17949. */
  17950. this.onAfterStepObservable = new BABYLON.Observable();
  17951. /**
  17952. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17953. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17954. * 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)
  17955. */
  17956. this.onRenderingGroupObservable = new BABYLON.Observable();
  17957. // Animations
  17958. this.animations = [];
  17959. /**
  17960. * 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).
  17961. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  17962. */
  17963. this.onPrePointerObservable = new BABYLON.Observable();
  17964. /**
  17965. * Observable event triggered each time an input event is received from the rendering canvas
  17966. */
  17967. this.onPointerObservable = new BABYLON.Observable();
  17968. this._meshPickProceed = false;
  17969. this._currentPickResult = null;
  17970. this._previousPickResult = null;
  17971. this._totalPointersPressed = 0;
  17972. this._doubleClickOccured = false;
  17973. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  17974. this.cameraToUseForPointers = null;
  17975. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17976. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  17977. this._startingPointerTime = 0;
  17978. this._previousStartingPointerTime = 0;
  17979. // Deterministic lockstep
  17980. this._timeAccumulator = 0;
  17981. this._currentStepId = 0;
  17982. this._currentInternalStep = 0;
  17983. // Keyboard
  17984. /**
  17985. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  17986. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  17987. */
  17988. this.onPreKeyboardObservable = new BABYLON.Observable();
  17989. /**
  17990. * Observable event triggered each time an keyboard event is received from the hosting window
  17991. */
  17992. this.onKeyboardObservable = new BABYLON.Observable();
  17993. // Coordinate system
  17994. /**
  17995. * use right-handed coordinate system on this scene.
  17996. * @type {boolean}
  17997. */
  17998. this._useRightHandedSystem = false;
  17999. // Fog
  18000. this._fogEnabled = true;
  18001. this._fogMode = Scene.FOGMODE_NONE;
  18002. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  18003. this.fogDensity = 0.1;
  18004. this.fogStart = 0;
  18005. this.fogEnd = 1000.0;
  18006. // Lights
  18007. /**
  18008. * is shadow enabled on this scene.
  18009. * @type {boolean}
  18010. */
  18011. this._shadowsEnabled = true;
  18012. /**
  18013. * is light enabled on this scene.
  18014. * @type {boolean}
  18015. */
  18016. this._lightsEnabled = true;
  18017. /**
  18018. * All of the lights added to this scene.
  18019. * @see BABYLON.Light
  18020. * @type {BABYLON.Light[]}
  18021. */
  18022. this.lights = new Array();
  18023. // Cameras
  18024. /** All of the cameras added to this scene. */
  18025. this.cameras = new Array();
  18026. /** All of the active cameras added to this scene. */
  18027. this.activeCameras = new Array();
  18028. // Meshes
  18029. /**
  18030. * All of the tranform nodes added to this scene.
  18031. * @see BABYLON.TransformNode
  18032. * @type {BABYLON.TransformNode[]}
  18033. */
  18034. this.transformNodes = new Array();
  18035. /**
  18036. * All of the (abstract) meshes added to this scene.
  18037. * @see BABYLON.AbstractMesh
  18038. * @type {BABYLON.AbstractMesh[]}
  18039. */
  18040. this.meshes = new Array();
  18041. // Geometries
  18042. this._geometries = new Array();
  18043. this.materials = new Array();
  18044. this.multiMaterials = new Array();
  18045. // Textures
  18046. this._texturesEnabled = true;
  18047. this.textures = new Array();
  18048. // Particles
  18049. this.particlesEnabled = true;
  18050. this.particleSystems = new Array();
  18051. // Sprites
  18052. this.spritesEnabled = true;
  18053. this.spriteManagers = new Array();
  18054. // Layers
  18055. this.layers = new Array();
  18056. this.highlightLayers = new Array();
  18057. // Skeletons
  18058. this._skeletonsEnabled = true;
  18059. this.skeletons = new Array();
  18060. // Morph targets
  18061. this.morphTargetManagers = new Array();
  18062. // Lens flares
  18063. this.lensFlaresEnabled = true;
  18064. this.lensFlareSystems = new Array();
  18065. // Collisions
  18066. this.collisionsEnabled = true;
  18067. /** Defines the gravity applied to this scene */
  18068. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  18069. // Postprocesses
  18070. this.postProcesses = new Array();
  18071. this.postProcessesEnabled = true;
  18072. // Customs render targets
  18073. this.renderTargetsEnabled = true;
  18074. this.dumpNextRenderTargets = false;
  18075. this.customRenderTargets = new Array();
  18076. // Imported meshes
  18077. this.importedMeshesFiles = new Array();
  18078. // Probes
  18079. this.probesEnabled = true;
  18080. this.reflectionProbes = new Array();
  18081. this._actionManagers = new Array();
  18082. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  18083. // Procedural textures
  18084. this.proceduralTexturesEnabled = true;
  18085. this._proceduralTextures = new Array();
  18086. this.soundTracks = new Array();
  18087. this._audioEnabled = true;
  18088. this._headphone = false;
  18089. // Performance counters
  18090. this._totalVertices = new BABYLON.PerfCounter();
  18091. this._activeIndices = new BABYLON.PerfCounter();
  18092. this._activeParticles = new BABYLON.PerfCounter();
  18093. this._activeBones = new BABYLON.PerfCounter();
  18094. this._animationTime = 0;
  18095. this.animationTimeScale = 1;
  18096. this._renderId = 0;
  18097. this._executeWhenReadyTimeoutId = -1;
  18098. this._intermediateRendering = false;
  18099. this._viewUpdateFlag = -1;
  18100. this._projectionUpdateFlag = -1;
  18101. this._alternateViewUpdateFlag = -1;
  18102. this._alternateProjectionUpdateFlag = -1;
  18103. this._toBeDisposed = new BABYLON.SmartArray(256);
  18104. this._pendingData = new Array();
  18105. this._isDisposed = false;
  18106. this._activeMeshes = new BABYLON.SmartArray(256);
  18107. this._processedMaterials = new BABYLON.SmartArray(256);
  18108. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  18109. this._activeParticleSystems = new BABYLON.SmartArray(256);
  18110. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  18111. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  18112. this._activeAnimatables = new Array();
  18113. this._transformMatrix = BABYLON.Matrix.Zero();
  18114. this._useAlternateCameraConfiguration = false;
  18115. this._alternateRendering = false;
  18116. this.requireLightSorting = false;
  18117. this._activeMeshesFrozen = false;
  18118. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  18119. this._engine.scenes.push(this);
  18120. this._uid = null;
  18121. this._renderingManager = new BABYLON.RenderingManager(this);
  18122. this.postProcessManager = new BABYLON.PostProcessManager(this);
  18123. if (BABYLON.OutlineRenderer) {
  18124. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  18125. }
  18126. if (BABYLON.Tools.IsWindowObjectExist()) {
  18127. this.attachControl();
  18128. }
  18129. //simplification queue
  18130. if (BABYLON.SimplificationQueue) {
  18131. this.simplificationQueue = new BABYLON.SimplificationQueue();
  18132. }
  18133. //collision coordinator initialization. For now legacy per default.
  18134. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  18135. // Uniform Buffer
  18136. this._createUbo();
  18137. // Default Image processing definition.
  18138. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  18139. }
  18140. Object.defineProperty(Scene, "FOGMODE_NONE", {
  18141. /** The fog is deactivated */
  18142. get: function () {
  18143. return Scene._FOGMODE_NONE;
  18144. },
  18145. enumerable: true,
  18146. configurable: true
  18147. });
  18148. Object.defineProperty(Scene, "FOGMODE_EXP", {
  18149. /** The fog density is following an exponential function */
  18150. get: function () {
  18151. return Scene._FOGMODE_EXP;
  18152. },
  18153. enumerable: true,
  18154. configurable: true
  18155. });
  18156. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  18157. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  18158. get: function () {
  18159. return Scene._FOGMODE_EXP2;
  18160. },
  18161. enumerable: true,
  18162. configurable: true
  18163. });
  18164. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  18165. /** The fog density is following a linear function. */
  18166. get: function () {
  18167. return Scene._FOGMODE_LINEAR;
  18168. },
  18169. enumerable: true,
  18170. configurable: true
  18171. });
  18172. Object.defineProperty(Scene.prototype, "environmentTexture", {
  18173. /**
  18174. * Texture used in all pbr material as the reflection texture.
  18175. * As in the majority of the scene they are the same (exception for multi room and so on),
  18176. * this is easier to reference from here than from all the materials.
  18177. */
  18178. get: function () {
  18179. return this._environmentTexture;
  18180. },
  18181. /**
  18182. * Texture used in all pbr material as the reflection texture.
  18183. * As in the majority of the scene they are the same (exception for multi room and so on),
  18184. * this is easier to set here than in all the materials.
  18185. */
  18186. set: function (value) {
  18187. if (this._environmentTexture === value) {
  18188. return;
  18189. }
  18190. this._environmentTexture = value;
  18191. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18192. },
  18193. enumerable: true,
  18194. configurable: true
  18195. });
  18196. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  18197. /**
  18198. * Default image processing configuration used either in the rendering
  18199. * Forward main pass or through the imageProcessingPostProcess if present.
  18200. * As in the majority of the scene they are the same (exception for multi camera),
  18201. * this is easier to reference from here than from all the materials and post process.
  18202. *
  18203. * No setter as we it is a shared configuration, you can set the values instead.
  18204. */
  18205. get: function () {
  18206. return this._imageProcessingConfiguration;
  18207. },
  18208. enumerable: true,
  18209. configurable: true
  18210. });
  18211. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  18212. get: function () {
  18213. return this._forcePointsCloud;
  18214. },
  18215. set: function (value) {
  18216. if (this._forcePointsCloud === value) {
  18217. return;
  18218. }
  18219. this._forcePointsCloud = value;
  18220. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18221. },
  18222. enumerable: true,
  18223. configurable: true
  18224. });
  18225. Object.defineProperty(Scene.prototype, "onDispose", {
  18226. /** A function to be executed when this scene is disposed. */
  18227. set: function (callback) {
  18228. if (this._onDisposeObserver) {
  18229. this.onDisposeObservable.remove(this._onDisposeObserver);
  18230. }
  18231. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18232. },
  18233. enumerable: true,
  18234. configurable: true
  18235. });
  18236. Object.defineProperty(Scene.prototype, "beforeRender", {
  18237. /** A function to be executed before rendering this scene */
  18238. set: function (callback) {
  18239. if (this._onBeforeRenderObserver) {
  18240. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  18241. }
  18242. if (callback) {
  18243. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  18244. }
  18245. },
  18246. enumerable: true,
  18247. configurable: true
  18248. });
  18249. Object.defineProperty(Scene.prototype, "afterRender", {
  18250. /** A function to be executed after rendering this scene */
  18251. set: function (callback) {
  18252. if (this._onAfterRenderObserver) {
  18253. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  18254. }
  18255. if (callback) {
  18256. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  18257. }
  18258. },
  18259. enumerable: true,
  18260. configurable: true
  18261. });
  18262. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  18263. set: function (callback) {
  18264. if (this._onBeforeCameraRenderObserver) {
  18265. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  18266. }
  18267. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  18268. },
  18269. enumerable: true,
  18270. configurable: true
  18271. });
  18272. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  18273. set: function (callback) {
  18274. if (this._onAfterCameraRenderObserver) {
  18275. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  18276. }
  18277. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  18278. },
  18279. enumerable: true,
  18280. configurable: true
  18281. });
  18282. Object.defineProperty(Scene.prototype, "gamepadManager", {
  18283. get: function () {
  18284. if (!this._gamepadManager) {
  18285. this._gamepadManager = new BABYLON.GamepadManager();
  18286. }
  18287. return this._gamepadManager;
  18288. },
  18289. enumerable: true,
  18290. configurable: true
  18291. });
  18292. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  18293. get: function () {
  18294. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  18295. },
  18296. enumerable: true,
  18297. configurable: true
  18298. });
  18299. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  18300. get: function () {
  18301. return this._useRightHandedSystem;
  18302. },
  18303. set: function (value) {
  18304. if (this._useRightHandedSystem === value) {
  18305. return;
  18306. }
  18307. this._useRightHandedSystem = value;
  18308. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18309. },
  18310. enumerable: true,
  18311. configurable: true
  18312. });
  18313. Scene.prototype.setStepId = function (newStepId) {
  18314. this._currentStepId = newStepId;
  18315. };
  18316. ;
  18317. Scene.prototype.getStepId = function () {
  18318. return this._currentStepId;
  18319. };
  18320. ;
  18321. Scene.prototype.getInternalStep = function () {
  18322. return this._currentInternalStep;
  18323. };
  18324. ;
  18325. Object.defineProperty(Scene.prototype, "fogEnabled", {
  18326. get: function () {
  18327. return this._fogEnabled;
  18328. },
  18329. /**
  18330. * is fog enabled on this scene.
  18331. */
  18332. set: function (value) {
  18333. if (this._fogEnabled === value) {
  18334. return;
  18335. }
  18336. this._fogEnabled = value;
  18337. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18338. },
  18339. enumerable: true,
  18340. configurable: true
  18341. });
  18342. Object.defineProperty(Scene.prototype, "fogMode", {
  18343. get: function () {
  18344. return this._fogMode;
  18345. },
  18346. set: function (value) {
  18347. if (this._fogMode === value) {
  18348. return;
  18349. }
  18350. this._fogMode = value;
  18351. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18352. },
  18353. enumerable: true,
  18354. configurable: true
  18355. });
  18356. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  18357. get: function () {
  18358. return this._shadowsEnabled;
  18359. },
  18360. set: function (value) {
  18361. if (this._shadowsEnabled === value) {
  18362. return;
  18363. }
  18364. this._shadowsEnabled = value;
  18365. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18366. },
  18367. enumerable: true,
  18368. configurable: true
  18369. });
  18370. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  18371. get: function () {
  18372. return this._lightsEnabled;
  18373. },
  18374. set: function (value) {
  18375. if (this._lightsEnabled === value) {
  18376. return;
  18377. }
  18378. this._lightsEnabled = value;
  18379. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18380. },
  18381. enumerable: true,
  18382. configurable: true
  18383. });
  18384. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  18385. /** The default material used on meshes when no material is affected */
  18386. get: function () {
  18387. if (!this._defaultMaterial) {
  18388. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  18389. }
  18390. return this._defaultMaterial;
  18391. },
  18392. /** The default material used on meshes when no material is affected */
  18393. set: function (value) {
  18394. this._defaultMaterial = value;
  18395. },
  18396. enumerable: true,
  18397. configurable: true
  18398. });
  18399. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  18400. get: function () {
  18401. return this._texturesEnabled;
  18402. },
  18403. set: function (value) {
  18404. if (this._texturesEnabled === value) {
  18405. return;
  18406. }
  18407. this._texturesEnabled = value;
  18408. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18409. },
  18410. enumerable: true,
  18411. configurable: true
  18412. });
  18413. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  18414. get: function () {
  18415. return this._skeletonsEnabled;
  18416. },
  18417. set: function (value) {
  18418. if (this._skeletonsEnabled === value) {
  18419. return;
  18420. }
  18421. this._skeletonsEnabled = value;
  18422. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  18423. },
  18424. enumerable: true,
  18425. configurable: true
  18426. });
  18427. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  18428. get: function () {
  18429. if (!this._postProcessRenderPipelineManager) {
  18430. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  18431. }
  18432. return this._postProcessRenderPipelineManager;
  18433. },
  18434. enumerable: true,
  18435. configurable: true
  18436. });
  18437. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  18438. get: function () {
  18439. if (!this._mainSoundTrack) {
  18440. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  18441. }
  18442. return this._mainSoundTrack;
  18443. },
  18444. enumerable: true,
  18445. configurable: true
  18446. });
  18447. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  18448. get: function () {
  18449. return this._alternateRendering;
  18450. },
  18451. enumerable: true,
  18452. configurable: true
  18453. });
  18454. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  18455. get: function () {
  18456. return this._frustumPlanes;
  18457. },
  18458. enumerable: true,
  18459. configurable: true
  18460. });
  18461. Object.defineProperty(Scene.prototype, "debugLayer", {
  18462. // Properties
  18463. get: function () {
  18464. if (!this._debugLayer) {
  18465. this._debugLayer = new BABYLON.DebugLayer(this);
  18466. }
  18467. return this._debugLayer;
  18468. },
  18469. enumerable: true,
  18470. configurable: true
  18471. });
  18472. Object.defineProperty(Scene.prototype, "workerCollisions", {
  18473. get: function () {
  18474. return this._workerCollisions;
  18475. },
  18476. set: function (enabled) {
  18477. if (!BABYLON.CollisionCoordinatorLegacy) {
  18478. return;
  18479. }
  18480. enabled = (enabled && !!Worker);
  18481. this._workerCollisions = enabled;
  18482. if (this.collisionCoordinator) {
  18483. this.collisionCoordinator.destroy();
  18484. }
  18485. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  18486. this.collisionCoordinator.init(this);
  18487. },
  18488. enumerable: true,
  18489. configurable: true
  18490. });
  18491. Object.defineProperty(Scene.prototype, "selectionOctree", {
  18492. get: function () {
  18493. return this._selectionOctree;
  18494. },
  18495. enumerable: true,
  18496. configurable: true
  18497. });
  18498. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  18499. /**
  18500. * The mesh that is currently under the pointer.
  18501. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  18502. */
  18503. get: function () {
  18504. return this._pointerOverMesh;
  18505. },
  18506. enumerable: true,
  18507. configurable: true
  18508. });
  18509. Object.defineProperty(Scene.prototype, "pointerX", {
  18510. /**
  18511. * Current on-screen X position of the pointer
  18512. * @return {number} X position of the pointer
  18513. */
  18514. get: function () {
  18515. return this._pointerX;
  18516. },
  18517. enumerable: true,
  18518. configurable: true
  18519. });
  18520. Object.defineProperty(Scene.prototype, "pointerY", {
  18521. /**
  18522. * Current on-screen Y position of the pointer
  18523. * @return {number} Y position of the pointer
  18524. */
  18525. get: function () {
  18526. return this._pointerY;
  18527. },
  18528. enumerable: true,
  18529. configurable: true
  18530. });
  18531. Scene.prototype.getCachedMaterial = function () {
  18532. return this._cachedMaterial;
  18533. };
  18534. Scene.prototype.getCachedEffect = function () {
  18535. return this._cachedEffect;
  18536. };
  18537. Scene.prototype.getCachedVisibility = function () {
  18538. return this._cachedVisibility;
  18539. };
  18540. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  18541. if (visibility === void 0) { visibility = 1; }
  18542. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  18543. };
  18544. Scene.prototype.getBoundingBoxRenderer = function () {
  18545. if (!this._boundingBoxRenderer) {
  18546. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18547. }
  18548. return this._boundingBoxRenderer;
  18549. };
  18550. Scene.prototype.getOutlineRenderer = function () {
  18551. return this._outlineRenderer;
  18552. };
  18553. Scene.prototype.getEngine = function () {
  18554. return this._engine;
  18555. };
  18556. Scene.prototype.getTotalVertices = function () {
  18557. return this._totalVertices.current;
  18558. };
  18559. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18560. get: function () {
  18561. return this._totalVertices;
  18562. },
  18563. enumerable: true,
  18564. configurable: true
  18565. });
  18566. Scene.prototype.getActiveIndices = function () {
  18567. return this._activeIndices.current;
  18568. };
  18569. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18570. get: function () {
  18571. return this._activeIndices;
  18572. },
  18573. enumerable: true,
  18574. configurable: true
  18575. });
  18576. Scene.prototype.getActiveParticles = function () {
  18577. return this._activeParticles.current;
  18578. };
  18579. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18580. get: function () {
  18581. return this._activeParticles;
  18582. },
  18583. enumerable: true,
  18584. configurable: true
  18585. });
  18586. Scene.prototype.getActiveBones = function () {
  18587. return this._activeBones.current;
  18588. };
  18589. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18590. get: function () {
  18591. return this._activeBones;
  18592. },
  18593. enumerable: true,
  18594. configurable: true
  18595. });
  18596. // Stats
  18597. Scene.prototype.getInterFramePerfCounter = function () {
  18598. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18599. return 0;
  18600. };
  18601. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18602. get: function () {
  18603. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18604. return null;
  18605. },
  18606. enumerable: true,
  18607. configurable: true
  18608. });
  18609. Scene.prototype.getLastFrameDuration = function () {
  18610. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18611. return 0;
  18612. };
  18613. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18614. get: function () {
  18615. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18616. return null;
  18617. },
  18618. enumerable: true,
  18619. configurable: true
  18620. });
  18621. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18622. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18623. return 0;
  18624. };
  18625. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18626. get: function () {
  18627. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18628. return null;
  18629. },
  18630. enumerable: true,
  18631. configurable: true
  18632. });
  18633. Scene.prototype.getActiveMeshes = function () {
  18634. return this._activeMeshes;
  18635. };
  18636. Scene.prototype.getRenderTargetsDuration = function () {
  18637. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18638. return 0;
  18639. };
  18640. Scene.prototype.getRenderDuration = function () {
  18641. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18642. return 0;
  18643. };
  18644. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18645. get: function () {
  18646. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18647. return null;
  18648. },
  18649. enumerable: true,
  18650. configurable: true
  18651. });
  18652. Scene.prototype.getParticlesDuration = function () {
  18653. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18654. return 0;
  18655. };
  18656. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18657. get: function () {
  18658. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18659. return null;
  18660. },
  18661. enumerable: true,
  18662. configurable: true
  18663. });
  18664. Scene.prototype.getSpritesDuration = function () {
  18665. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18666. return 0;
  18667. };
  18668. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18669. get: function () {
  18670. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18671. return null;
  18672. },
  18673. enumerable: true,
  18674. configurable: true
  18675. });
  18676. Scene.prototype.getAnimationRatio = function () {
  18677. return this._animationRatio;
  18678. };
  18679. Scene.prototype.getRenderId = function () {
  18680. return this._renderId;
  18681. };
  18682. Scene.prototype.incrementRenderId = function () {
  18683. this._renderId++;
  18684. };
  18685. Scene.prototype._updatePointerPosition = function (evt) {
  18686. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18687. if (!canvasRect) {
  18688. return;
  18689. }
  18690. this._pointerX = evt.clientX - canvasRect.left;
  18691. this._pointerY = evt.clientY - canvasRect.top;
  18692. this._unTranslatedPointerX = this._pointerX;
  18693. this._unTranslatedPointerY = this._pointerY;
  18694. };
  18695. Scene.prototype._createUbo = function () {
  18696. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18697. this._sceneUbo.addUniform("viewProjection", 16);
  18698. this._sceneUbo.addUniform("view", 16);
  18699. };
  18700. Scene.prototype._createAlternateUbo = function () {
  18701. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18702. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18703. this._alternateSceneUbo.addUniform("view", 16);
  18704. };
  18705. // Pointers handling
  18706. /**
  18707. * Use this method to simulate a pointer move on a mesh
  18708. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18709. */
  18710. Scene.prototype.simulatePointerMove = function (pickResult) {
  18711. var evt = new PointerEvent("pointermove");
  18712. return this._processPointerMove(pickResult, evt);
  18713. };
  18714. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18715. var canvas = this._engine.getRenderingCanvas();
  18716. if (!canvas) {
  18717. return this;
  18718. }
  18719. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18720. this.setPointerOverSprite(null);
  18721. this.setPointerOverMesh(pickResult.pickedMesh);
  18722. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18723. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18724. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18725. }
  18726. else {
  18727. canvas.style.cursor = this.hoverCursor;
  18728. }
  18729. }
  18730. else {
  18731. canvas.style.cursor = this.defaultCursor;
  18732. }
  18733. }
  18734. else {
  18735. this.setPointerOverMesh(null);
  18736. // Sprites
  18737. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18738. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18739. this.setPointerOverSprite(pickResult.pickedSprite);
  18740. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18741. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18742. }
  18743. else {
  18744. canvas.style.cursor = this.hoverCursor;
  18745. }
  18746. }
  18747. else {
  18748. this.setPointerOverSprite(null);
  18749. // Restore pointer
  18750. canvas.style.cursor = this.defaultCursor;
  18751. }
  18752. }
  18753. if (pickResult) {
  18754. if (this.onPointerMove) {
  18755. this.onPointerMove(evt, pickResult);
  18756. }
  18757. if (this.onPointerObservable.hasObservers()) {
  18758. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18759. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18760. this.onPointerObservable.notifyObservers(pi, type);
  18761. }
  18762. }
  18763. return this;
  18764. };
  18765. /**
  18766. * Use this method to simulate a pointer down on a mesh
  18767. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18768. */
  18769. Scene.prototype.simulatePointerDown = function (pickResult) {
  18770. var evt = new PointerEvent("pointerdown");
  18771. return this._processPointerDown(pickResult, evt);
  18772. };
  18773. Scene.prototype._processPointerDown = function (pickResult, evt) {
  18774. var _this = this;
  18775. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18776. this._pickedDownMesh = pickResult.pickedMesh;
  18777. var actionManager = pickResult.pickedMesh.actionManager;
  18778. if (actionManager) {
  18779. if (actionManager.hasPickTriggers) {
  18780. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18781. switch (evt.button) {
  18782. case 0:
  18783. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18784. break;
  18785. case 1:
  18786. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18787. break;
  18788. case 2:
  18789. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18790. break;
  18791. }
  18792. }
  18793. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18794. window.setTimeout(function () {
  18795. 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);
  18796. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18797. if (_this._totalPointersPressed !== 0 &&
  18798. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18799. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18800. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18801. _this._startingPointerTime = 0;
  18802. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18803. }
  18804. }
  18805. }, Scene.LongPressDelay);
  18806. }
  18807. }
  18808. }
  18809. if (pickResult) {
  18810. if (this.onPointerDown) {
  18811. this.onPointerDown(evt, pickResult);
  18812. }
  18813. if (this.onPointerObservable.hasObservers()) {
  18814. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18815. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18816. this.onPointerObservable.notifyObservers(pi, type);
  18817. }
  18818. }
  18819. return this;
  18820. };
  18821. /**
  18822. * Use this method to simulate a pointer up on a mesh
  18823. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18824. */
  18825. Scene.prototype.simulatePointerUp = function (pickResult) {
  18826. var evt = new PointerEvent("pointerup");
  18827. var clickInfo = new ClickInfo();
  18828. clickInfo.singleClick = true;
  18829. return this._processPointerUp(pickResult, evt, clickInfo);
  18830. };
  18831. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18832. if (pickResult && pickResult && pickResult.pickedMesh) {
  18833. this._pickedUpMesh = pickResult.pickedMesh;
  18834. if (this._pickedDownMesh === this._pickedUpMesh) {
  18835. if (this.onPointerPick) {
  18836. this.onPointerPick(evt, pickResult);
  18837. }
  18838. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18839. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18840. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18841. this.onPointerObservable.notifyObservers(pi, type);
  18842. }
  18843. }
  18844. if (pickResult.pickedMesh.actionManager) {
  18845. if (clickInfo.ignore) {
  18846. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18847. }
  18848. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18849. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18850. }
  18851. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18852. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18853. }
  18854. }
  18855. }
  18856. if (this._pickedDownMesh &&
  18857. this._pickedDownMesh.actionManager &&
  18858. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18859. this._pickedDownMesh !== this._pickedUpMesh) {
  18860. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18861. }
  18862. if (this.onPointerUp) {
  18863. this.onPointerUp(evt, pickResult);
  18864. }
  18865. if (this.onPointerObservable.hasObservers()) {
  18866. if (!clickInfo.ignore) {
  18867. if (!clickInfo.hasSwiped) {
  18868. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18869. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18870. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18871. this.onPointerObservable.notifyObservers(pi, type);
  18872. }
  18873. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18874. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18875. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18876. this.onPointerObservable.notifyObservers(pi, type);
  18877. }
  18878. }
  18879. }
  18880. else {
  18881. var type = BABYLON.PointerEventTypes.POINTERUP;
  18882. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18883. this.onPointerObservable.notifyObservers(pi, type);
  18884. }
  18885. }
  18886. return this;
  18887. };
  18888. /**
  18889. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18890. * @param attachUp defines if you want to attach events to pointerup
  18891. * @param attachDown defines if you want to attach events to pointerdown
  18892. * @param attachMove defines if you want to attach events to pointermove
  18893. */
  18894. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18895. var _this = this;
  18896. if (attachUp === void 0) { attachUp = true; }
  18897. if (attachDown === void 0) { attachDown = true; }
  18898. if (attachMove === void 0) { attachMove = true; }
  18899. this._initActionManager = function (act, clickInfo) {
  18900. if (!_this._meshPickProceed) {
  18901. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18902. _this._currentPickResult = pickResult;
  18903. if (pickResult) {
  18904. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18905. }
  18906. _this._meshPickProceed = true;
  18907. }
  18908. return act;
  18909. };
  18910. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18911. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  18912. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  18913. btn !== _this._previousButtonPressed) {
  18914. _this._doubleClickOccured = false;
  18915. clickInfo.singleClick = true;
  18916. clickInfo.ignore = false;
  18917. cb(clickInfo, _this._currentPickResult);
  18918. }
  18919. };
  18920. this._initClickEvent = function (obs1, obs2, evt, cb) {
  18921. var clickInfo = new ClickInfo();
  18922. _this._currentPickResult = null;
  18923. var act = null;
  18924. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  18925. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  18926. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18927. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  18928. act = _this._initActionManager(act, clickInfo);
  18929. if (act)
  18930. checkPicking = act.hasPickTriggers;
  18931. }
  18932. if (checkPicking) {
  18933. var btn = evt.button;
  18934. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18935. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18936. if (!clickInfo.hasSwiped) {
  18937. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  18938. if (!checkSingleClickImmediately) {
  18939. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  18940. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18941. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18942. act = _this._initActionManager(act, clickInfo);
  18943. if (act)
  18944. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18945. }
  18946. }
  18947. if (checkSingleClickImmediately) {
  18948. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  18949. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  18950. btn !== _this._previousButtonPressed) {
  18951. clickInfo.singleClick = true;
  18952. cb(clickInfo, _this._currentPickResult);
  18953. }
  18954. }
  18955. else {
  18956. // wait that no double click has been raised during the double click delay
  18957. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18958. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  18959. }
  18960. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  18961. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18962. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18963. act = _this._initActionManager(act, clickInfo);
  18964. if (act)
  18965. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18966. }
  18967. if (checkDoubleClick) {
  18968. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  18969. if (btn === _this._previousButtonPressed &&
  18970. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  18971. !_this._doubleClickOccured) {
  18972. // pointer has not moved for 2 clicks, it's a double click
  18973. if (!clickInfo.hasSwiped &&
  18974. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  18975. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  18976. _this._previousStartingPointerTime = 0;
  18977. _this._doubleClickOccured = true;
  18978. clickInfo.doubleClick = true;
  18979. clickInfo.ignore = false;
  18980. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  18981. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18982. }
  18983. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18984. cb(clickInfo, _this._currentPickResult);
  18985. }
  18986. else {
  18987. _this._doubleClickOccured = false;
  18988. _this._previousStartingPointerTime = _this._startingPointerTime;
  18989. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18990. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18991. _this._previousButtonPressed = btn;
  18992. if (Scene.ExclusiveDoubleClickMode) {
  18993. if (_this._previousDelayedSimpleClickTimeout) {
  18994. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18995. }
  18996. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18997. cb(clickInfo, _this._previousPickResult);
  18998. }
  18999. else {
  19000. cb(clickInfo, _this._currentPickResult);
  19001. }
  19002. }
  19003. }
  19004. else {
  19005. _this._doubleClickOccured = false;
  19006. _this._previousStartingPointerTime = _this._startingPointerTime;
  19007. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19008. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19009. _this._previousButtonPressed = btn;
  19010. }
  19011. }
  19012. }
  19013. }
  19014. clickInfo.ignore = true;
  19015. cb(clickInfo, _this._currentPickResult);
  19016. };
  19017. this._spritePredicate = function (sprite) {
  19018. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  19019. };
  19020. this._onPointerMove = function (evt) {
  19021. _this._updatePointerPosition(evt);
  19022. // PreObservable support
  19023. if (_this.onPrePointerObservable.hasObservers()) {
  19024. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  19025. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19026. _this.onPrePointerObservable.notifyObservers(pi, type);
  19027. if (pi.skipOnPointerObservable) {
  19028. return;
  19029. }
  19030. }
  19031. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19032. return;
  19033. }
  19034. if (!_this.pointerMovePredicate) {
  19035. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  19036. }
  19037. // Meshes
  19038. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  19039. _this._processPointerMove(pickResult, evt);
  19040. };
  19041. this._onPointerDown = function (evt) {
  19042. _this._totalPointersPressed++;
  19043. _this._pickedDownMesh = null;
  19044. _this._meshPickProceed = false;
  19045. _this._updatePointerPosition(evt);
  19046. if (_this.preventDefaultOnPointerDown && canvas) {
  19047. evt.preventDefault();
  19048. canvas.focus();
  19049. }
  19050. // PreObservable support
  19051. if (_this.onPrePointerObservable.hasObservers()) {
  19052. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  19053. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19054. _this.onPrePointerObservable.notifyObservers(pi, type);
  19055. if (pi.skipOnPointerObservable) {
  19056. return;
  19057. }
  19058. }
  19059. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19060. return;
  19061. }
  19062. _this._startingPointerPosition.x = _this._pointerX;
  19063. _this._startingPointerPosition.y = _this._pointerY;
  19064. _this._startingPointerTime = new Date().getTime();
  19065. if (!_this.pointerDownPredicate) {
  19066. _this.pointerDownPredicate = function (mesh) {
  19067. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19068. };
  19069. }
  19070. // Meshes
  19071. _this._pickedDownMesh = null;
  19072. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19073. _this._processPointerDown(pickResult, evt);
  19074. // Sprites
  19075. _this._pickedDownSprite = null;
  19076. if (_this.spriteManagers.length > 0) {
  19077. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19078. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  19079. if (pickResult.pickedSprite.actionManager) {
  19080. _this._pickedDownSprite = pickResult.pickedSprite;
  19081. switch (evt.button) {
  19082. case 0:
  19083. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19084. break;
  19085. case 1:
  19086. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19087. break;
  19088. case 2:
  19089. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19090. break;
  19091. }
  19092. if (pickResult.pickedSprite.actionManager) {
  19093. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19094. }
  19095. }
  19096. }
  19097. }
  19098. };
  19099. this._onPointerUp = function (evt) {
  19100. if (_this._totalPointersPressed === 0) {
  19101. return; // So we need to test it the pointer down was pressed before.
  19102. }
  19103. _this._totalPointersPressed--;
  19104. _this._pickedUpMesh = null;
  19105. _this._meshPickProceed = false;
  19106. _this._updatePointerPosition(evt);
  19107. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  19108. // PreObservable support
  19109. if (_this.onPrePointerObservable.hasObservers()) {
  19110. if (!clickInfo.ignore) {
  19111. if (!clickInfo.hasSwiped) {
  19112. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19113. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19114. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19115. _this.onPrePointerObservable.notifyObservers(pi, type);
  19116. if (pi.skipOnPointerObservable) {
  19117. return;
  19118. }
  19119. }
  19120. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19121. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19122. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19123. _this.onPrePointerObservable.notifyObservers(pi, type);
  19124. if (pi.skipOnPointerObservable) {
  19125. return;
  19126. }
  19127. }
  19128. }
  19129. }
  19130. else {
  19131. var type = BABYLON.PointerEventTypes.POINTERUP;
  19132. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19133. _this.onPrePointerObservable.notifyObservers(pi, type);
  19134. if (pi.skipOnPointerObservable) {
  19135. return;
  19136. }
  19137. }
  19138. }
  19139. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19140. return;
  19141. }
  19142. if (!_this.pointerUpPredicate) {
  19143. _this.pointerUpPredicate = function (mesh) {
  19144. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19145. };
  19146. }
  19147. // Meshes
  19148. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  19149. _this._initActionManager(null, clickInfo);
  19150. }
  19151. if (!pickResult) {
  19152. pickResult = _this._currentPickResult;
  19153. }
  19154. _this._processPointerUp(pickResult, evt, clickInfo);
  19155. // Sprites
  19156. if (_this.spriteManagers.length > 0) {
  19157. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19158. if (spritePickResult) {
  19159. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  19160. if (spritePickResult.pickedSprite.actionManager) {
  19161. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19162. if (spritePickResult.pickedSprite.actionManager) {
  19163. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  19164. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19165. }
  19166. }
  19167. }
  19168. }
  19169. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  19170. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  19171. }
  19172. }
  19173. }
  19174. _this._previousPickResult = _this._currentPickResult;
  19175. });
  19176. };
  19177. this._onKeyDown = function (evt) {
  19178. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  19179. if (_this.onPreKeyboardObservable.hasObservers()) {
  19180. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19181. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19182. if (pi.skipOnPointerObservable) {
  19183. return;
  19184. }
  19185. }
  19186. if (_this.onKeyboardObservable.hasObservers()) {
  19187. var pi = new BABYLON.KeyboardInfo(type, evt);
  19188. _this.onKeyboardObservable.notifyObservers(pi, type);
  19189. }
  19190. if (_this.actionManager) {
  19191. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19192. }
  19193. };
  19194. this._onKeyUp = function (evt) {
  19195. var type = BABYLON.KeyboardEventTypes.KEYUP;
  19196. if (_this.onPreKeyboardObservable.hasObservers()) {
  19197. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19198. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19199. if (pi.skipOnPointerObservable) {
  19200. return;
  19201. }
  19202. }
  19203. if (_this.onKeyboardObservable.hasObservers()) {
  19204. var pi = new BABYLON.KeyboardInfo(type, evt);
  19205. _this.onKeyboardObservable.notifyObservers(pi, type);
  19206. }
  19207. if (_this.actionManager) {
  19208. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19209. }
  19210. };
  19211. var engine = this.getEngine();
  19212. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  19213. if (!canvas) {
  19214. return;
  19215. }
  19216. canvas.addEventListener("keydown", _this._onKeyDown, false);
  19217. canvas.addEventListener("keyup", _this._onKeyUp, false);
  19218. });
  19219. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  19220. if (!canvas) {
  19221. return;
  19222. }
  19223. canvas.removeEventListener("keydown", _this._onKeyDown);
  19224. canvas.removeEventListener("keyup", _this._onKeyUp);
  19225. });
  19226. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19227. var canvas = this._engine.getRenderingCanvas();
  19228. if (!canvas) {
  19229. return;
  19230. }
  19231. if (attachMove) {
  19232. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  19233. // Wheel
  19234. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  19235. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  19236. }
  19237. if (attachDown) {
  19238. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  19239. }
  19240. if (attachUp) {
  19241. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  19242. }
  19243. canvas.tabIndex = 1;
  19244. };
  19245. Scene.prototype.detachControl = function () {
  19246. var engine = this.getEngine();
  19247. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19248. var canvas = engine.getRenderingCanvas();
  19249. if (!canvas) {
  19250. return;
  19251. }
  19252. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  19253. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  19254. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  19255. if (this._onCanvasBlurObserver) {
  19256. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  19257. }
  19258. if (this._onCanvasFocusObserver) {
  19259. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  19260. }
  19261. // Wheel
  19262. canvas.removeEventListener('mousewheel', this._onPointerMove);
  19263. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  19264. // Keyboard
  19265. canvas.removeEventListener("keydown", this._onKeyDown);
  19266. canvas.removeEventListener("keyup", this._onKeyUp);
  19267. // Observables
  19268. this.onKeyboardObservable.clear();
  19269. this.onPreKeyboardObservable.clear();
  19270. this.onPointerObservable.clear();
  19271. this.onPrePointerObservable.clear();
  19272. };
  19273. // Ready
  19274. Scene.prototype.isReady = function () {
  19275. if (this._isDisposed) {
  19276. return false;
  19277. }
  19278. if (this._pendingData.length > 0) {
  19279. return false;
  19280. }
  19281. var index;
  19282. // Geometries
  19283. for (index = 0; index < this._geometries.length; index++) {
  19284. var geometry = this._geometries[index];
  19285. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19286. return false;
  19287. }
  19288. }
  19289. // Meshes
  19290. for (index = 0; index < this.meshes.length; index++) {
  19291. var mesh = this.meshes[index];
  19292. if (!mesh.isEnabled()) {
  19293. continue;
  19294. }
  19295. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19296. continue;
  19297. }
  19298. if (!mesh.isReady()) {
  19299. return false;
  19300. }
  19301. var mat = mesh.material;
  19302. if (mat) {
  19303. if (!mat.isReady(mesh)) {
  19304. return false;
  19305. }
  19306. }
  19307. }
  19308. return true;
  19309. };
  19310. Scene.prototype.resetCachedMaterial = function () {
  19311. this._cachedMaterial = null;
  19312. this._cachedEffect = null;
  19313. this._cachedVisibility = null;
  19314. };
  19315. Scene.prototype.registerBeforeRender = function (func) {
  19316. this.onBeforeRenderObservable.add(func);
  19317. };
  19318. Scene.prototype.unregisterBeforeRender = function (func) {
  19319. this.onBeforeRenderObservable.removeCallback(func);
  19320. };
  19321. Scene.prototype.registerAfterRender = function (func) {
  19322. this.onAfterRenderObservable.add(func);
  19323. };
  19324. Scene.prototype.unregisterAfterRender = function (func) {
  19325. this.onAfterRenderObservable.removeCallback(func);
  19326. };
  19327. Scene.prototype._addPendingData = function (data) {
  19328. this._pendingData.push(data);
  19329. };
  19330. Scene.prototype._removePendingData = function (data) {
  19331. var wasLoading = this.isLoading;
  19332. var index = this._pendingData.indexOf(data);
  19333. if (index !== -1) {
  19334. this._pendingData.splice(index, 1);
  19335. }
  19336. if (wasLoading && !this.isLoading) {
  19337. this.onDataLoadedObservable.notifyObservers(this);
  19338. }
  19339. };
  19340. Scene.prototype.getWaitingItemsCount = function () {
  19341. return this._pendingData.length;
  19342. };
  19343. Object.defineProperty(Scene.prototype, "isLoading", {
  19344. get: function () {
  19345. return this._pendingData.length > 0;
  19346. },
  19347. enumerable: true,
  19348. configurable: true
  19349. });
  19350. /**
  19351. * Registers a function to be executed when the scene is ready.
  19352. * @param {Function} func - the function to be executed.
  19353. */
  19354. Scene.prototype.executeWhenReady = function (func) {
  19355. var _this = this;
  19356. this.onReadyObservable.add(func);
  19357. if (this._executeWhenReadyTimeoutId !== -1) {
  19358. return;
  19359. }
  19360. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19361. _this._checkIsReady();
  19362. }, 150);
  19363. };
  19364. Scene.prototype._checkIsReady = function () {
  19365. var _this = this;
  19366. if (this.isReady()) {
  19367. this.onReadyObservable.notifyObservers(this);
  19368. this.onReadyObservable.clear();
  19369. this._executeWhenReadyTimeoutId = -1;
  19370. return;
  19371. }
  19372. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19373. _this._checkIsReady();
  19374. }, 150);
  19375. };
  19376. // Animations
  19377. /**
  19378. * Will start the animation sequence of a given target
  19379. * @param target - the target
  19380. * @param {number} from - from which frame should animation start
  19381. * @param {number} to - till which frame should animation run.
  19382. * @param {boolean} [loop] - should the animation loop
  19383. * @param {number} [speedRatio] - the speed in which to run the animation
  19384. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  19385. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  19386. * Returns {BABYLON.Animatable} the animatable object created for this animation
  19387. * See BABYLON.Animatable
  19388. */
  19389. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  19390. if (speedRatio === void 0) { speedRatio = 1.0; }
  19391. if (from > to && speedRatio > 0) {
  19392. speedRatio *= -1;
  19393. }
  19394. this.stopAnimation(target);
  19395. if (!animatable) {
  19396. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  19397. }
  19398. // Local animations
  19399. if (target.animations) {
  19400. animatable.appendAnimations(target, target.animations);
  19401. }
  19402. // Children animations
  19403. if (target.getAnimatables) {
  19404. var animatables = target.getAnimatables();
  19405. for (var index = 0; index < animatables.length; index++) {
  19406. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  19407. }
  19408. }
  19409. animatable.reset();
  19410. return animatable;
  19411. };
  19412. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  19413. if (speedRatio === undefined) {
  19414. speedRatio = 1.0;
  19415. }
  19416. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  19417. return animatable;
  19418. };
  19419. Scene.prototype.getAnimatableByTarget = function (target) {
  19420. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19421. if (this._activeAnimatables[index].target === target) {
  19422. return this._activeAnimatables[index];
  19423. }
  19424. }
  19425. return null;
  19426. };
  19427. Object.defineProperty(Scene.prototype, "Animatables", {
  19428. get: function () {
  19429. return this._activeAnimatables;
  19430. },
  19431. enumerable: true,
  19432. configurable: true
  19433. });
  19434. /**
  19435. * Will stop the animation of the given target
  19436. * @param target - the target
  19437. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  19438. * @see beginAnimation
  19439. */
  19440. Scene.prototype.stopAnimation = function (target, animationName) {
  19441. var animatable = this.getAnimatableByTarget(target);
  19442. if (animatable) {
  19443. animatable.stop(animationName);
  19444. }
  19445. };
  19446. /**
  19447. * Stops and removes all animations that have been applied to the scene
  19448. */
  19449. Scene.prototype.stopAllAnimations = function () {
  19450. if (this._activeAnimatables) {
  19451. for (var i = 0; i < this._activeAnimatables.length; i++) {
  19452. this._activeAnimatables[i].stop();
  19453. }
  19454. this._activeAnimatables = [];
  19455. }
  19456. };
  19457. Scene.prototype._animate = function () {
  19458. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  19459. return;
  19460. }
  19461. // Getting time
  19462. var now = BABYLON.Tools.Now;
  19463. if (!this._animationTimeLast) {
  19464. if (this._pendingData.length > 0) {
  19465. return;
  19466. }
  19467. this._animationTimeLast = now;
  19468. }
  19469. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  19470. this._animationTime += deltaTime;
  19471. this._animationTimeLast = now;
  19472. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19473. this._activeAnimatables[index]._animate(this._animationTime);
  19474. }
  19475. };
  19476. // Matrix
  19477. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  19478. this._useAlternateCameraConfiguration = active;
  19479. };
  19480. Scene.prototype.getViewMatrix = function () {
  19481. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  19482. };
  19483. Scene.prototype.getProjectionMatrix = function () {
  19484. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  19485. };
  19486. Scene.prototype.getTransformMatrix = function () {
  19487. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  19488. };
  19489. Scene.prototype.setTransformMatrix = function (view, projection) {
  19490. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  19491. return;
  19492. }
  19493. this._viewUpdateFlag = view.updateFlag;
  19494. this._projectionUpdateFlag = projection.updateFlag;
  19495. this._viewMatrix = view;
  19496. this._projectionMatrix = projection;
  19497. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19498. // Update frustum
  19499. if (!this._frustumPlanes) {
  19500. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19501. }
  19502. else {
  19503. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19504. }
  19505. if (this.activeCamera && this.activeCamera._alternateCamera) {
  19506. var otherCamera = this.activeCamera._alternateCamera;
  19507. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  19508. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  19509. }
  19510. if (this._sceneUbo.useUbo) {
  19511. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  19512. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  19513. this._sceneUbo.update();
  19514. }
  19515. };
  19516. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  19517. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  19518. return;
  19519. }
  19520. this._alternateViewUpdateFlag = view.updateFlag;
  19521. this._alternateProjectionUpdateFlag = projection.updateFlag;
  19522. this._alternateViewMatrix = view;
  19523. this._alternateProjectionMatrix = projection;
  19524. if (!this._alternateTransformMatrix) {
  19525. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  19526. }
  19527. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  19528. if (!this._alternateSceneUbo) {
  19529. this._createAlternateUbo();
  19530. }
  19531. if (this._alternateSceneUbo.useUbo) {
  19532. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  19533. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  19534. this._alternateSceneUbo.update();
  19535. }
  19536. };
  19537. Scene.prototype.getSceneUniformBuffer = function () {
  19538. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  19539. };
  19540. // Methods
  19541. Scene.prototype.getUniqueId = function () {
  19542. var result = Scene._uniqueIdCounter;
  19543. Scene._uniqueIdCounter++;
  19544. return result;
  19545. };
  19546. Scene.prototype.addMesh = function (newMesh) {
  19547. this.meshes.push(newMesh);
  19548. //notify the collision coordinator
  19549. if (this.collisionCoordinator) {
  19550. this.collisionCoordinator.onMeshAdded(newMesh);
  19551. }
  19552. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  19553. };
  19554. Scene.prototype.removeMesh = function (toRemove) {
  19555. var index = this.meshes.indexOf(toRemove);
  19556. if (index !== -1) {
  19557. // Remove from the scene if mesh found
  19558. this.meshes.splice(index, 1);
  19559. }
  19560. this.onMeshRemovedObservable.notifyObservers(toRemove);
  19561. return index;
  19562. };
  19563. Scene.prototype.addTransformNode = function (newTransformNode) {
  19564. this.transformNodes.push(newTransformNode);
  19565. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  19566. };
  19567. Scene.prototype.removeTransformNode = function (toRemove) {
  19568. var index = this.transformNodes.indexOf(toRemove);
  19569. if (index !== -1) {
  19570. // Remove from the scene if found
  19571. this.transformNodes.splice(index, 1);
  19572. }
  19573. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  19574. return index;
  19575. };
  19576. Scene.prototype.removeSkeleton = function (toRemove) {
  19577. var index = this.skeletons.indexOf(toRemove);
  19578. if (index !== -1) {
  19579. // Remove from the scene if found
  19580. this.skeletons.splice(index, 1);
  19581. }
  19582. return index;
  19583. };
  19584. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19585. var index = this.morphTargetManagers.indexOf(toRemove);
  19586. if (index !== -1) {
  19587. // Remove from the scene if found
  19588. this.morphTargetManagers.splice(index, 1);
  19589. }
  19590. return index;
  19591. };
  19592. Scene.prototype.removeLight = function (toRemove) {
  19593. var index = this.lights.indexOf(toRemove);
  19594. if (index !== -1) {
  19595. // Remove from the scene if mesh found
  19596. this.lights.splice(index, 1);
  19597. this.sortLightsByPriority();
  19598. }
  19599. this.onLightRemovedObservable.notifyObservers(toRemove);
  19600. return index;
  19601. };
  19602. Scene.prototype.removeCamera = function (toRemove) {
  19603. var index = this.cameras.indexOf(toRemove);
  19604. if (index !== -1) {
  19605. // Remove from the scene if mesh found
  19606. this.cameras.splice(index, 1);
  19607. }
  19608. // Remove from activeCameras
  19609. var index2 = this.activeCameras.indexOf(toRemove);
  19610. if (index2 !== -1) {
  19611. // Remove from the scene if mesh found
  19612. this.activeCameras.splice(index2, 1);
  19613. }
  19614. // Reset the activeCamera
  19615. if (this.activeCamera === toRemove) {
  19616. if (this.cameras.length > 0) {
  19617. this.activeCamera = this.cameras[0];
  19618. }
  19619. else {
  19620. this.activeCamera = null;
  19621. }
  19622. }
  19623. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19624. return index;
  19625. };
  19626. Scene.prototype.addLight = function (newLight) {
  19627. this.lights.push(newLight);
  19628. this.sortLightsByPriority();
  19629. this.onNewLightAddedObservable.notifyObservers(newLight);
  19630. };
  19631. Scene.prototype.sortLightsByPriority = function () {
  19632. if (this.requireLightSorting) {
  19633. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19634. }
  19635. };
  19636. Scene.prototype.addCamera = function (newCamera) {
  19637. this.cameras.push(newCamera);
  19638. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19639. };
  19640. /**
  19641. * Switch active camera
  19642. * @param {Camera} newCamera - new active camera
  19643. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19644. */
  19645. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19646. if (attachControl === void 0) { attachControl = true; }
  19647. var canvas = this._engine.getRenderingCanvas();
  19648. if (!canvas) {
  19649. return;
  19650. }
  19651. if (this.activeCamera) {
  19652. this.activeCamera.detachControl(canvas);
  19653. }
  19654. this.activeCamera = newCamera;
  19655. if (attachControl) {
  19656. newCamera.attachControl(canvas);
  19657. }
  19658. };
  19659. /**
  19660. * sets the active camera of the scene using its ID
  19661. * @param {string} id - the camera's ID
  19662. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19663. * @see activeCamera
  19664. */
  19665. Scene.prototype.setActiveCameraByID = function (id) {
  19666. var camera = this.getCameraByID(id);
  19667. if (camera) {
  19668. this.activeCamera = camera;
  19669. return camera;
  19670. }
  19671. return null;
  19672. };
  19673. /**
  19674. * sets the active camera of the scene using its name
  19675. * @param {string} name - the camera's name
  19676. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19677. * @see activeCamera
  19678. */
  19679. Scene.prototype.setActiveCameraByName = function (name) {
  19680. var camera = this.getCameraByName(name);
  19681. if (camera) {
  19682. this.activeCamera = camera;
  19683. return camera;
  19684. }
  19685. return null;
  19686. };
  19687. /**
  19688. * get a material using its id
  19689. * @param {string} the material's ID
  19690. * @return {BABYLON.Material|null} the material or null if none found.
  19691. */
  19692. Scene.prototype.getMaterialByID = function (id) {
  19693. for (var index = 0; index < this.materials.length; index++) {
  19694. if (this.materials[index].id === id) {
  19695. return this.materials[index];
  19696. }
  19697. }
  19698. return null;
  19699. };
  19700. /**
  19701. * get a material using its name
  19702. * @param {string} the material's name
  19703. * @return {BABYLON.Material|null} the material or null if none found.
  19704. */
  19705. Scene.prototype.getMaterialByName = function (name) {
  19706. for (var index = 0; index < this.materials.length; index++) {
  19707. if (this.materials[index].name === name) {
  19708. return this.materials[index];
  19709. }
  19710. }
  19711. return null;
  19712. };
  19713. Scene.prototype.getLensFlareSystemByName = function (name) {
  19714. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19715. if (this.lensFlareSystems[index].name === name) {
  19716. return this.lensFlareSystems[index];
  19717. }
  19718. }
  19719. return null;
  19720. };
  19721. Scene.prototype.getLensFlareSystemByID = function (id) {
  19722. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19723. if (this.lensFlareSystems[index].id === id) {
  19724. return this.lensFlareSystems[index];
  19725. }
  19726. }
  19727. return null;
  19728. };
  19729. Scene.prototype.getCameraByID = function (id) {
  19730. for (var index = 0; index < this.cameras.length; index++) {
  19731. if (this.cameras[index].id === id) {
  19732. return this.cameras[index];
  19733. }
  19734. }
  19735. return null;
  19736. };
  19737. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19738. for (var index = 0; index < this.cameras.length; index++) {
  19739. if (this.cameras[index].uniqueId === uniqueId) {
  19740. return this.cameras[index];
  19741. }
  19742. }
  19743. return null;
  19744. };
  19745. /**
  19746. * get a camera using its name
  19747. * @param {string} the camera's name
  19748. * @return {BABYLON.Camera|null} the camera or null if none found.
  19749. */
  19750. Scene.prototype.getCameraByName = function (name) {
  19751. for (var index = 0; index < this.cameras.length; index++) {
  19752. if (this.cameras[index].name === name) {
  19753. return this.cameras[index];
  19754. }
  19755. }
  19756. return null;
  19757. };
  19758. /**
  19759. * get a bone using its id
  19760. * @param {string} the bone's id
  19761. * @return {BABYLON.Bone|null} the bone or null if not found
  19762. */
  19763. Scene.prototype.getBoneByID = function (id) {
  19764. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19765. var skeleton = this.skeletons[skeletonIndex];
  19766. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19767. if (skeleton.bones[boneIndex].id === id) {
  19768. return skeleton.bones[boneIndex];
  19769. }
  19770. }
  19771. }
  19772. return null;
  19773. };
  19774. /**
  19775. * get a bone using its id
  19776. * @param {string} the bone's name
  19777. * @return {BABYLON.Bone|null} the bone or null if not found
  19778. */
  19779. Scene.prototype.getBoneByName = function (name) {
  19780. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19781. var skeleton = this.skeletons[skeletonIndex];
  19782. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19783. if (skeleton.bones[boneIndex].name === name) {
  19784. return skeleton.bones[boneIndex];
  19785. }
  19786. }
  19787. }
  19788. return null;
  19789. };
  19790. /**
  19791. * get a light node using its name
  19792. * @param {string} the light's name
  19793. * @return {BABYLON.Light|null} the light or null if none found.
  19794. */
  19795. Scene.prototype.getLightByName = function (name) {
  19796. for (var index = 0; index < this.lights.length; index++) {
  19797. if (this.lights[index].name === name) {
  19798. return this.lights[index];
  19799. }
  19800. }
  19801. return null;
  19802. };
  19803. /**
  19804. * get a light node using its ID
  19805. * @param {string} the light's id
  19806. * @return {BABYLON.Light|null} the light or null if none found.
  19807. */
  19808. Scene.prototype.getLightByID = function (id) {
  19809. for (var index = 0; index < this.lights.length; index++) {
  19810. if (this.lights[index].id === id) {
  19811. return this.lights[index];
  19812. }
  19813. }
  19814. return null;
  19815. };
  19816. /**
  19817. * get a light node using its scene-generated unique ID
  19818. * @param {number} the light's unique id
  19819. * @return {BABYLON.Light|null} the light or null if none found.
  19820. */
  19821. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19822. for (var index = 0; index < this.lights.length; index++) {
  19823. if (this.lights[index].uniqueId === uniqueId) {
  19824. return this.lights[index];
  19825. }
  19826. }
  19827. return null;
  19828. };
  19829. /**
  19830. * get a particle system by id
  19831. * @param id {number} the particle system id
  19832. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19833. */
  19834. Scene.prototype.getParticleSystemByID = function (id) {
  19835. for (var index = 0; index < this.particleSystems.length; index++) {
  19836. if (this.particleSystems[index].id === id) {
  19837. return this.particleSystems[index];
  19838. }
  19839. }
  19840. return null;
  19841. };
  19842. /**
  19843. * get a geometry using its ID
  19844. * @param {string} the geometry's id
  19845. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19846. */
  19847. Scene.prototype.getGeometryByID = function (id) {
  19848. for (var index = 0; index < this._geometries.length; index++) {
  19849. if (this._geometries[index].id === id) {
  19850. return this._geometries[index];
  19851. }
  19852. }
  19853. return null;
  19854. };
  19855. /**
  19856. * add a new geometry to this scene.
  19857. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19858. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19859. * @return {boolean} was the geometry added or not
  19860. */
  19861. Scene.prototype.pushGeometry = function (geometry, force) {
  19862. if (!force && this.getGeometryByID(geometry.id)) {
  19863. return false;
  19864. }
  19865. this._geometries.push(geometry);
  19866. //notify the collision coordinator
  19867. if (this.collisionCoordinator) {
  19868. this.collisionCoordinator.onGeometryAdded(geometry);
  19869. }
  19870. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19871. return true;
  19872. };
  19873. /**
  19874. * Removes an existing geometry
  19875. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19876. * @return {boolean} was the geometry removed or not
  19877. */
  19878. Scene.prototype.removeGeometry = function (geometry) {
  19879. var index = this._geometries.indexOf(geometry);
  19880. if (index > -1) {
  19881. this._geometries.splice(index, 1);
  19882. //notify the collision coordinator
  19883. if (this.collisionCoordinator) {
  19884. this.collisionCoordinator.onGeometryDeleted(geometry);
  19885. }
  19886. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19887. return true;
  19888. }
  19889. return false;
  19890. };
  19891. Scene.prototype.getGeometries = function () {
  19892. return this._geometries;
  19893. };
  19894. /**
  19895. * Get the first added mesh found of a given ID
  19896. * @param {string} id - the id to search for
  19897. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19898. */
  19899. Scene.prototype.getMeshByID = function (id) {
  19900. for (var index = 0; index < this.meshes.length; index++) {
  19901. if (this.meshes[index].id === id) {
  19902. return this.meshes[index];
  19903. }
  19904. }
  19905. return null;
  19906. };
  19907. Scene.prototype.getMeshesByID = function (id) {
  19908. return this.meshes.filter(function (m) {
  19909. return m.id === id;
  19910. });
  19911. };
  19912. /**
  19913. * Get the first added transform node found of a given ID
  19914. * @param {string} id - the id to search for
  19915. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  19916. */
  19917. Scene.prototype.getTransformNodeByID = function (id) {
  19918. for (var index = 0; index < this.transformNodes.length; index++) {
  19919. if (this.transformNodes[index].id === id) {
  19920. return this.transformNodes[index];
  19921. }
  19922. }
  19923. return null;
  19924. };
  19925. Scene.prototype.getTransformNodesByID = function (id) {
  19926. return this.transformNodes.filter(function (m) {
  19927. return m.id === id;
  19928. });
  19929. };
  19930. /**
  19931. * Get a mesh with its auto-generated unique id
  19932. * @param {number} uniqueId - the unique id to search for
  19933. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19934. */
  19935. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  19936. for (var index = 0; index < this.meshes.length; index++) {
  19937. if (this.meshes[index].uniqueId === uniqueId) {
  19938. return this.meshes[index];
  19939. }
  19940. }
  19941. return null;
  19942. };
  19943. /**
  19944. * Get a the last added mesh found of a given ID
  19945. * @param {string} id - the id to search for
  19946. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19947. */
  19948. Scene.prototype.getLastMeshByID = function (id) {
  19949. for (var index = this.meshes.length - 1; index >= 0; index--) {
  19950. if (this.meshes[index].id === id) {
  19951. return this.meshes[index];
  19952. }
  19953. }
  19954. return null;
  19955. };
  19956. /**
  19957. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  19958. * @param {string} id - the id to search for
  19959. * @return {BABYLON.Node|null} the node found or null if not found at all.
  19960. */
  19961. Scene.prototype.getLastEntryByID = function (id) {
  19962. var index;
  19963. for (index = this.meshes.length - 1; index >= 0; index--) {
  19964. if (this.meshes[index].id === id) {
  19965. return this.meshes[index];
  19966. }
  19967. }
  19968. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  19969. if (this.transformNodes[index].id === id) {
  19970. return this.transformNodes[index];
  19971. }
  19972. }
  19973. for (index = this.cameras.length - 1; index >= 0; index--) {
  19974. if (this.cameras[index].id === id) {
  19975. return this.cameras[index];
  19976. }
  19977. }
  19978. for (index = this.lights.length - 1; index >= 0; index--) {
  19979. if (this.lights[index].id === id) {
  19980. return this.lights[index];
  19981. }
  19982. }
  19983. return null;
  19984. };
  19985. Scene.prototype.getNodeByID = function (id) {
  19986. var mesh = this.getMeshByID(id);
  19987. if (mesh) {
  19988. return mesh;
  19989. }
  19990. var light = this.getLightByID(id);
  19991. if (light) {
  19992. return light;
  19993. }
  19994. var camera = this.getCameraByID(id);
  19995. if (camera) {
  19996. return camera;
  19997. }
  19998. var bone = this.getBoneByID(id);
  19999. return bone;
  20000. };
  20001. Scene.prototype.getNodeByName = function (name) {
  20002. var mesh = this.getMeshByName(name);
  20003. if (mesh) {
  20004. return mesh;
  20005. }
  20006. var light = this.getLightByName(name);
  20007. if (light) {
  20008. return light;
  20009. }
  20010. var camera = this.getCameraByName(name);
  20011. if (camera) {
  20012. return camera;
  20013. }
  20014. var bone = this.getBoneByName(name);
  20015. return bone;
  20016. };
  20017. Scene.prototype.getMeshByName = function (name) {
  20018. for (var index = 0; index < this.meshes.length; index++) {
  20019. if (this.meshes[index].name === name) {
  20020. return this.meshes[index];
  20021. }
  20022. }
  20023. return null;
  20024. };
  20025. Scene.prototype.getTransformNodeByName = function (name) {
  20026. for (var index = 0; index < this.transformNodes.length; index++) {
  20027. if (this.transformNodes[index].name === name) {
  20028. return this.transformNodes[index];
  20029. }
  20030. }
  20031. return null;
  20032. };
  20033. Scene.prototype.getSoundByName = function (name) {
  20034. var index;
  20035. if (BABYLON.AudioEngine) {
  20036. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  20037. if (this.mainSoundTrack.soundCollection[index].name === name) {
  20038. return this.mainSoundTrack.soundCollection[index];
  20039. }
  20040. }
  20041. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  20042. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  20043. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  20044. return this.soundTracks[sdIndex].soundCollection[index];
  20045. }
  20046. }
  20047. }
  20048. }
  20049. return null;
  20050. };
  20051. Scene.prototype.getLastSkeletonByID = function (id) {
  20052. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  20053. if (this.skeletons[index].id === id) {
  20054. return this.skeletons[index];
  20055. }
  20056. }
  20057. return null;
  20058. };
  20059. Scene.prototype.getSkeletonById = function (id) {
  20060. for (var index = 0; index < this.skeletons.length; index++) {
  20061. if (this.skeletons[index].id === id) {
  20062. return this.skeletons[index];
  20063. }
  20064. }
  20065. return null;
  20066. };
  20067. Scene.prototype.getSkeletonByName = function (name) {
  20068. for (var index = 0; index < this.skeletons.length; index++) {
  20069. if (this.skeletons[index].name === name) {
  20070. return this.skeletons[index];
  20071. }
  20072. }
  20073. return null;
  20074. };
  20075. Scene.prototype.getMorphTargetManagerById = function (id) {
  20076. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  20077. if (this.morphTargetManagers[index].uniqueId === id) {
  20078. return this.morphTargetManagers[index];
  20079. }
  20080. }
  20081. return null;
  20082. };
  20083. Scene.prototype.isActiveMesh = function (mesh) {
  20084. return (this._activeMeshes.indexOf(mesh) !== -1);
  20085. };
  20086. /**
  20087. * Return a the first highlight layer of the scene with a given name.
  20088. * @param name The name of the highlight layer to look for.
  20089. * @return The highlight layer if found otherwise null.
  20090. */
  20091. Scene.prototype.getHighlightLayerByName = function (name) {
  20092. for (var index = 0; index < this.highlightLayers.length; index++) {
  20093. if (this.highlightLayers[index].name === name) {
  20094. return this.highlightLayers[index];
  20095. }
  20096. }
  20097. return null;
  20098. };
  20099. Object.defineProperty(Scene.prototype, "uid", {
  20100. /**
  20101. * Return a unique id as a string which can serve as an identifier for the scene
  20102. */
  20103. get: function () {
  20104. if (!this._uid) {
  20105. this._uid = BABYLON.Tools.RandomId();
  20106. }
  20107. return this._uid;
  20108. },
  20109. enumerable: true,
  20110. configurable: true
  20111. });
  20112. /**
  20113. * Add an externaly attached data from its key.
  20114. * This method call will fail and return false, if such key already exists.
  20115. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  20116. * @param key the unique key that identifies the data
  20117. * @param data the data object to associate to the key for this Engine instance
  20118. * @return true if no such key were already present and the data was added successfully, false otherwise
  20119. */
  20120. Scene.prototype.addExternalData = function (key, data) {
  20121. if (!this._externalData) {
  20122. this._externalData = new BABYLON.StringDictionary();
  20123. }
  20124. return this._externalData.add(key, data);
  20125. };
  20126. /**
  20127. * Get an externaly attached data from its key
  20128. * @param key the unique key that identifies the data
  20129. * @return the associated data, if present (can be null), or undefined if not present
  20130. */
  20131. Scene.prototype.getExternalData = function (key) {
  20132. if (!this._externalData) {
  20133. return null;
  20134. }
  20135. return this._externalData.get(key);
  20136. };
  20137. /**
  20138. * Get an externaly attached data from its key, create it using a factory if it's not already present
  20139. * @param key the unique key that identifies the data
  20140. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  20141. * @return the associated data, can be null if the factory returned null.
  20142. */
  20143. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  20144. if (!this._externalData) {
  20145. this._externalData = new BABYLON.StringDictionary();
  20146. }
  20147. return this._externalData.getOrAddWithFactory(key, factory);
  20148. };
  20149. /**
  20150. * Remove an externaly attached data from the Engine instance
  20151. * @param key the unique key that identifies the data
  20152. * @return true if the data was successfully removed, false if it doesn't exist
  20153. */
  20154. Scene.prototype.removeExternalData = function (key) {
  20155. return this._externalData.remove(key);
  20156. };
  20157. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  20158. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  20159. var material = subMesh.getMaterial();
  20160. if (mesh.showSubMeshesBoundingBox) {
  20161. var boundingInfo = subMesh.getBoundingInfo();
  20162. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20163. }
  20164. if (material) {
  20165. // Render targets
  20166. if (material.getRenderTargetTextures) {
  20167. if (this._processedMaterials.indexOf(material) === -1) {
  20168. this._processedMaterials.push(material);
  20169. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  20170. }
  20171. }
  20172. // Dispatch
  20173. this._activeIndices.addCount(subMesh.indexCount, false);
  20174. this._renderingManager.dispatch(subMesh);
  20175. }
  20176. }
  20177. };
  20178. Scene.prototype._isInIntermediateRendering = function () {
  20179. return this._intermediateRendering;
  20180. };
  20181. /**
  20182. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  20183. */
  20184. Scene.prototype.freezeActiveMeshes = function () {
  20185. this._evaluateActiveMeshes();
  20186. this._activeMeshesFrozen = true;
  20187. return this;
  20188. };
  20189. /**
  20190. * Use this function to restart evaluating active meshes on every frame
  20191. */
  20192. Scene.prototype.unfreezeActiveMeshes = function () {
  20193. this._activeMeshesFrozen = false;
  20194. return this;
  20195. };
  20196. Scene.prototype._evaluateActiveMeshes = function () {
  20197. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  20198. return;
  20199. }
  20200. if (!this.activeCamera) {
  20201. return;
  20202. }
  20203. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  20204. this.activeCamera._activeMeshes.reset();
  20205. this._activeMeshes.reset();
  20206. this._renderingManager.reset();
  20207. this._processedMaterials.reset();
  20208. this._activeParticleSystems.reset();
  20209. this._activeSkeletons.reset();
  20210. this._softwareSkinnedMeshes.reset();
  20211. if (this._boundingBoxRenderer) {
  20212. this._boundingBoxRenderer.reset();
  20213. }
  20214. // Meshes
  20215. var meshes;
  20216. var len;
  20217. if (this._selectionOctree) {
  20218. var selection = this._selectionOctree.select(this._frustumPlanes);
  20219. meshes = selection.data;
  20220. len = selection.length;
  20221. }
  20222. else {
  20223. len = this.meshes.length;
  20224. meshes = this.meshes;
  20225. }
  20226. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  20227. var mesh = meshes[meshIndex];
  20228. if (mesh.isBlocked) {
  20229. continue;
  20230. }
  20231. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  20232. if (!mesh.isReady() || !mesh.isEnabled()) {
  20233. continue;
  20234. }
  20235. mesh.computeWorldMatrix();
  20236. // Intersections
  20237. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  20238. this._meshesForIntersections.pushNoDuplicate(mesh);
  20239. }
  20240. // Switch to current LOD
  20241. var meshLOD = mesh.getLOD(this.activeCamera);
  20242. if (!meshLOD) {
  20243. continue;
  20244. }
  20245. mesh._preActivate();
  20246. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  20247. this._activeMeshes.push(mesh);
  20248. this.activeCamera._activeMeshes.push(mesh);
  20249. mesh._activate(this._renderId);
  20250. if (meshLOD !== mesh) {
  20251. meshLOD._activate(this._renderId);
  20252. }
  20253. this._activeMesh(mesh, meshLOD);
  20254. }
  20255. }
  20256. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  20257. // Particle systems
  20258. if (this.particlesEnabled) {
  20259. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  20260. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  20261. var particleSystem = this.particleSystems[particleIndex];
  20262. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  20263. continue;
  20264. }
  20265. var emitter = particleSystem.emitter;
  20266. if (!emitter.position || emitter.isEnabled()) {
  20267. this._activeParticleSystems.push(particleSystem);
  20268. particleSystem.animate();
  20269. this._renderingManager.dispatchParticles(particleSystem);
  20270. }
  20271. }
  20272. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  20273. }
  20274. };
  20275. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  20276. if (mesh.skeleton && this.skeletonsEnabled) {
  20277. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  20278. mesh.skeleton.prepare();
  20279. }
  20280. if (!mesh.computeBonesUsingShaders) {
  20281. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  20282. }
  20283. }
  20284. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  20285. var boundingInfo = sourceMesh.getBoundingInfo();
  20286. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20287. }
  20288. if (mesh && mesh.subMeshes) {
  20289. // Submeshes Octrees
  20290. var len;
  20291. var subMeshes;
  20292. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  20293. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  20294. len = intersections.length;
  20295. subMeshes = intersections.data;
  20296. }
  20297. else {
  20298. subMeshes = mesh.subMeshes;
  20299. len = subMeshes.length;
  20300. }
  20301. for (var subIndex = 0; subIndex < len; subIndex++) {
  20302. var subMesh = subMeshes[subIndex];
  20303. this._evaluateSubMesh(subMesh, mesh);
  20304. }
  20305. }
  20306. };
  20307. Scene.prototype.updateTransformMatrix = function (force) {
  20308. if (!this.activeCamera) {
  20309. return;
  20310. }
  20311. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  20312. };
  20313. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  20314. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  20315. };
  20316. Scene.prototype._renderForCamera = function (camera) {
  20317. if (camera && camera._skipRendering) {
  20318. return;
  20319. }
  20320. var engine = this._engine;
  20321. this.activeCamera = camera;
  20322. if (!this.activeCamera)
  20323. throw new Error("Active camera not set");
  20324. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20325. // Viewport
  20326. engine.setViewport(this.activeCamera.viewport);
  20327. // Camera
  20328. this.resetCachedMaterial();
  20329. this._renderId++;
  20330. this.activeCamera.update();
  20331. this.updateTransformMatrix();
  20332. if (camera._alternateCamera) {
  20333. this.updateAlternateTransformMatrix(camera._alternateCamera);
  20334. this._alternateRendering = true;
  20335. }
  20336. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  20337. // Meshes
  20338. this._evaluateActiveMeshes();
  20339. // Software skinning
  20340. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  20341. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  20342. mesh.applySkeleton(mesh.skeleton);
  20343. }
  20344. // Render targets
  20345. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20346. var needsRestoreFrameBuffer = false;
  20347. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  20348. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  20349. }
  20350. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  20351. this._intermediateRendering = true;
  20352. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20353. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  20354. var renderTarget = this._renderTargets.data[renderIndex];
  20355. if (renderTarget._shouldRender()) {
  20356. this._renderId++;
  20357. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  20358. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  20359. }
  20360. }
  20361. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20362. this._intermediateRendering = false;
  20363. this._renderId++;
  20364. needsRestoreFrameBuffer = true; // Restore back buffer
  20365. }
  20366. // Render HighlightLayer Texture
  20367. var stencilState = this._engine.getStencilBuffer();
  20368. var renderhighlights = false;
  20369. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  20370. this._intermediateRendering = true;
  20371. for (var i = 0; i < this.highlightLayers.length; i++) {
  20372. var highlightLayer = this.highlightLayers[i];
  20373. if (highlightLayer.shouldRender() &&
  20374. (!highlightLayer.camera ||
  20375. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  20376. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  20377. renderhighlights = true;
  20378. var renderTarget = highlightLayer._mainTexture;
  20379. if (renderTarget._shouldRender()) {
  20380. this._renderId++;
  20381. renderTarget.render(false, false);
  20382. needsRestoreFrameBuffer = true;
  20383. }
  20384. }
  20385. }
  20386. this._intermediateRendering = false;
  20387. this._renderId++;
  20388. }
  20389. if (needsRestoreFrameBuffer) {
  20390. engine.restoreDefaultFramebuffer(); // Restore back buffer
  20391. }
  20392. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20393. // Prepare Frame
  20394. this.postProcessManager._prepareFrame();
  20395. // Backgrounds
  20396. var layerIndex;
  20397. var layer;
  20398. if (this.layers.length) {
  20399. engine.setDepthBuffer(false);
  20400. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20401. layer = this.layers[layerIndex];
  20402. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20403. layer.render();
  20404. }
  20405. }
  20406. engine.setDepthBuffer(true);
  20407. }
  20408. // Activate HighlightLayer stencil
  20409. if (renderhighlights) {
  20410. this._engine.setStencilBuffer(true);
  20411. }
  20412. // Render
  20413. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  20414. this._renderingManager.render(null, null, true, true);
  20415. this.onAfterDrawPhaseObservable.notifyObservers(this);
  20416. // Restore HighlightLayer stencil
  20417. if (renderhighlights) {
  20418. this._engine.setStencilBuffer(stencilState);
  20419. }
  20420. // Bounding boxes
  20421. if (this._boundingBoxRenderer) {
  20422. this._boundingBoxRenderer.render();
  20423. }
  20424. // Lens flares
  20425. if (this.lensFlaresEnabled) {
  20426. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20427. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  20428. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  20429. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  20430. lensFlareSystem.render();
  20431. }
  20432. }
  20433. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20434. }
  20435. // Foregrounds
  20436. if (this.layers.length) {
  20437. engine.setDepthBuffer(false);
  20438. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20439. layer = this.layers[layerIndex];
  20440. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20441. layer.render();
  20442. }
  20443. }
  20444. engine.setDepthBuffer(true);
  20445. }
  20446. // Highlight Layer
  20447. if (renderhighlights) {
  20448. engine.setDepthBuffer(false);
  20449. for (var i = 0; i < this.highlightLayers.length; i++) {
  20450. if (this.highlightLayers[i].shouldRender()) {
  20451. this.highlightLayers[i].render();
  20452. }
  20453. }
  20454. engine.setDepthBuffer(true);
  20455. }
  20456. // Finalize frame
  20457. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  20458. // Reset some special arrays
  20459. this._renderTargets.reset();
  20460. this._alternateRendering = false;
  20461. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  20462. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20463. };
  20464. Scene.prototype._processSubCameras = function (camera) {
  20465. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  20466. this._renderForCamera(camera);
  20467. return;
  20468. }
  20469. // Update camera
  20470. if (this.activeCamera) {
  20471. this.activeCamera.update();
  20472. }
  20473. // rig cameras
  20474. for (var index = 0; index < camera._rigCameras.length; index++) {
  20475. this._renderForCamera(camera._rigCameras[index]);
  20476. }
  20477. this.activeCamera = camera;
  20478. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  20479. };
  20480. Scene.prototype._checkIntersections = function () {
  20481. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  20482. var sourceMesh = this._meshesForIntersections.data[index];
  20483. if (!sourceMesh.actionManager) {
  20484. continue;
  20485. }
  20486. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  20487. var action = sourceMesh.actionManager.actions[actionIndex];
  20488. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20489. var parameters = action.getTriggerParameter();
  20490. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  20491. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  20492. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  20493. if (areIntersecting && currentIntersectionInProgress === -1) {
  20494. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  20495. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20496. sourceMesh._intersectionsInProgress.push(otherMesh);
  20497. }
  20498. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20499. sourceMesh._intersectionsInProgress.push(otherMesh);
  20500. }
  20501. }
  20502. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  20503. //They intersected, and now they don't.
  20504. //is this trigger an exit trigger? execute an event.
  20505. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20506. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20507. }
  20508. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  20509. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20510. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  20511. }
  20512. }
  20513. }
  20514. }
  20515. }
  20516. };
  20517. Scene.prototype.render = function () {
  20518. if (this.isDisposed) {
  20519. return;
  20520. }
  20521. this._activeParticles.fetchNewFrame();
  20522. this._totalVertices.fetchNewFrame();
  20523. this._activeIndices.fetchNewFrame();
  20524. this._activeBones.fetchNewFrame();
  20525. this._meshesForIntersections.reset();
  20526. this.resetCachedMaterial();
  20527. this.onBeforeAnimationsObservable.notifyObservers(this);
  20528. // Actions
  20529. if (this.actionManager) {
  20530. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  20531. }
  20532. //Simplification Queue
  20533. if (this.simplificationQueue && !this.simplificationQueue.running) {
  20534. this.simplificationQueue.executeNext();
  20535. }
  20536. if (this._engine.isDeterministicLockStep()) {
  20537. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  20538. var defaultFPS = (60.0 / 1000.0);
  20539. var defaultFrameTime = 1000 / 60; // frame time in MS
  20540. if (this._physicsEngine) {
  20541. defaultFrameTime = this._physicsEngine.getTimeStep() / 1000; //timestep in physics engine is in seconds
  20542. }
  20543. var stepsTaken = 0;
  20544. var maxSubSteps = this._engine.getLockstepMaxSteps();
  20545. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  20546. internalSteps = Math.min(internalSteps, maxSubSteps);
  20547. do {
  20548. this.onBeforeStepObservable.notifyObservers(this);
  20549. // Animations
  20550. this._animationRatio = defaultFrameTime * defaultFPS;
  20551. this._animate();
  20552. this.onAfterAnimationsObservable.notifyObservers(this);
  20553. // Physics
  20554. if (this._physicsEngine) {
  20555. this.onBeforePhysicsObservable.notifyObservers(this);
  20556. this._physicsEngine._step(defaultFPS);
  20557. this.onAfterPhysicsObservable.notifyObservers(this);
  20558. }
  20559. this.onAfterStepObservable.notifyObservers(this);
  20560. this._currentStepId++;
  20561. if ((internalSteps > 1) && (stepsTaken != internalSteps - 1)) {
  20562. this._evaluateActiveMeshes();
  20563. }
  20564. stepsTaken++;
  20565. deltaTime -= defaultFrameTime;
  20566. } while (deltaTime > 0 && stepsTaken < maxSubSteps);
  20567. this._timeAccumulator = deltaTime;
  20568. }
  20569. else {
  20570. // Animations
  20571. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20572. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20573. this._animate();
  20574. this.onAfterAnimationsObservable.notifyObservers(this);
  20575. // Physics
  20576. if (this._physicsEngine) {
  20577. this.onBeforePhysicsObservable.notifyObservers(this);
  20578. this._physicsEngine._step(deltaTime / 1000.0);
  20579. this.onAfterPhysicsObservable.notifyObservers(this);
  20580. }
  20581. }
  20582. // Before render
  20583. this.onBeforeRenderObservable.notifyObservers(this);
  20584. // Customs render targets
  20585. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20586. var engine = this.getEngine();
  20587. var currentActiveCamera = this.activeCamera;
  20588. if (this.renderTargetsEnabled) {
  20589. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20590. this._intermediateRendering = true;
  20591. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20592. var renderTarget = this.customRenderTargets[customIndex];
  20593. if (renderTarget._shouldRender()) {
  20594. this._renderId++;
  20595. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20596. if (!this.activeCamera)
  20597. throw new Error("Active camera not set");
  20598. // Viewport
  20599. engine.setViewport(this.activeCamera.viewport);
  20600. // Camera
  20601. this.updateTransformMatrix();
  20602. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20603. }
  20604. }
  20605. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20606. this._intermediateRendering = false;
  20607. this._renderId++;
  20608. }
  20609. // Restore back buffer
  20610. if (this.customRenderTargets.length > 0) {
  20611. engine.restoreDefaultFramebuffer();
  20612. }
  20613. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20614. this.activeCamera = currentActiveCamera;
  20615. // Procedural textures
  20616. if (this.proceduralTexturesEnabled) {
  20617. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20618. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20619. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20620. if (proceduralTexture._shouldRender()) {
  20621. proceduralTexture.render();
  20622. }
  20623. }
  20624. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20625. }
  20626. // Clear
  20627. if (this.autoClearDepthAndStencil || this.autoClear) {
  20628. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20629. }
  20630. // Shadows
  20631. if (this.shadowsEnabled) {
  20632. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20633. var light = this.lights[lightIndex];
  20634. var shadowGenerator = light.getShadowGenerator();
  20635. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20636. var shadowMap = (shadowGenerator.getShadowMap());
  20637. if (this.textures.indexOf(shadowMap) !== -1) {
  20638. this._renderTargets.push(shadowMap);
  20639. }
  20640. }
  20641. }
  20642. }
  20643. // Depth renderer
  20644. if (this._depthRenderer) {
  20645. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20646. }
  20647. // Geometry renderer
  20648. if (this._geometryBufferRenderer) {
  20649. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20650. }
  20651. // RenderPipeline
  20652. if (this._postProcessRenderPipelineManager) {
  20653. this._postProcessRenderPipelineManager.update();
  20654. }
  20655. // Multi-cameras?
  20656. if (this.activeCameras.length > 0) {
  20657. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20658. if (cameraIndex > 0) {
  20659. this._engine.clear(null, false, true, true);
  20660. }
  20661. this._processSubCameras(this.activeCameras[cameraIndex]);
  20662. }
  20663. }
  20664. else {
  20665. if (!this.activeCamera) {
  20666. throw new Error("No camera defined");
  20667. }
  20668. this._processSubCameras(this.activeCamera);
  20669. }
  20670. // Intersection checks
  20671. this._checkIntersections();
  20672. // Update the audio listener attached to the camera
  20673. if (BABYLON.AudioEngine) {
  20674. this._updateAudioParameters();
  20675. }
  20676. // After render
  20677. if (this.afterRender) {
  20678. this.afterRender();
  20679. }
  20680. this.onAfterRenderObservable.notifyObservers(this);
  20681. // Cleaning
  20682. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20683. var data = this._toBeDisposed.data[index];
  20684. if (data) {
  20685. data.dispose();
  20686. }
  20687. this._toBeDisposed[index] = null;
  20688. }
  20689. this._toBeDisposed.reset();
  20690. if (this.dumpNextRenderTargets) {
  20691. this.dumpNextRenderTargets = false;
  20692. }
  20693. this._activeBones.addCount(0, true);
  20694. this._activeIndices.addCount(0, true);
  20695. this._activeParticles.addCount(0, true);
  20696. };
  20697. Scene.prototype._updateAudioParameters = function () {
  20698. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20699. return;
  20700. }
  20701. var listeningCamera;
  20702. var audioEngine = BABYLON.Engine.audioEngine;
  20703. if (this.activeCameras.length > 0) {
  20704. listeningCamera = this.activeCameras[0];
  20705. }
  20706. else {
  20707. listeningCamera = this.activeCamera;
  20708. }
  20709. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20710. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20711. // for VR cameras
  20712. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20713. listeningCamera = listeningCamera.rigCameras[0];
  20714. }
  20715. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20716. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20717. cameraDirection.normalize();
  20718. // To avoid some errors on GearVR
  20719. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20720. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20721. }
  20722. var i;
  20723. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20724. var sound = this.mainSoundTrack.soundCollection[i];
  20725. if (sound.useCustomAttenuation) {
  20726. sound.updateDistanceFromListener();
  20727. }
  20728. }
  20729. for (i = 0; i < this.soundTracks.length; i++) {
  20730. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20731. sound = this.soundTracks[i].soundCollection[j];
  20732. if (sound.useCustomAttenuation) {
  20733. sound.updateDistanceFromListener();
  20734. }
  20735. }
  20736. }
  20737. }
  20738. };
  20739. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20740. // Audio
  20741. get: function () {
  20742. return this._audioEnabled;
  20743. },
  20744. set: function (value) {
  20745. this._audioEnabled = value;
  20746. if (BABYLON.AudioEngine) {
  20747. if (this._audioEnabled) {
  20748. this._enableAudio();
  20749. }
  20750. else {
  20751. this._disableAudio();
  20752. }
  20753. }
  20754. },
  20755. enumerable: true,
  20756. configurable: true
  20757. });
  20758. Scene.prototype._disableAudio = function () {
  20759. var i;
  20760. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20761. this.mainSoundTrack.soundCollection[i].pause();
  20762. }
  20763. for (i = 0; i < this.soundTracks.length; i++) {
  20764. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20765. this.soundTracks[i].soundCollection[j].pause();
  20766. }
  20767. }
  20768. };
  20769. Scene.prototype._enableAudio = function () {
  20770. var i;
  20771. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20772. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  20773. this.mainSoundTrack.soundCollection[i].play();
  20774. }
  20775. }
  20776. for (i = 0; i < this.soundTracks.length; i++) {
  20777. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20778. if (this.soundTracks[i].soundCollection[j].isPaused) {
  20779. this.soundTracks[i].soundCollection[j].play();
  20780. }
  20781. }
  20782. }
  20783. };
  20784. Object.defineProperty(Scene.prototype, "headphone", {
  20785. get: function () {
  20786. return this._headphone;
  20787. },
  20788. set: function (value) {
  20789. this._headphone = value;
  20790. if (BABYLON.AudioEngine) {
  20791. if (this._headphone) {
  20792. this._switchAudioModeForHeadphones();
  20793. }
  20794. else {
  20795. this._switchAudioModeForNormalSpeakers();
  20796. }
  20797. }
  20798. },
  20799. enumerable: true,
  20800. configurable: true
  20801. });
  20802. Scene.prototype._switchAudioModeForHeadphones = function () {
  20803. this.mainSoundTrack.switchPanningModelToHRTF();
  20804. for (var i = 0; i < this.soundTracks.length; i++) {
  20805. this.soundTracks[i].switchPanningModelToHRTF();
  20806. }
  20807. };
  20808. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  20809. this.mainSoundTrack.switchPanningModelToEqualPower();
  20810. for (var i = 0; i < this.soundTracks.length; i++) {
  20811. this.soundTracks[i].switchPanningModelToEqualPower();
  20812. }
  20813. };
  20814. Scene.prototype.enableDepthRenderer = function () {
  20815. if (this._depthRenderer) {
  20816. return this._depthRenderer;
  20817. }
  20818. this._depthRenderer = new BABYLON.DepthRenderer(this);
  20819. return this._depthRenderer;
  20820. };
  20821. Scene.prototype.disableDepthRenderer = function () {
  20822. if (!this._depthRenderer) {
  20823. return;
  20824. }
  20825. this._depthRenderer.dispose();
  20826. this._depthRenderer = null;
  20827. };
  20828. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20829. if (ratio === void 0) { ratio = 1; }
  20830. if (this._geometryBufferRenderer) {
  20831. return this._geometryBufferRenderer;
  20832. }
  20833. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20834. if (!this._geometryBufferRenderer.isSupported) {
  20835. this._geometryBufferRenderer = null;
  20836. }
  20837. return this._geometryBufferRenderer;
  20838. };
  20839. Scene.prototype.disableGeometryBufferRenderer = function () {
  20840. if (!this._geometryBufferRenderer) {
  20841. return;
  20842. }
  20843. this._geometryBufferRenderer.dispose();
  20844. this._geometryBufferRenderer = null;
  20845. };
  20846. Scene.prototype.freezeMaterials = function () {
  20847. for (var i = 0; i < this.materials.length; i++) {
  20848. this.materials[i].freeze();
  20849. }
  20850. };
  20851. Scene.prototype.unfreezeMaterials = function () {
  20852. for (var i = 0; i < this.materials.length; i++) {
  20853. this.materials[i].unfreeze();
  20854. }
  20855. };
  20856. Scene.prototype.dispose = function () {
  20857. this.beforeRender = null;
  20858. this.afterRender = null;
  20859. this.skeletons = [];
  20860. this.morphTargetManagers = [];
  20861. this.importedMeshesFiles = new Array();
  20862. this.stopAllAnimations();
  20863. this.resetCachedMaterial();
  20864. if (this._depthRenderer) {
  20865. this._depthRenderer.dispose();
  20866. }
  20867. if (this._gamepadManager) {
  20868. this._gamepadManager.dispose();
  20869. this._gamepadManager = null;
  20870. }
  20871. // Smart arrays
  20872. if (this.activeCamera) {
  20873. this.activeCamera._activeMeshes.dispose();
  20874. this.activeCamera = null;
  20875. }
  20876. this._activeMeshes.dispose();
  20877. this._renderingManager.dispose();
  20878. this._processedMaterials.dispose();
  20879. this._activeParticleSystems.dispose();
  20880. this._activeSkeletons.dispose();
  20881. this._softwareSkinnedMeshes.dispose();
  20882. this._renderTargets.dispose();
  20883. if (this._boundingBoxRenderer) {
  20884. this._boundingBoxRenderer.dispose();
  20885. }
  20886. this._meshesForIntersections.dispose();
  20887. this._toBeDisposed.dispose();
  20888. // Debug layer
  20889. if (this._debugLayer) {
  20890. this._debugLayer.hide();
  20891. }
  20892. // Events
  20893. this.onDisposeObservable.notifyObservers(this);
  20894. this.onDisposeObservable.clear();
  20895. this.onBeforeRenderObservable.clear();
  20896. this.onAfterRenderObservable.clear();
  20897. this.OnBeforeRenderTargetsRenderObservable.clear();
  20898. this.OnAfterRenderTargetsRenderObservable.clear();
  20899. this.onAfterStepObservable.clear();
  20900. this.onBeforeStepObservable.clear();
  20901. this.onBeforeActiveMeshesEvaluationObservable.clear();
  20902. this.onAfterActiveMeshesEvaluationObservable.clear();
  20903. this.onBeforeParticlesRenderingObservable.clear();
  20904. this.onAfterParticlesRenderingObservable.clear();
  20905. this.onBeforeSpritesRenderingObservable.clear();
  20906. this.onAfterSpritesRenderingObservable.clear();
  20907. this.onBeforeDrawPhaseObservable.clear();
  20908. this.onAfterDrawPhaseObservable.clear();
  20909. this.onBeforePhysicsObservable.clear();
  20910. this.onAfterPhysicsObservable.clear();
  20911. this.onBeforeAnimationsObservable.clear();
  20912. this.onAfterAnimationsObservable.clear();
  20913. this.onDataLoadedObservable.clear();
  20914. this.detachControl();
  20915. // Release sounds & sounds tracks
  20916. if (BABYLON.AudioEngine) {
  20917. this.disposeSounds();
  20918. }
  20919. // VR Helper
  20920. if (this.VRHelper) {
  20921. this.VRHelper.dispose();
  20922. }
  20923. // Detach cameras
  20924. var canvas = this._engine.getRenderingCanvas();
  20925. if (canvas) {
  20926. var index;
  20927. for (index = 0; index < this.cameras.length; index++) {
  20928. this.cameras[index].detachControl(canvas);
  20929. }
  20930. }
  20931. // Release lights
  20932. while (this.lights.length) {
  20933. this.lights[0].dispose();
  20934. }
  20935. // Release meshes
  20936. while (this.meshes.length) {
  20937. this.meshes[0].dispose(true);
  20938. }
  20939. while (this.transformNodes.length) {
  20940. this.removeTransformNode(this.transformNodes[0]);
  20941. }
  20942. // Release cameras
  20943. while (this.cameras.length) {
  20944. this.cameras[0].dispose();
  20945. }
  20946. // Release materials
  20947. if (this.defaultMaterial) {
  20948. this.defaultMaterial.dispose();
  20949. }
  20950. while (this.multiMaterials.length) {
  20951. this.multiMaterials[0].dispose();
  20952. }
  20953. while (this.materials.length) {
  20954. this.materials[0].dispose();
  20955. }
  20956. // Release particles
  20957. while (this.particleSystems.length) {
  20958. this.particleSystems[0].dispose();
  20959. }
  20960. // Release sprites
  20961. while (this.spriteManagers.length) {
  20962. this.spriteManagers[0].dispose();
  20963. }
  20964. // Release postProcesses
  20965. while (this.postProcesses.length) {
  20966. this.postProcesses[0].dispose();
  20967. }
  20968. // Release layers
  20969. while (this.layers.length) {
  20970. this.layers[0].dispose();
  20971. }
  20972. while (this.highlightLayers.length) {
  20973. this.highlightLayers[0].dispose();
  20974. }
  20975. // Release textures
  20976. while (this.textures.length) {
  20977. this.textures[0].dispose();
  20978. }
  20979. // Release UBO
  20980. this._sceneUbo.dispose();
  20981. if (this._alternateSceneUbo) {
  20982. this._alternateSceneUbo.dispose();
  20983. }
  20984. // Post-processes
  20985. this.postProcessManager.dispose();
  20986. if (this._postProcessRenderPipelineManager) {
  20987. this._postProcessRenderPipelineManager.dispose();
  20988. }
  20989. // Physics
  20990. if (this._physicsEngine) {
  20991. this.disablePhysicsEngine();
  20992. }
  20993. // Remove from engine
  20994. index = this._engine.scenes.indexOf(this);
  20995. if (index > -1) {
  20996. this._engine.scenes.splice(index, 1);
  20997. }
  20998. this._engine.wipeCaches();
  20999. this._isDisposed = true;
  21000. };
  21001. Object.defineProperty(Scene.prototype, "isDisposed", {
  21002. get: function () {
  21003. return this._isDisposed;
  21004. },
  21005. enumerable: true,
  21006. configurable: true
  21007. });
  21008. // Release sounds & sounds tracks
  21009. Scene.prototype.disposeSounds = function () {
  21010. if (!this._mainSoundTrack) {
  21011. return;
  21012. }
  21013. this.mainSoundTrack.dispose();
  21014. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21015. this.soundTracks[scIndex].dispose();
  21016. }
  21017. };
  21018. // Octrees
  21019. Scene.prototype.getWorldExtends = function () {
  21020. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21021. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21022. for (var index = 0; index < this.meshes.length; index++) {
  21023. var mesh = this.meshes[index];
  21024. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  21025. continue;
  21026. }
  21027. mesh.computeWorldMatrix(true);
  21028. var boundingInfo = mesh.getBoundingInfo();
  21029. var minBox = boundingInfo.boundingBox.minimumWorld;
  21030. var maxBox = boundingInfo.boundingBox.maximumWorld;
  21031. BABYLON.Tools.CheckExtends(minBox, min, max);
  21032. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21033. }
  21034. return {
  21035. min: min,
  21036. max: max
  21037. };
  21038. };
  21039. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21040. if (maxCapacity === void 0) { maxCapacity = 64; }
  21041. if (maxDepth === void 0) { maxDepth = 2; }
  21042. if (!this._selectionOctree) {
  21043. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21044. }
  21045. var worldExtends = this.getWorldExtends();
  21046. // Update octree
  21047. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21048. return this._selectionOctree;
  21049. };
  21050. // Picking
  21051. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21052. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21053. var result = BABYLON.Ray.Zero();
  21054. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  21055. return result;
  21056. };
  21057. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  21058. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21059. var engine = this._engine;
  21060. if (!camera) {
  21061. if (!this.activeCamera)
  21062. throw new Error("Active camera not set");
  21063. camera = this.activeCamera;
  21064. }
  21065. var cameraViewport = camera.viewport;
  21066. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21067. // Moving coordinates to local viewport world
  21068. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21069. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21070. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21071. return this;
  21072. };
  21073. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21074. var result = BABYLON.Ray.Zero();
  21075. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  21076. return result;
  21077. };
  21078. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  21079. if (!BABYLON.PickingInfo) {
  21080. return this;
  21081. }
  21082. var engine = this._engine;
  21083. if (!camera) {
  21084. if (!this.activeCamera)
  21085. throw new Error("Active camera not set");
  21086. camera = this.activeCamera;
  21087. }
  21088. var cameraViewport = camera.viewport;
  21089. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21090. var identity = BABYLON.Matrix.Identity();
  21091. // Moving coordinates to local viewport world
  21092. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21093. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21094. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21095. return this;
  21096. };
  21097. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21098. if (!BABYLON.PickingInfo) {
  21099. return null;
  21100. }
  21101. var pickingInfo = null;
  21102. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21103. var mesh = this.meshes[meshIndex];
  21104. if (predicate) {
  21105. if (!predicate(mesh)) {
  21106. continue;
  21107. }
  21108. }
  21109. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21110. continue;
  21111. }
  21112. var world = mesh.getWorldMatrix();
  21113. var ray = rayFunction(world);
  21114. var result = mesh.intersects(ray, fastCheck);
  21115. if (!result || !result.hit)
  21116. continue;
  21117. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21118. continue;
  21119. pickingInfo = result;
  21120. if (fastCheck) {
  21121. break;
  21122. }
  21123. }
  21124. return pickingInfo || new BABYLON.PickingInfo();
  21125. };
  21126. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21127. if (!BABYLON.PickingInfo) {
  21128. return null;
  21129. }
  21130. var pickingInfos = new Array();
  21131. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21132. var mesh = this.meshes[meshIndex];
  21133. if (predicate) {
  21134. if (!predicate(mesh)) {
  21135. continue;
  21136. }
  21137. }
  21138. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21139. continue;
  21140. }
  21141. var world = mesh.getWorldMatrix();
  21142. var ray = rayFunction(world);
  21143. var result = mesh.intersects(ray, false);
  21144. if (!result || !result.hit)
  21145. continue;
  21146. pickingInfos.push(result);
  21147. }
  21148. return pickingInfos;
  21149. };
  21150. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21151. if (!BABYLON.PickingInfo) {
  21152. return null;
  21153. }
  21154. var pickingInfo = null;
  21155. if (!camera) {
  21156. if (!this.activeCamera) {
  21157. return null;
  21158. }
  21159. camera = this.activeCamera;
  21160. }
  21161. if (this.spriteManagers.length > 0) {
  21162. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21163. var spriteManager = this.spriteManagers[spriteIndex];
  21164. if (!spriteManager.isPickable) {
  21165. continue;
  21166. }
  21167. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21168. if (!result || !result.hit)
  21169. continue;
  21170. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21171. continue;
  21172. pickingInfo = result;
  21173. if (fastCheck) {
  21174. break;
  21175. }
  21176. }
  21177. }
  21178. return pickingInfo || new BABYLON.PickingInfo();
  21179. };
  21180. /** Launch a ray to try to pick a mesh in the scene
  21181. * @param x position on screen
  21182. * @param y position on screen
  21183. * @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
  21184. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21185. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21186. */
  21187. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  21188. var _this = this;
  21189. if (!this._tempPickingRay) {
  21190. this._tempPickingRay = BABYLON.Ray.Zero();
  21191. }
  21192. return this._internalPick(function (world) {
  21193. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  21194. return _this._tempPickingRay;
  21195. }, predicate, fastCheck);
  21196. };
  21197. /** Launch a ray to try to pick a sprite in the scene
  21198. * @param x position on screen
  21199. * @param y position on screen
  21200. * @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
  21201. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21202. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21203. */
  21204. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  21205. if (!this._tempPickingRay) {
  21206. this._tempPickingRay = BABYLON.Ray.Zero();
  21207. }
  21208. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  21209. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  21210. };
  21211. /** Use the given ray to pick a mesh in the scene
  21212. * @param ray The ray to use to pick meshes
  21213. * @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
  21214. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21215. */
  21216. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  21217. var _this = this;
  21218. return this._internalPick(function (world) {
  21219. if (!_this._pickWithRayInverseMatrix) {
  21220. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21221. }
  21222. world.invertToRef(_this._pickWithRayInverseMatrix);
  21223. if (!_this._cachedRayForTransform) {
  21224. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21225. }
  21226. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21227. return _this._cachedRayForTransform;
  21228. }, predicate, fastCheck);
  21229. };
  21230. /**
  21231. * Launch a ray to try to pick a mesh in the scene
  21232. * @param x X position on screen
  21233. * @param y Y position on screen
  21234. * @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
  21235. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21236. */
  21237. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  21238. var _this = this;
  21239. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  21240. };
  21241. /**
  21242. * Launch a ray to try to pick a mesh in the scene
  21243. * @param ray Ray to use
  21244. * @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
  21245. */
  21246. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  21247. var _this = this;
  21248. return this._internalMultiPick(function (world) {
  21249. if (!_this._pickWithRayInverseMatrix) {
  21250. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21251. }
  21252. world.invertToRef(_this._pickWithRayInverseMatrix);
  21253. if (!_this._cachedRayForTransform) {
  21254. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21255. }
  21256. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21257. return _this._cachedRayForTransform;
  21258. }, predicate);
  21259. };
  21260. Scene.prototype.setPointerOverMesh = function (mesh) {
  21261. if (this._pointerOverMesh === mesh) {
  21262. return;
  21263. }
  21264. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21265. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21266. }
  21267. this._pointerOverMesh = mesh;
  21268. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21269. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21270. }
  21271. };
  21272. Scene.prototype.getPointerOverMesh = function () {
  21273. return this._pointerOverMesh;
  21274. };
  21275. Scene.prototype.setPointerOverSprite = function (sprite) {
  21276. if (this._pointerOverSprite === sprite) {
  21277. return;
  21278. }
  21279. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21280. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21281. }
  21282. this._pointerOverSprite = sprite;
  21283. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21284. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21285. }
  21286. };
  21287. Scene.prototype.getPointerOverSprite = function () {
  21288. return this._pointerOverSprite;
  21289. };
  21290. // Physics
  21291. Scene.prototype.getPhysicsEngine = function () {
  21292. return this._physicsEngine;
  21293. };
  21294. /**
  21295. * Enables physics to the current scene
  21296. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  21297. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  21298. * @return {boolean} was the physics engine initialized
  21299. */
  21300. Scene.prototype.enablePhysics = function (gravity, plugin) {
  21301. if (gravity === void 0) { gravity = null; }
  21302. if (this._physicsEngine) {
  21303. return true;
  21304. }
  21305. try {
  21306. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  21307. return true;
  21308. }
  21309. catch (e) {
  21310. BABYLON.Tools.Error(e.message);
  21311. return false;
  21312. }
  21313. };
  21314. Scene.prototype.disablePhysicsEngine = function () {
  21315. if (!this._physicsEngine) {
  21316. return;
  21317. }
  21318. this._physicsEngine.dispose();
  21319. this._physicsEngine = null;
  21320. };
  21321. Scene.prototype.isPhysicsEnabled = function () {
  21322. return this._physicsEngine !== undefined;
  21323. };
  21324. Scene.prototype.deleteCompoundImpostor = function (compound) {
  21325. var mesh = compound.parts[0].mesh;
  21326. if (mesh.physicsImpostor) {
  21327. mesh.physicsImpostor.dispose();
  21328. mesh.physicsImpostor = null;
  21329. }
  21330. };
  21331. // Misc.
  21332. Scene.prototype._rebuildGeometries = function () {
  21333. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  21334. var geometry = _a[_i];
  21335. geometry._rebuild();
  21336. }
  21337. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  21338. var mesh = _c[_b];
  21339. mesh._rebuild();
  21340. }
  21341. if (this.postProcessManager) {
  21342. this.postProcessManager._rebuild();
  21343. }
  21344. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  21345. var layer = _e[_d];
  21346. layer._rebuild();
  21347. }
  21348. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  21349. var highlightLayer = _g[_f];
  21350. highlightLayer._rebuild();
  21351. }
  21352. if (this._boundingBoxRenderer) {
  21353. this._boundingBoxRenderer._rebuild();
  21354. }
  21355. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  21356. var system = _j[_h];
  21357. system.rebuild();
  21358. }
  21359. if (this._postProcessRenderPipelineManager) {
  21360. this._postProcessRenderPipelineManager._rebuild();
  21361. }
  21362. };
  21363. Scene.prototype._rebuildTextures = function () {
  21364. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  21365. var texture = _a[_i];
  21366. texture._rebuild();
  21367. }
  21368. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21369. };
  21370. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  21371. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  21372. if (replace === void 0) { replace = false; }
  21373. if (attachCameraControls === void 0) { attachCameraControls = false; }
  21374. // Dispose existing camera or light in replace mode.
  21375. if (replace) {
  21376. if (this.activeCamera) {
  21377. this.activeCamera.dispose();
  21378. this.activeCamera = null;
  21379. }
  21380. if (this.lights) {
  21381. for (var i = 0; i < this.lights.length; i++) {
  21382. this.lights[i].dispose();
  21383. }
  21384. }
  21385. }
  21386. // Light
  21387. if (this.lights.length === 0) {
  21388. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  21389. }
  21390. // Camera
  21391. if (!this.activeCamera) {
  21392. var worldExtends = this.getWorldExtends();
  21393. var worldSize = worldExtends.max.subtract(worldExtends.min);
  21394. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  21395. var camera;
  21396. var radius = worldSize.length() * 1.5;
  21397. if (createArcRotateCamera) {
  21398. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  21399. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  21400. arcRotateCamera.wheelPrecision = 100 / radius;
  21401. camera = arcRotateCamera;
  21402. }
  21403. else {
  21404. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  21405. freeCamera.setTarget(worldCenter);
  21406. camera = freeCamera;
  21407. }
  21408. camera.minZ = radius * 0.01;
  21409. camera.maxZ = radius * 100;
  21410. camera.speed = radius * 0.2;
  21411. this.activeCamera = camera;
  21412. var canvas = this.getEngine().getRenderingCanvas();
  21413. if (attachCameraControls && canvas) {
  21414. camera.attachControl(canvas);
  21415. }
  21416. }
  21417. };
  21418. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  21419. if (pbr === void 0) { pbr = false; }
  21420. if (scale === void 0) { scale = 1000; }
  21421. if (blur === void 0) { blur = 0; }
  21422. if (environmentTexture) {
  21423. this.environmentTexture = environmentTexture;
  21424. }
  21425. if (!this.environmentTexture) {
  21426. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  21427. return null;
  21428. }
  21429. // Skybox
  21430. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  21431. if (pbr) {
  21432. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  21433. hdrSkyboxMaterial.backFaceCulling = false;
  21434. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21435. if (hdrSkyboxMaterial.reflectionTexture) {
  21436. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21437. }
  21438. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  21439. hdrSkyboxMaterial.disableLighting = true;
  21440. hdrSkyboxMaterial.twoSidedLighting = true;
  21441. hdrSkybox.infiniteDistance = true;
  21442. hdrSkybox.material = hdrSkyboxMaterial;
  21443. }
  21444. else {
  21445. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  21446. skyboxMaterial.backFaceCulling = false;
  21447. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21448. if (skyboxMaterial.reflectionTexture) {
  21449. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21450. }
  21451. skyboxMaterial.disableLighting = true;
  21452. hdrSkybox.infiniteDistance = true;
  21453. hdrSkybox.material = skyboxMaterial;
  21454. }
  21455. return hdrSkybox;
  21456. };
  21457. Scene.prototype.createDefaultEnvironment = function (options) {
  21458. if (BABYLON.EnvironmentHelper) {
  21459. return new BABYLON.EnvironmentHelper(options, this);
  21460. }
  21461. return null;
  21462. };
  21463. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  21464. if (webVROptions === void 0) { webVROptions = {}; }
  21465. return new BABYLON.VRExperienceHelper(this, webVROptions);
  21466. };
  21467. // Tags
  21468. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  21469. if (tagsQuery === undefined) {
  21470. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  21471. return list;
  21472. }
  21473. var listByTags = [];
  21474. forEach = forEach || (function (item) { return; });
  21475. for (var i in list) {
  21476. var item = list[i];
  21477. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  21478. listByTags.push(item);
  21479. forEach(item);
  21480. }
  21481. }
  21482. return listByTags;
  21483. };
  21484. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  21485. return this._getByTags(this.meshes, tagsQuery, forEach);
  21486. };
  21487. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  21488. return this._getByTags(this.cameras, tagsQuery, forEach);
  21489. };
  21490. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  21491. return this._getByTags(this.lights, tagsQuery, forEach);
  21492. };
  21493. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  21494. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  21495. };
  21496. /**
  21497. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21498. * This allowed control for front to back rendering or reversly depending of the special needs.
  21499. *
  21500. * @param renderingGroupId The rendering group id corresponding to its index
  21501. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21502. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21503. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21504. */
  21505. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21506. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21507. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21508. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21509. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  21510. };
  21511. /**
  21512. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21513. *
  21514. * @param renderingGroupId The rendering group id corresponding to its index
  21515. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21516. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21517. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21518. */
  21519. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21520. if (depth === void 0) { depth = true; }
  21521. if (stencil === void 0) { stencil = true; }
  21522. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  21523. };
  21524. /**
  21525. * Will flag all materials as dirty to trigger new shader compilation
  21526. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  21527. */
  21528. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  21529. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  21530. var material = _a[_i];
  21531. if (predicate && !predicate(material)) {
  21532. continue;
  21533. }
  21534. material.markAsDirty(flag);
  21535. }
  21536. };
  21537. // Statics
  21538. Scene._FOGMODE_NONE = 0;
  21539. Scene._FOGMODE_EXP = 1;
  21540. Scene._FOGMODE_EXP2 = 2;
  21541. Scene._FOGMODE_LINEAR = 3;
  21542. Scene._uniqueIdCounter = 0;
  21543. Scene.MinDeltaTime = 1.0;
  21544. Scene.MaxDeltaTime = 1000.0;
  21545. /** The distance in pixel that you have to move to prevent some events */
  21546. Scene.DragMovementThreshold = 10; // in pixels
  21547. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  21548. Scene.LongPressDelay = 500; // in milliseconds
  21549. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  21550. Scene.DoubleClickDelay = 300; // in milliseconds
  21551. /** If you need to check double click without raising a single click at first click, enable this flag */
  21552. Scene.ExclusiveDoubleClickMode = false;
  21553. return Scene;
  21554. }());
  21555. BABYLON.Scene = Scene;
  21556. })(BABYLON || (BABYLON = {}));
  21557. //# sourceMappingURL=babylon.scene.js.map
  21558. var BABYLON;
  21559. (function (BABYLON) {
  21560. var Buffer = /** @class */ (function () {
  21561. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21562. if (instanced === void 0) { instanced = false; }
  21563. if (engine instanceof BABYLON.Mesh) {
  21564. this._engine = engine.getScene().getEngine();
  21565. }
  21566. else {
  21567. this._engine = engine;
  21568. }
  21569. this._updatable = updatable;
  21570. this._data = data;
  21571. this._strideSize = stride;
  21572. if (!postponeInternalCreation) {
  21573. this.create();
  21574. }
  21575. this._instanced = instanced;
  21576. this._instanceDivisor = instanced ? 1 : 0;
  21577. }
  21578. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21579. // a lot of these parameters are ignored as they are overriden by the buffer
  21580. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21581. };
  21582. // Properties
  21583. Buffer.prototype.isUpdatable = function () {
  21584. return this._updatable;
  21585. };
  21586. Buffer.prototype.getData = function () {
  21587. return this._data;
  21588. };
  21589. Buffer.prototype.getBuffer = function () {
  21590. return this._buffer;
  21591. };
  21592. Buffer.prototype.getStrideSize = function () {
  21593. return this._strideSize;
  21594. };
  21595. Buffer.prototype.getIsInstanced = function () {
  21596. return this._instanced;
  21597. };
  21598. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  21599. get: function () {
  21600. return this._instanceDivisor;
  21601. },
  21602. set: function (value) {
  21603. this._instanceDivisor = value;
  21604. if (value == 0) {
  21605. this._instanced = false;
  21606. }
  21607. else {
  21608. this._instanced = true;
  21609. }
  21610. },
  21611. enumerable: true,
  21612. configurable: true
  21613. });
  21614. // Methods
  21615. Buffer.prototype.create = function (data) {
  21616. if (data === void 0) { data = null; }
  21617. if (!data && this._buffer) {
  21618. return; // nothing to do
  21619. }
  21620. data = data || this._data;
  21621. if (!data) {
  21622. return;
  21623. }
  21624. if (!this._buffer) {
  21625. if (this._updatable) {
  21626. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21627. this._data = data;
  21628. }
  21629. else {
  21630. this._buffer = this._engine.createVertexBuffer(data);
  21631. }
  21632. }
  21633. else if (this._updatable) {
  21634. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21635. this._data = data;
  21636. }
  21637. };
  21638. Buffer.prototype._rebuild = function () {
  21639. this._buffer = null;
  21640. this.create(this._data);
  21641. };
  21642. Buffer.prototype.update = function (data) {
  21643. this.create(data);
  21644. };
  21645. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21646. if (!this._buffer) {
  21647. return;
  21648. }
  21649. if (this._updatable) {
  21650. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21651. this._data = null;
  21652. }
  21653. };
  21654. Buffer.prototype.dispose = function () {
  21655. if (!this._buffer) {
  21656. return;
  21657. }
  21658. if (this._engine._releaseBuffer(this._buffer)) {
  21659. this._buffer = null;
  21660. }
  21661. };
  21662. return Buffer;
  21663. }());
  21664. BABYLON.Buffer = Buffer;
  21665. })(BABYLON || (BABYLON = {}));
  21666. //# sourceMappingURL=babylon.buffer.js.map
  21667. var BABYLON;
  21668. (function (BABYLON) {
  21669. var VertexBuffer = /** @class */ (function () {
  21670. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21671. if (!stride) {
  21672. // Deduce stride from kind
  21673. switch (kind) {
  21674. case VertexBuffer.PositionKind:
  21675. stride = 3;
  21676. break;
  21677. case VertexBuffer.NormalKind:
  21678. stride = 3;
  21679. break;
  21680. case VertexBuffer.UVKind:
  21681. case VertexBuffer.UV2Kind:
  21682. case VertexBuffer.UV3Kind:
  21683. case VertexBuffer.UV4Kind:
  21684. case VertexBuffer.UV5Kind:
  21685. case VertexBuffer.UV6Kind:
  21686. stride = 2;
  21687. break;
  21688. case VertexBuffer.TangentKind:
  21689. case VertexBuffer.ColorKind:
  21690. stride = 4;
  21691. break;
  21692. case VertexBuffer.MatricesIndicesKind:
  21693. case VertexBuffer.MatricesIndicesExtraKind:
  21694. stride = 4;
  21695. break;
  21696. case VertexBuffer.MatricesWeightsKind:
  21697. case VertexBuffer.MatricesWeightsExtraKind:
  21698. default:
  21699. stride = 4;
  21700. break;
  21701. }
  21702. }
  21703. if (data instanceof BABYLON.Buffer) {
  21704. if (!stride) {
  21705. stride = data.getStrideSize();
  21706. }
  21707. this._buffer = data;
  21708. this._ownsBuffer = false;
  21709. }
  21710. else {
  21711. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21712. this._ownsBuffer = true;
  21713. }
  21714. this._stride = stride;
  21715. this._offset = offset ? offset : 0;
  21716. this._size = size ? size : stride;
  21717. this._kind = kind;
  21718. }
  21719. VertexBuffer.prototype._rebuild = function () {
  21720. if (!this._buffer) {
  21721. return;
  21722. }
  21723. this._buffer._rebuild();
  21724. };
  21725. /**
  21726. * Returns the kind of the VertexBuffer (string).
  21727. */
  21728. VertexBuffer.prototype.getKind = function () {
  21729. return this._kind;
  21730. };
  21731. // Properties
  21732. /**
  21733. * Boolean : is the VertexBuffer updatable ?
  21734. */
  21735. VertexBuffer.prototype.isUpdatable = function () {
  21736. return this._buffer.isUpdatable();
  21737. };
  21738. /**
  21739. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21740. */
  21741. VertexBuffer.prototype.getData = function () {
  21742. return this._buffer.getData();
  21743. };
  21744. /**
  21745. * Returns the WebGLBuffer associated to the VertexBuffer.
  21746. */
  21747. VertexBuffer.prototype.getBuffer = function () {
  21748. return this._buffer.getBuffer();
  21749. };
  21750. /**
  21751. * Returns the stride of the VertexBuffer (integer).
  21752. */
  21753. VertexBuffer.prototype.getStrideSize = function () {
  21754. return this._stride;
  21755. };
  21756. /**
  21757. * Returns the offset (integer).
  21758. */
  21759. VertexBuffer.prototype.getOffset = function () {
  21760. return this._offset;
  21761. };
  21762. /**
  21763. * Returns the VertexBuffer total size (integer).
  21764. */
  21765. VertexBuffer.prototype.getSize = function () {
  21766. return this._size;
  21767. };
  21768. /**
  21769. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21770. */
  21771. VertexBuffer.prototype.getIsInstanced = function () {
  21772. return this._buffer.getIsInstanced();
  21773. };
  21774. /**
  21775. * Returns the instancing divisor, zero for non-instanced (integer).
  21776. */
  21777. VertexBuffer.prototype.getInstanceDivisor = function () {
  21778. return this._buffer.instanceDivisor;
  21779. };
  21780. // Methods
  21781. /**
  21782. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21783. * Returns the created WebGLBuffer.
  21784. */
  21785. VertexBuffer.prototype.create = function (data) {
  21786. return this._buffer.create(data);
  21787. };
  21788. /**
  21789. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21790. * Returns the updated WebGLBuffer.
  21791. */
  21792. VertexBuffer.prototype.update = function (data) {
  21793. return this._buffer.update(data);
  21794. };
  21795. /**
  21796. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21797. * Returns the directly updated WebGLBuffer.
  21798. */
  21799. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21800. return this._buffer.updateDirectly(data, offset);
  21801. };
  21802. /**
  21803. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21804. */
  21805. VertexBuffer.prototype.dispose = function () {
  21806. if (this._ownsBuffer) {
  21807. this._buffer.dispose();
  21808. }
  21809. };
  21810. Object.defineProperty(VertexBuffer, "PositionKind", {
  21811. get: function () {
  21812. return VertexBuffer._PositionKind;
  21813. },
  21814. enumerable: true,
  21815. configurable: true
  21816. });
  21817. Object.defineProperty(VertexBuffer, "NormalKind", {
  21818. get: function () {
  21819. return VertexBuffer._NormalKind;
  21820. },
  21821. enumerable: true,
  21822. configurable: true
  21823. });
  21824. Object.defineProperty(VertexBuffer, "TangentKind", {
  21825. get: function () {
  21826. return VertexBuffer._TangentKind;
  21827. },
  21828. enumerable: true,
  21829. configurable: true
  21830. });
  21831. Object.defineProperty(VertexBuffer, "UVKind", {
  21832. get: function () {
  21833. return VertexBuffer._UVKind;
  21834. },
  21835. enumerable: true,
  21836. configurable: true
  21837. });
  21838. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21839. get: function () {
  21840. return VertexBuffer._UV2Kind;
  21841. },
  21842. enumerable: true,
  21843. configurable: true
  21844. });
  21845. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21846. get: function () {
  21847. return VertexBuffer._UV3Kind;
  21848. },
  21849. enumerable: true,
  21850. configurable: true
  21851. });
  21852. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21853. get: function () {
  21854. return VertexBuffer._UV4Kind;
  21855. },
  21856. enumerable: true,
  21857. configurable: true
  21858. });
  21859. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21860. get: function () {
  21861. return VertexBuffer._UV5Kind;
  21862. },
  21863. enumerable: true,
  21864. configurable: true
  21865. });
  21866. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21867. get: function () {
  21868. return VertexBuffer._UV6Kind;
  21869. },
  21870. enumerable: true,
  21871. configurable: true
  21872. });
  21873. Object.defineProperty(VertexBuffer, "ColorKind", {
  21874. get: function () {
  21875. return VertexBuffer._ColorKind;
  21876. },
  21877. enumerable: true,
  21878. configurable: true
  21879. });
  21880. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21881. get: function () {
  21882. return VertexBuffer._MatricesIndicesKind;
  21883. },
  21884. enumerable: true,
  21885. configurable: true
  21886. });
  21887. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21888. get: function () {
  21889. return VertexBuffer._MatricesWeightsKind;
  21890. },
  21891. enumerable: true,
  21892. configurable: true
  21893. });
  21894. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21895. get: function () {
  21896. return VertexBuffer._MatricesIndicesExtraKind;
  21897. },
  21898. enumerable: true,
  21899. configurable: true
  21900. });
  21901. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21902. get: function () {
  21903. return VertexBuffer._MatricesWeightsExtraKind;
  21904. },
  21905. enumerable: true,
  21906. configurable: true
  21907. });
  21908. // Enums
  21909. VertexBuffer._PositionKind = "position";
  21910. VertexBuffer._NormalKind = "normal";
  21911. VertexBuffer._TangentKind = "tangent";
  21912. VertexBuffer._UVKind = "uv";
  21913. VertexBuffer._UV2Kind = "uv2";
  21914. VertexBuffer._UV3Kind = "uv3";
  21915. VertexBuffer._UV4Kind = "uv4";
  21916. VertexBuffer._UV5Kind = "uv5";
  21917. VertexBuffer._UV6Kind = "uv6";
  21918. VertexBuffer._ColorKind = "color";
  21919. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21920. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21921. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21922. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21923. return VertexBuffer;
  21924. }());
  21925. BABYLON.VertexBuffer = VertexBuffer;
  21926. })(BABYLON || (BABYLON = {}));
  21927. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21928. var BABYLON;
  21929. (function (BABYLON) {
  21930. var InternalTexture = /** @class */ (function () {
  21931. function InternalTexture(engine, dataSource) {
  21932. this.onLoadedObservable = new BABYLON.Observable();
  21933. // Private
  21934. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  21935. this._references = 1;
  21936. this._engine = engine;
  21937. this._dataSource = dataSource;
  21938. this._webGLTexture = engine._createTexture();
  21939. }
  21940. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  21941. get: function () {
  21942. return this._dataSource;
  21943. },
  21944. enumerable: true,
  21945. configurable: true
  21946. });
  21947. InternalTexture.prototype.incrementReferences = function () {
  21948. this._references++;
  21949. };
  21950. InternalTexture.prototype.updateSize = function (width, height, depth) {
  21951. if (depth === void 0) { depth = 1; }
  21952. this.width = width;
  21953. this.height = height;
  21954. this.depth = depth;
  21955. this.baseWidth = width;
  21956. this.baseHeight = height;
  21957. this.baseDepth = depth;
  21958. this._size = width * height * depth;
  21959. };
  21960. InternalTexture.prototype._rebuild = function () {
  21961. var _this = this;
  21962. var proxy;
  21963. this.isReady = false;
  21964. this._cachedCoordinatesMode = null;
  21965. this._cachedWrapU = null;
  21966. this._cachedWrapV = null;
  21967. this._cachedAnisotropicFilteringLevel = null;
  21968. switch (this._dataSource) {
  21969. case InternalTexture.DATASOURCE_TEMP:
  21970. return;
  21971. case InternalTexture.DATASOURCE_URL:
  21972. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  21973. _this.isReady = true;
  21974. }, null, this._buffer, undefined, this.format);
  21975. proxy._swapAndDie(this);
  21976. return;
  21977. case InternalTexture.DATASOURCE_RAW:
  21978. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21979. proxy._swapAndDie(this);
  21980. this.isReady = true;
  21981. return;
  21982. case InternalTexture.DATASOURCE_RAW3D:
  21983. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21984. proxy._swapAndDie(this);
  21985. this.isReady = true;
  21986. return;
  21987. case InternalTexture.DATASOURCE_DYNAMIC:
  21988. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  21989. proxy._swapAndDie(this);
  21990. // The engine will make sure to update content so no need to flag it as isReady = true
  21991. return;
  21992. case InternalTexture.DATASOURCE_RENDERTARGET:
  21993. var options = new BABYLON.RenderTargetCreationOptions();
  21994. options.generateDepthBuffer = this._generateDepthBuffer;
  21995. options.generateMipMaps = this.generateMipMaps;
  21996. options.generateStencilBuffer = this._generateStencilBuffer;
  21997. options.samplingMode = this.samplingMode;
  21998. options.type = this.type;
  21999. if (this.isCube) {
  22000. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  22001. }
  22002. else {
  22003. var size = {
  22004. width: this.width,
  22005. height: this.height
  22006. };
  22007. proxy = this._engine.createRenderTargetTexture(size, options);
  22008. }
  22009. proxy._swapAndDie(this);
  22010. this.isReady = true;
  22011. return;
  22012. case InternalTexture.DATASOURCE_CUBE:
  22013. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  22014. _this.isReady = true;
  22015. }, null, this.format, this._extension);
  22016. proxy._swapAndDie(this);
  22017. return;
  22018. case InternalTexture.DATASOURCE_CUBERAW:
  22019. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22020. proxy._swapAndDie(this);
  22021. this.isReady = true;
  22022. return;
  22023. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  22024. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  22025. if (proxy) {
  22026. proxy._swapAndDie(_this);
  22027. }
  22028. _this.isReady = true;
  22029. }, null, this.format, this._extension);
  22030. return;
  22031. }
  22032. };
  22033. InternalTexture.prototype._swapAndDie = function (target) {
  22034. target._webGLTexture = this._webGLTexture;
  22035. if (this._framebuffer) {
  22036. target._framebuffer = this._framebuffer;
  22037. }
  22038. if (this._depthStencilBuffer) {
  22039. target._depthStencilBuffer = this._depthStencilBuffer;
  22040. }
  22041. if (this._lodTextureHigh) {
  22042. if (target._lodTextureHigh) {
  22043. target._lodTextureHigh.dispose();
  22044. }
  22045. target._lodTextureHigh = this._lodTextureHigh;
  22046. }
  22047. if (this._lodTextureMid) {
  22048. if (target._lodTextureMid) {
  22049. target._lodTextureMid.dispose();
  22050. }
  22051. target._lodTextureMid = this._lodTextureMid;
  22052. }
  22053. if (this._lodTextureLow) {
  22054. if (target._lodTextureLow) {
  22055. target._lodTextureLow.dispose();
  22056. }
  22057. target._lodTextureLow = this._lodTextureLow;
  22058. }
  22059. var cache = this._engine.getLoadedTexturesCache();
  22060. var index = cache.indexOf(this);
  22061. if (index !== -1) {
  22062. cache.splice(index, 1);
  22063. }
  22064. };
  22065. InternalTexture.prototype.dispose = function () {
  22066. if (!this._webGLTexture) {
  22067. return;
  22068. }
  22069. this._references--;
  22070. if (this._references === 0) {
  22071. this._engine._releaseTexture(this);
  22072. this._webGLTexture = null;
  22073. }
  22074. };
  22075. InternalTexture.DATASOURCE_UNKNOWN = 0;
  22076. InternalTexture.DATASOURCE_URL = 1;
  22077. InternalTexture.DATASOURCE_TEMP = 2;
  22078. InternalTexture.DATASOURCE_RAW = 3;
  22079. InternalTexture.DATASOURCE_DYNAMIC = 4;
  22080. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  22081. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  22082. InternalTexture.DATASOURCE_CUBE = 7;
  22083. InternalTexture.DATASOURCE_CUBERAW = 8;
  22084. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  22085. InternalTexture.DATASOURCE_RAW3D = 10;
  22086. return InternalTexture;
  22087. }());
  22088. BABYLON.InternalTexture = InternalTexture;
  22089. })(BABYLON || (BABYLON = {}));
  22090. //# sourceMappingURL=babylon.internalTexture.js.map
  22091. var BABYLON;
  22092. (function (BABYLON) {
  22093. var BaseTexture = /** @class */ (function () {
  22094. function BaseTexture(scene) {
  22095. this._hasAlpha = false;
  22096. this.getAlphaFromRGB = false;
  22097. this.level = 1;
  22098. this.coordinatesIndex = 0;
  22099. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22100. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22101. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22102. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  22103. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  22104. this.isCube = false;
  22105. this.is3D = false;
  22106. this.gammaSpace = true;
  22107. this.invertZ = false;
  22108. this.lodLevelInAlpha = false;
  22109. this.lodGenerationOffset = 0.0;
  22110. this.lodGenerationScale = 0.8;
  22111. this.isRenderTarget = false;
  22112. this.animations = new Array();
  22113. /**
  22114. * An event triggered when the texture is disposed.
  22115. * @type {BABYLON.Observable}
  22116. */
  22117. this.onDisposeObservable = new BABYLON.Observable();
  22118. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22119. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22120. if (this._scene) {
  22121. this._scene.textures.push(this);
  22122. }
  22123. this._uid = null;
  22124. }
  22125. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  22126. get: function () {
  22127. return this._hasAlpha;
  22128. },
  22129. set: function (value) {
  22130. if (this._hasAlpha === value) {
  22131. return;
  22132. }
  22133. this._hasAlpha = value;
  22134. if (this._scene) {
  22135. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22136. }
  22137. },
  22138. enumerable: true,
  22139. configurable: true
  22140. });
  22141. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  22142. get: function () {
  22143. return this._coordinatesMode;
  22144. },
  22145. set: function (value) {
  22146. if (this._coordinatesMode === value) {
  22147. return;
  22148. }
  22149. this._coordinatesMode = value;
  22150. if (this._scene) {
  22151. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22152. }
  22153. },
  22154. enumerable: true,
  22155. configurable: true
  22156. });
  22157. Object.defineProperty(BaseTexture.prototype, "uid", {
  22158. get: function () {
  22159. if (!this._uid) {
  22160. this._uid = BABYLON.Tools.RandomId();
  22161. }
  22162. return this._uid;
  22163. },
  22164. enumerable: true,
  22165. configurable: true
  22166. });
  22167. BaseTexture.prototype.toString = function () {
  22168. return this.name;
  22169. };
  22170. BaseTexture.prototype.getClassName = function () {
  22171. return "BaseTexture";
  22172. };
  22173. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22174. set: function (callback) {
  22175. if (this._onDisposeObserver) {
  22176. this.onDisposeObservable.remove(this._onDisposeObserver);
  22177. }
  22178. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22179. },
  22180. enumerable: true,
  22181. configurable: true
  22182. });
  22183. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  22184. get: function () {
  22185. return true;
  22186. },
  22187. enumerable: true,
  22188. configurable: true
  22189. });
  22190. BaseTexture.prototype.getScene = function () {
  22191. return this._scene;
  22192. };
  22193. BaseTexture.prototype.getTextureMatrix = function () {
  22194. return BABYLON.Matrix.IdentityReadOnly;
  22195. };
  22196. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22197. return BABYLON.Matrix.IdentityReadOnly;
  22198. };
  22199. BaseTexture.prototype.getInternalTexture = function () {
  22200. return this._texture;
  22201. };
  22202. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  22203. return !this.isBlocking || this.isReady();
  22204. };
  22205. BaseTexture.prototype.isReady = function () {
  22206. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22207. this.delayLoad();
  22208. return false;
  22209. }
  22210. if (this._texture) {
  22211. return this._texture.isReady;
  22212. }
  22213. return false;
  22214. };
  22215. BaseTexture.prototype.getSize = function () {
  22216. if (this._texture && this._texture.width) {
  22217. return new BABYLON.Size(this._texture.width, this._texture.height);
  22218. }
  22219. if (this._texture && this._texture._size) {
  22220. return new BABYLON.Size(this._texture._size, this._texture._size);
  22221. }
  22222. return BABYLON.Size.Zero();
  22223. };
  22224. BaseTexture.prototype.getBaseSize = function () {
  22225. if (!this.isReady() || !this._texture)
  22226. return BABYLON.Size.Zero();
  22227. if (this._texture._size) {
  22228. return new BABYLON.Size(this._texture._size, this._texture._size);
  22229. }
  22230. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  22231. };
  22232. BaseTexture.prototype.scale = function (ratio) {
  22233. };
  22234. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22235. get: function () {
  22236. return false;
  22237. },
  22238. enumerable: true,
  22239. configurable: true
  22240. });
  22241. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22242. if (!this._scene) {
  22243. return null;
  22244. }
  22245. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22246. for (var index = 0; index < texturesCache.length; index++) {
  22247. var texturesCacheEntry = texturesCache[index];
  22248. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  22249. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22250. texturesCacheEntry.incrementReferences();
  22251. return texturesCacheEntry;
  22252. }
  22253. }
  22254. }
  22255. return null;
  22256. };
  22257. BaseTexture.prototype._rebuild = function () {
  22258. };
  22259. BaseTexture.prototype.delayLoad = function () {
  22260. };
  22261. BaseTexture.prototype.clone = function () {
  22262. return null;
  22263. };
  22264. Object.defineProperty(BaseTexture.prototype, "textureType", {
  22265. get: function () {
  22266. if (!this._texture) {
  22267. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22268. }
  22269. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22270. },
  22271. enumerable: true,
  22272. configurable: true
  22273. });
  22274. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  22275. get: function () {
  22276. if (!this._texture) {
  22277. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22278. }
  22279. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22280. },
  22281. enumerable: true,
  22282. configurable: true
  22283. });
  22284. BaseTexture.prototype.readPixels = function (faceIndex) {
  22285. if (faceIndex === void 0) { faceIndex = 0; }
  22286. if (!this._texture) {
  22287. return null;
  22288. }
  22289. var size = this.getSize();
  22290. var scene = this.getScene();
  22291. if (!scene) {
  22292. return null;
  22293. }
  22294. var engine = scene.getEngine();
  22295. if (this._texture.isCube) {
  22296. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  22297. }
  22298. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  22299. };
  22300. BaseTexture.prototype.releaseInternalTexture = function () {
  22301. if (this._texture) {
  22302. this._texture.dispose();
  22303. this._texture = null;
  22304. }
  22305. };
  22306. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  22307. get: function () {
  22308. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  22309. return null;
  22310. }
  22311. if (!this._texture._sphericalPolynomial) {
  22312. this._texture._sphericalPolynomial =
  22313. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  22314. }
  22315. return this._texture._sphericalPolynomial;
  22316. },
  22317. set: function (value) {
  22318. if (this._texture) {
  22319. this._texture._sphericalPolynomial = value;
  22320. }
  22321. },
  22322. enumerable: true,
  22323. configurable: true
  22324. });
  22325. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  22326. get: function () {
  22327. if (this._texture) {
  22328. return this._texture._lodTextureHigh;
  22329. }
  22330. return null;
  22331. },
  22332. enumerable: true,
  22333. configurable: true
  22334. });
  22335. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  22336. get: function () {
  22337. if (this._texture) {
  22338. return this._texture._lodTextureMid;
  22339. }
  22340. return null;
  22341. },
  22342. enumerable: true,
  22343. configurable: true
  22344. });
  22345. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  22346. get: function () {
  22347. if (this._texture) {
  22348. return this._texture._lodTextureLow;
  22349. }
  22350. return null;
  22351. },
  22352. enumerable: true,
  22353. configurable: true
  22354. });
  22355. BaseTexture.prototype.dispose = function () {
  22356. if (!this._scene) {
  22357. return;
  22358. }
  22359. // Animations
  22360. this._scene.stopAnimation(this);
  22361. // Remove from scene
  22362. this._scene._removePendingData(this);
  22363. var index = this._scene.textures.indexOf(this);
  22364. if (index >= 0) {
  22365. this._scene.textures.splice(index, 1);
  22366. }
  22367. if (this._texture === undefined) {
  22368. return;
  22369. }
  22370. // Release
  22371. this.releaseInternalTexture();
  22372. // Callback
  22373. this.onDisposeObservable.notifyObservers(this);
  22374. this.onDisposeObservable.clear();
  22375. };
  22376. BaseTexture.prototype.serialize = function () {
  22377. if (!this.name) {
  22378. return null;
  22379. }
  22380. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22381. // Animations
  22382. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22383. return serializationObject;
  22384. };
  22385. BaseTexture.WhenAllReady = function (textures, callback) {
  22386. var numRemaining = textures.length;
  22387. if (numRemaining === 0) {
  22388. callback();
  22389. return;
  22390. }
  22391. var _loop_1 = function () {
  22392. texture = textures[i];
  22393. if (texture.isReady()) {
  22394. if (--numRemaining === 0) {
  22395. callback();
  22396. }
  22397. }
  22398. else {
  22399. onLoadObservable = texture.onLoadObservable;
  22400. var onLoadCallback_1 = function () {
  22401. onLoadObservable.removeCallback(onLoadCallback_1);
  22402. if (--numRemaining === 0) {
  22403. callback();
  22404. }
  22405. };
  22406. onLoadObservable.add(onLoadCallback_1);
  22407. }
  22408. };
  22409. var texture, onLoadObservable;
  22410. for (var i = 0; i < textures.length; i++) {
  22411. _loop_1();
  22412. }
  22413. };
  22414. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  22415. __decorate([
  22416. BABYLON.serialize()
  22417. ], BaseTexture.prototype, "name", void 0);
  22418. __decorate([
  22419. BABYLON.serialize("hasAlpha")
  22420. ], BaseTexture.prototype, "_hasAlpha", void 0);
  22421. __decorate([
  22422. BABYLON.serialize()
  22423. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22424. __decorate([
  22425. BABYLON.serialize()
  22426. ], BaseTexture.prototype, "level", void 0);
  22427. __decorate([
  22428. BABYLON.serialize()
  22429. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22430. __decorate([
  22431. BABYLON.serialize("coordinatesMode")
  22432. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  22433. __decorate([
  22434. BABYLON.serialize()
  22435. ], BaseTexture.prototype, "wrapU", void 0);
  22436. __decorate([
  22437. BABYLON.serialize()
  22438. ], BaseTexture.prototype, "wrapV", void 0);
  22439. __decorate([
  22440. BABYLON.serialize()
  22441. ], BaseTexture.prototype, "wrapR", void 0);
  22442. __decorate([
  22443. BABYLON.serialize()
  22444. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22445. __decorate([
  22446. BABYLON.serialize()
  22447. ], BaseTexture.prototype, "isCube", void 0);
  22448. __decorate([
  22449. BABYLON.serialize()
  22450. ], BaseTexture.prototype, "is3D", void 0);
  22451. __decorate([
  22452. BABYLON.serialize()
  22453. ], BaseTexture.prototype, "gammaSpace", void 0);
  22454. __decorate([
  22455. BABYLON.serialize()
  22456. ], BaseTexture.prototype, "invertZ", void 0);
  22457. __decorate([
  22458. BABYLON.serialize()
  22459. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  22460. __decorate([
  22461. BABYLON.serialize()
  22462. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  22463. __decorate([
  22464. BABYLON.serialize()
  22465. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  22466. __decorate([
  22467. BABYLON.serialize()
  22468. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22469. return BaseTexture;
  22470. }());
  22471. BABYLON.BaseTexture = BaseTexture;
  22472. })(BABYLON || (BABYLON = {}));
  22473. //# sourceMappingURL=babylon.baseTexture.js.map
  22474. var BABYLON;
  22475. (function (BABYLON) {
  22476. var Texture = /** @class */ (function (_super) {
  22477. __extends(Texture, _super);
  22478. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  22479. if (noMipmap === void 0) { noMipmap = false; }
  22480. if (invertY === void 0) { invertY = true; }
  22481. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22482. if (onLoad === void 0) { onLoad = null; }
  22483. if (onError === void 0) { onError = null; }
  22484. if (buffer === void 0) { buffer = null; }
  22485. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22486. var _this = _super.call(this, scene) || this;
  22487. _this.uOffset = 0;
  22488. _this.vOffset = 0;
  22489. _this.uScale = 1.0;
  22490. _this.vScale = 1.0;
  22491. _this.uAng = 0;
  22492. _this.vAng = 0;
  22493. _this.wAng = 0;
  22494. _this._isBlocking = true;
  22495. _this.name = url || "";
  22496. _this.url = url;
  22497. _this._noMipmap = noMipmap;
  22498. _this._invertY = invertY;
  22499. _this._samplingMode = samplingMode;
  22500. _this._buffer = buffer;
  22501. _this._deleteBuffer = deleteBuffer;
  22502. if (format) {
  22503. _this._format = format;
  22504. }
  22505. scene = _this.getScene();
  22506. if (!scene) {
  22507. return _this;
  22508. }
  22509. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  22510. var load = function () {
  22511. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  22512. _this.onLoadObservable.notifyObservers(_this);
  22513. }
  22514. if (onLoad) {
  22515. onLoad();
  22516. }
  22517. if (!_this.isBlocking && scene) {
  22518. scene.resetCachedMaterial();
  22519. }
  22520. };
  22521. if (!_this.url) {
  22522. _this._delayedOnLoad = load;
  22523. _this._delayedOnError = onError;
  22524. return _this;
  22525. }
  22526. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  22527. if (!_this._texture) {
  22528. if (!scene.useDelayedTextureLoading) {
  22529. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  22530. if (deleteBuffer) {
  22531. delete _this._buffer;
  22532. }
  22533. }
  22534. else {
  22535. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22536. _this._delayedOnLoad = load;
  22537. _this._delayedOnError = onError;
  22538. }
  22539. }
  22540. else {
  22541. if (_this._texture.isReady) {
  22542. BABYLON.Tools.SetImmediate(function () { return load(); });
  22543. }
  22544. else {
  22545. _this._texture.onLoadedObservable.add(load);
  22546. }
  22547. }
  22548. return _this;
  22549. }
  22550. Object.defineProperty(Texture.prototype, "noMipmap", {
  22551. get: function () {
  22552. return this._noMipmap;
  22553. },
  22554. enumerable: true,
  22555. configurable: true
  22556. });
  22557. Object.defineProperty(Texture.prototype, "isBlocking", {
  22558. get: function () {
  22559. return this._isBlocking;
  22560. },
  22561. set: function (value) {
  22562. this._isBlocking = value;
  22563. },
  22564. enumerable: true,
  22565. configurable: true
  22566. });
  22567. Object.defineProperty(Texture.prototype, "samplingMode", {
  22568. get: function () {
  22569. return this._samplingMode;
  22570. },
  22571. enumerable: true,
  22572. configurable: true
  22573. });
  22574. Texture.prototype.updateURL = function (url) {
  22575. this.url = url;
  22576. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22577. this.delayLoad();
  22578. };
  22579. Texture.prototype.delayLoad = function () {
  22580. var _this = this;
  22581. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22582. return;
  22583. }
  22584. var scene = this.getScene();
  22585. if (!scene) {
  22586. return;
  22587. }
  22588. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22589. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22590. if (!this._texture) {
  22591. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  22592. if (this._deleteBuffer) {
  22593. delete this._buffer;
  22594. }
  22595. }
  22596. else {
  22597. if (this._texture.isReady) {
  22598. BABYLON.Tools.SetImmediate(function () {
  22599. if (!_this._delayedOnLoad) {
  22600. return;
  22601. }
  22602. _this._delayedOnLoad();
  22603. });
  22604. }
  22605. else {
  22606. if (this._delayedOnLoad) {
  22607. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  22608. }
  22609. }
  22610. }
  22611. };
  22612. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22613. if (!this._texture) {
  22614. return;
  22615. }
  22616. var scene = this.getScene();
  22617. if (!scene) {
  22618. return;
  22619. }
  22620. this._samplingMode = samplingMode;
  22621. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22622. };
  22623. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22624. x *= this.uScale;
  22625. y *= this.vScale;
  22626. x -= 0.5 * this.uScale;
  22627. y -= 0.5 * this.vScale;
  22628. z -= 0.5;
  22629. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22630. t.x += 0.5 * this.uScale + this.uOffset;
  22631. t.y += 0.5 * this.vScale + this.vOffset;
  22632. t.z += 0.5;
  22633. };
  22634. Texture.prototype.getTextureMatrix = function () {
  22635. var _this = this;
  22636. if (this.uOffset === this._cachedUOffset &&
  22637. this.vOffset === this._cachedVOffset &&
  22638. this.uScale === this._cachedUScale &&
  22639. this.vScale === this._cachedVScale &&
  22640. this.uAng === this._cachedUAng &&
  22641. this.vAng === this._cachedVAng &&
  22642. this.wAng === this._cachedWAng) {
  22643. return this._cachedTextureMatrix;
  22644. }
  22645. this._cachedUOffset = this.uOffset;
  22646. this._cachedVOffset = this.vOffset;
  22647. this._cachedUScale = this.uScale;
  22648. this._cachedVScale = this.vScale;
  22649. this._cachedUAng = this.uAng;
  22650. this._cachedVAng = this.vAng;
  22651. this._cachedWAng = this.wAng;
  22652. if (!this._cachedTextureMatrix) {
  22653. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22654. this._rowGenerationMatrix = new BABYLON.Matrix();
  22655. this._t0 = BABYLON.Vector3.Zero();
  22656. this._t1 = BABYLON.Vector3.Zero();
  22657. this._t2 = BABYLON.Vector3.Zero();
  22658. }
  22659. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22660. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22661. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22662. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22663. this._t1.subtractInPlace(this._t0);
  22664. this._t2.subtractInPlace(this._t0);
  22665. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22666. this._cachedTextureMatrix.m[0] = this._t1.x;
  22667. this._cachedTextureMatrix.m[1] = this._t1.y;
  22668. this._cachedTextureMatrix.m[2] = this._t1.z;
  22669. this._cachedTextureMatrix.m[4] = this._t2.x;
  22670. this._cachedTextureMatrix.m[5] = this._t2.y;
  22671. this._cachedTextureMatrix.m[6] = this._t2.z;
  22672. this._cachedTextureMatrix.m[8] = this._t0.x;
  22673. this._cachedTextureMatrix.m[9] = this._t0.y;
  22674. this._cachedTextureMatrix.m[10] = this._t0.z;
  22675. var scene = this.getScene();
  22676. if (!scene) {
  22677. return this._cachedTextureMatrix;
  22678. }
  22679. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22680. return mat.hasTexture(_this);
  22681. });
  22682. return this._cachedTextureMatrix;
  22683. };
  22684. Texture.prototype.getReflectionTextureMatrix = function () {
  22685. var _this = this;
  22686. var scene = this.getScene();
  22687. if (!scene) {
  22688. return this._cachedTextureMatrix;
  22689. }
  22690. if (this.uOffset === this._cachedUOffset &&
  22691. this.vOffset === this._cachedVOffset &&
  22692. this.uScale === this._cachedUScale &&
  22693. this.vScale === this._cachedVScale &&
  22694. this.coordinatesMode === this._cachedCoordinatesMode) {
  22695. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  22696. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  22697. return this._cachedTextureMatrix;
  22698. }
  22699. }
  22700. else {
  22701. return this._cachedTextureMatrix;
  22702. }
  22703. }
  22704. if (!this._cachedTextureMatrix) {
  22705. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22706. }
  22707. if (!this._projectionModeMatrix) {
  22708. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22709. }
  22710. this._cachedUOffset = this.uOffset;
  22711. this._cachedVOffset = this.vOffset;
  22712. this._cachedUScale = this.uScale;
  22713. this._cachedVScale = this.vScale;
  22714. this._cachedCoordinatesMode = this.coordinatesMode;
  22715. switch (this.coordinatesMode) {
  22716. case Texture.PLANAR_MODE:
  22717. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22718. this._cachedTextureMatrix[0] = this.uScale;
  22719. this._cachedTextureMatrix[5] = this.vScale;
  22720. this._cachedTextureMatrix[12] = this.uOffset;
  22721. this._cachedTextureMatrix[13] = this.vOffset;
  22722. break;
  22723. case Texture.PROJECTION_MODE:
  22724. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22725. this._projectionModeMatrix.m[0] = 0.5;
  22726. this._projectionModeMatrix.m[5] = -0.5;
  22727. this._projectionModeMatrix.m[10] = 0.0;
  22728. this._projectionModeMatrix.m[12] = 0.5;
  22729. this._projectionModeMatrix.m[13] = 0.5;
  22730. this._projectionModeMatrix.m[14] = 1.0;
  22731. this._projectionModeMatrix.m[15] = 1.0;
  22732. var projectionMatrix = scene.getProjectionMatrix();
  22733. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22734. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22735. break;
  22736. default:
  22737. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22738. break;
  22739. }
  22740. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22741. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22742. });
  22743. return this._cachedTextureMatrix;
  22744. };
  22745. Texture.prototype.clone = function () {
  22746. var _this = this;
  22747. return BABYLON.SerializationHelper.Clone(function () {
  22748. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22749. }, this);
  22750. };
  22751. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22752. get: function () {
  22753. if (!this._onLoadObservable) {
  22754. this._onLoadObservable = new BABYLON.Observable();
  22755. }
  22756. return this._onLoadObservable;
  22757. },
  22758. enumerable: true,
  22759. configurable: true
  22760. });
  22761. Texture.prototype.serialize = function () {
  22762. var serializationObject = _super.prototype.serialize.call(this);
  22763. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  22764. serializationObject.base64String = this._buffer;
  22765. serializationObject.name = serializationObject.name.replace("data:", "");
  22766. }
  22767. return serializationObject;
  22768. };
  22769. Texture.prototype.getClassName = function () {
  22770. return "Texture";
  22771. };
  22772. Texture.prototype.dispose = function () {
  22773. _super.prototype.dispose.call(this);
  22774. if (this.onLoadObservable) {
  22775. this.onLoadObservable.clear();
  22776. this._onLoadObservable = null;
  22777. }
  22778. this._delayedOnLoad = null;
  22779. this._delayedOnError = null;
  22780. };
  22781. // Statics
  22782. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22783. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22784. if (onLoad === void 0) { onLoad = null; }
  22785. if (onError === void 0) { onError = null; }
  22786. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22787. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  22788. };
  22789. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22790. if (parsedTexture.customType) {
  22791. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22792. // Update Sampling Mode
  22793. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  22794. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  22795. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  22796. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  22797. }
  22798. }
  22799. return parsedCustomTexture;
  22800. }
  22801. if (parsedTexture.isCube) {
  22802. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22803. }
  22804. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22805. return null;
  22806. }
  22807. var texture = BABYLON.SerializationHelper.Parse(function () {
  22808. var generateMipMaps = true;
  22809. if (parsedTexture.noMipmap) {
  22810. generateMipMaps = false;
  22811. }
  22812. if (parsedTexture.mirrorPlane) {
  22813. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  22814. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22815. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22816. return mirrorTexture;
  22817. }
  22818. else if (parsedTexture.isRenderTarget) {
  22819. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  22820. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22821. return renderTargetTexture;
  22822. }
  22823. else {
  22824. var texture;
  22825. if (parsedTexture.base64String) {
  22826. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  22827. }
  22828. else {
  22829. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  22830. }
  22831. return texture;
  22832. }
  22833. }, parsedTexture, scene);
  22834. // Update Sampling Mode
  22835. if (parsedTexture.samplingMode) {
  22836. var sampling = parsedTexture.samplingMode;
  22837. if (texture._samplingMode !== sampling) {
  22838. texture.updateSamplingMode(sampling);
  22839. }
  22840. }
  22841. // Animations
  22842. if (parsedTexture.animations) {
  22843. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22844. var parsedAnimation = parsedTexture.animations[animationIndex];
  22845. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22846. }
  22847. }
  22848. return texture;
  22849. };
  22850. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22851. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22852. if (noMipmap === void 0) { noMipmap = false; }
  22853. if (invertY === void 0) { invertY = true; }
  22854. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22855. if (onLoad === void 0) { onLoad = null; }
  22856. if (onError === void 0) { onError = null; }
  22857. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22858. if (name.substr(0, 5) !== "data:") {
  22859. name = "data:" + name;
  22860. }
  22861. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  22862. };
  22863. // Constants
  22864. Texture.NEAREST_SAMPLINGMODE = 1;
  22865. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  22866. Texture.BILINEAR_SAMPLINGMODE = 2;
  22867. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  22868. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22869. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  22870. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  22871. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  22872. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  22873. Texture.NEAREST_LINEAR = 7;
  22874. Texture.NEAREST_NEAREST = 8;
  22875. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  22876. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  22877. Texture.LINEAR_LINEAR = 11;
  22878. Texture.LINEAR_NEAREST = 12;
  22879. Texture.EXPLICIT_MODE = 0;
  22880. Texture.SPHERICAL_MODE = 1;
  22881. Texture.PLANAR_MODE = 2;
  22882. Texture.CUBIC_MODE = 3;
  22883. Texture.PROJECTION_MODE = 4;
  22884. Texture.SKYBOX_MODE = 5;
  22885. Texture.INVCUBIC_MODE = 6;
  22886. Texture.EQUIRECTANGULAR_MODE = 7;
  22887. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22888. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22889. Texture.CLAMP_ADDRESSMODE = 0;
  22890. Texture.WRAP_ADDRESSMODE = 1;
  22891. Texture.MIRROR_ADDRESSMODE = 2;
  22892. __decorate([
  22893. BABYLON.serialize()
  22894. ], Texture.prototype, "url", void 0);
  22895. __decorate([
  22896. BABYLON.serialize()
  22897. ], Texture.prototype, "uOffset", void 0);
  22898. __decorate([
  22899. BABYLON.serialize()
  22900. ], Texture.prototype, "vOffset", void 0);
  22901. __decorate([
  22902. BABYLON.serialize()
  22903. ], Texture.prototype, "uScale", void 0);
  22904. __decorate([
  22905. BABYLON.serialize()
  22906. ], Texture.prototype, "vScale", void 0);
  22907. __decorate([
  22908. BABYLON.serialize()
  22909. ], Texture.prototype, "uAng", void 0);
  22910. __decorate([
  22911. BABYLON.serialize()
  22912. ], Texture.prototype, "vAng", void 0);
  22913. __decorate([
  22914. BABYLON.serialize()
  22915. ], Texture.prototype, "wAng", void 0);
  22916. __decorate([
  22917. BABYLON.serialize()
  22918. ], Texture.prototype, "isBlocking", null);
  22919. return Texture;
  22920. }(BABYLON.BaseTexture));
  22921. BABYLON.Texture = Texture;
  22922. })(BABYLON || (BABYLON = {}));
  22923. //# sourceMappingURL=babylon.texture.js.map
  22924. var BABYLON;
  22925. (function (BABYLON) {
  22926. var _InstancesBatch = /** @class */ (function () {
  22927. function _InstancesBatch() {
  22928. this.mustReturn = false;
  22929. this.visibleInstances = new Array();
  22930. this.renderSelf = new Array();
  22931. }
  22932. return _InstancesBatch;
  22933. }());
  22934. BABYLON._InstancesBatch = _InstancesBatch;
  22935. var Mesh = /** @class */ (function (_super) {
  22936. __extends(Mesh, _super);
  22937. /**
  22938. * @constructor
  22939. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22940. * @param {Scene} scene The scene to add this mesh to.
  22941. * @param {Node} parent The parent of this mesh, if it has one
  22942. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22943. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22944. * When false, achieved by calling a clone(), also passing False.
  22945. * This will make creation of children, recursive.
  22946. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22947. */
  22948. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22949. if (scene === void 0) { scene = null; }
  22950. if (parent === void 0) { parent = null; }
  22951. if (source === void 0) { source = null; }
  22952. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22953. var _this = _super.call(this, name, scene) || this;
  22954. // Events
  22955. /**
  22956. * An event triggered before rendering the mesh
  22957. * @type {BABYLON.Observable}
  22958. */
  22959. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22960. /**
  22961. * An event triggered after rendering the mesh
  22962. * @type {BABYLON.Observable}
  22963. */
  22964. _this.onAfterRenderObservable = new BABYLON.Observable();
  22965. /**
  22966. * An event triggered before drawing the mesh
  22967. * @type {BABYLON.Observable}
  22968. */
  22969. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22970. // Members
  22971. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22972. _this.instances = new Array();
  22973. _this._LODLevels = new Array();
  22974. _this._visibleInstances = {};
  22975. _this._renderIdForInstances = new Array();
  22976. _this._batchCache = new _InstancesBatch();
  22977. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22978. // Use by builder only to know what orientation were the mesh build in.
  22979. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  22980. _this.overrideMaterialSideOrientation = null;
  22981. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22982. // Will be used to save a source mesh reference, If any
  22983. _this._source = null;
  22984. scene = _this.getScene();
  22985. if (source) {
  22986. // Source mesh
  22987. _this._source = source;
  22988. // Geometry
  22989. if (source._geometry) {
  22990. source._geometry.applyToMesh(_this);
  22991. }
  22992. // Deep copy
  22993. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  22994. // Tags
  22995. if (BABYLON.Tags.HasTags(source)) {
  22996. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  22997. }
  22998. _this.metadata = source.metadata;
  22999. // Parent
  23000. _this.parent = source.parent;
  23001. // Pivot
  23002. _this.setPivotMatrix(source.getPivotMatrix());
  23003. _this.id = name + "." + source.id;
  23004. // Material
  23005. _this.material = source.material;
  23006. var index;
  23007. if (!doNotCloneChildren) {
  23008. // Children
  23009. for (index = 0; index < scene.meshes.length; index++) {
  23010. var mesh = scene.meshes[index];
  23011. if (mesh.parent === source) {
  23012. // doNotCloneChildren is always going to be False
  23013. mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  23014. }
  23015. }
  23016. }
  23017. // Physics clone
  23018. var physicsEngine = _this.getScene().getPhysicsEngine();
  23019. if (clonePhysicsImpostor && physicsEngine) {
  23020. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  23021. if (impostor) {
  23022. _this.physicsImpostor = impostor.clone(_this);
  23023. }
  23024. }
  23025. // Particles
  23026. for (index = 0; index < scene.particleSystems.length; index++) {
  23027. var system = scene.particleSystems[index];
  23028. if (system.emitter === source) {
  23029. system.clone(system.name, _this);
  23030. }
  23031. }
  23032. _this.computeWorldMatrix(true);
  23033. }
  23034. // Parent
  23035. if (parent !== null) {
  23036. _this.parent = parent;
  23037. }
  23038. return _this;
  23039. }
  23040. Object.defineProperty(Mesh, "FRONTSIDE", {
  23041. /**
  23042. * Mesh side orientation : usually the external or front surface
  23043. */
  23044. get: function () {
  23045. return Mesh._FRONTSIDE;
  23046. },
  23047. enumerable: true,
  23048. configurable: true
  23049. });
  23050. Object.defineProperty(Mesh, "BACKSIDE", {
  23051. /**
  23052. * Mesh side orientation : usually the internal or back surface
  23053. */
  23054. get: function () {
  23055. return Mesh._BACKSIDE;
  23056. },
  23057. enumerable: true,
  23058. configurable: true
  23059. });
  23060. Object.defineProperty(Mesh, "DOUBLESIDE", {
  23061. /**
  23062. * Mesh side orientation : both internal and external or front and back surfaces
  23063. */
  23064. get: function () {
  23065. return Mesh._DOUBLESIDE;
  23066. },
  23067. enumerable: true,
  23068. configurable: true
  23069. });
  23070. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  23071. /**
  23072. * Mesh side orientation : by default, `FRONTSIDE`
  23073. */
  23074. get: function () {
  23075. return Mesh._DEFAULTSIDE;
  23076. },
  23077. enumerable: true,
  23078. configurable: true
  23079. });
  23080. Object.defineProperty(Mesh, "NO_CAP", {
  23081. /**
  23082. * Mesh cap setting : no cap
  23083. */
  23084. get: function () {
  23085. return Mesh._NO_CAP;
  23086. },
  23087. enumerable: true,
  23088. configurable: true
  23089. });
  23090. Object.defineProperty(Mesh, "CAP_START", {
  23091. /**
  23092. * Mesh cap setting : one cap at the beginning of the mesh
  23093. */
  23094. get: function () {
  23095. return Mesh._CAP_START;
  23096. },
  23097. enumerable: true,
  23098. configurable: true
  23099. });
  23100. Object.defineProperty(Mesh, "CAP_END", {
  23101. /**
  23102. * Mesh cap setting : one cap at the end of the mesh
  23103. */
  23104. get: function () {
  23105. return Mesh._CAP_END;
  23106. },
  23107. enumerable: true,
  23108. configurable: true
  23109. });
  23110. Object.defineProperty(Mesh, "CAP_ALL", {
  23111. /**
  23112. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  23113. */
  23114. get: function () {
  23115. return Mesh._CAP_ALL;
  23116. },
  23117. enumerable: true,
  23118. configurable: true
  23119. });
  23120. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  23121. set: function (callback) {
  23122. if (this._onBeforeDrawObserver) {
  23123. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  23124. }
  23125. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  23126. },
  23127. enumerable: true,
  23128. configurable: true
  23129. });
  23130. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  23131. get: function () {
  23132. return this._morphTargetManager;
  23133. },
  23134. set: function (value) {
  23135. if (this._morphTargetManager === value) {
  23136. return;
  23137. }
  23138. this._morphTargetManager = value;
  23139. this._syncGeometryWithMorphTargetManager();
  23140. },
  23141. enumerable: true,
  23142. configurable: true
  23143. });
  23144. Object.defineProperty(Mesh.prototype, "source", {
  23145. get: function () {
  23146. return this._source;
  23147. },
  23148. enumerable: true,
  23149. configurable: true
  23150. });
  23151. // Methods
  23152. /**
  23153. * Returns the string "Mesh".
  23154. */
  23155. Mesh.prototype.getClassName = function () {
  23156. return "Mesh";
  23157. };
  23158. /**
  23159. * Returns a string.
  23160. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23161. */
  23162. Mesh.prototype.toString = function (fullDetails) {
  23163. var ret = _super.prototype.toString.call(this, fullDetails);
  23164. ret += ", n vertices: " + this.getTotalVertices();
  23165. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  23166. if (this.animations) {
  23167. for (var i = 0; i < this.animations.length; i++) {
  23168. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23169. }
  23170. }
  23171. if (fullDetails) {
  23172. if (this._geometry) {
  23173. var ib = this.getIndices();
  23174. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23175. if (vb && ib) {
  23176. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  23177. }
  23178. }
  23179. else {
  23180. ret += ", flat shading: UNKNOWN";
  23181. }
  23182. }
  23183. return ret;
  23184. };
  23185. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  23186. /**
  23187. * True if the mesh has some Levels Of Details (LOD).
  23188. * Returns a boolean.
  23189. */
  23190. get: function () {
  23191. return this._LODLevels.length > 0;
  23192. },
  23193. enumerable: true,
  23194. configurable: true
  23195. });
  23196. Mesh.prototype._sortLODLevels = function () {
  23197. this._LODLevels.sort(function (a, b) {
  23198. if (a.distance < b.distance) {
  23199. return 1;
  23200. }
  23201. if (a.distance > b.distance) {
  23202. return -1;
  23203. }
  23204. return 0;
  23205. });
  23206. };
  23207. /**
  23208. * Add a mesh as LOD level triggered at the given distance.
  23209. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23210. * @param {number} distance The distance from the center of the object to show this level
  23211. * @param {Mesh} mesh The mesh to be added as LOD level
  23212. * @return {Mesh} This mesh (for chaining)
  23213. */
  23214. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23215. if (mesh && mesh._masterMesh) {
  23216. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23217. return this;
  23218. }
  23219. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23220. this._LODLevels.push(level);
  23221. if (mesh) {
  23222. mesh._masterMesh = this;
  23223. }
  23224. this._sortLODLevels();
  23225. return this;
  23226. };
  23227. /**
  23228. * Returns the LOD level mesh at the passed distance or null if not found.
  23229. * It is related to the method `addLODLevel(distance, mesh)`.
  23230. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23231. * Returns an object Mesh or `null`.
  23232. */
  23233. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23234. for (var index = 0; index < this._LODLevels.length; index++) {
  23235. var level = this._LODLevels[index];
  23236. if (level.distance === distance) {
  23237. return level.mesh;
  23238. }
  23239. }
  23240. return null;
  23241. };
  23242. /**
  23243. * Remove a mesh from the LOD array
  23244. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23245. * @param {Mesh} mesh The mesh to be removed.
  23246. * @return {Mesh} This mesh (for chaining)
  23247. */
  23248. Mesh.prototype.removeLODLevel = function (mesh) {
  23249. for (var index = 0; index < this._LODLevels.length; index++) {
  23250. if (this._LODLevels[index].mesh === mesh) {
  23251. this._LODLevels.splice(index, 1);
  23252. if (mesh) {
  23253. mesh._masterMesh = null;
  23254. }
  23255. }
  23256. }
  23257. this._sortLODLevels();
  23258. return this;
  23259. };
  23260. /**
  23261. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23262. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23263. */
  23264. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23265. if (!this._LODLevels || this._LODLevels.length === 0) {
  23266. return this;
  23267. }
  23268. var bSphere;
  23269. if (boundingSphere) {
  23270. bSphere = boundingSphere;
  23271. }
  23272. else {
  23273. var boundingInfo = this.getBoundingInfo();
  23274. bSphere = boundingInfo.boundingSphere;
  23275. }
  23276. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  23277. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23278. if (this.onLODLevelSelection) {
  23279. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23280. }
  23281. return this;
  23282. }
  23283. for (var index = 0; index < this._LODLevels.length; index++) {
  23284. var level = this._LODLevels[index];
  23285. if (level.distance < distanceToCamera) {
  23286. if (level.mesh) {
  23287. level.mesh._preActivate();
  23288. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23289. }
  23290. if (this.onLODLevelSelection) {
  23291. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23292. }
  23293. return level.mesh;
  23294. }
  23295. }
  23296. if (this.onLODLevelSelection) {
  23297. this.onLODLevelSelection(distanceToCamera, this, this);
  23298. }
  23299. return this;
  23300. };
  23301. Object.defineProperty(Mesh.prototype, "geometry", {
  23302. /**
  23303. * Returns the mesh internal Geometry object.
  23304. */
  23305. get: function () {
  23306. return this._geometry;
  23307. },
  23308. enumerable: true,
  23309. configurable: true
  23310. });
  23311. /**
  23312. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23313. */
  23314. Mesh.prototype.getTotalVertices = function () {
  23315. if (!this._geometry) {
  23316. return 0;
  23317. }
  23318. return this._geometry.getTotalVertices();
  23319. };
  23320. /**
  23321. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23322. * 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.
  23323. * You can force the copy with forceCopy === true
  23324. * Returns null if the mesh has no geometry or no vertex buffer.
  23325. * Possible `kind` values :
  23326. * - BABYLON.VertexBuffer.PositionKind
  23327. * - BABYLON.VertexBuffer.UVKind
  23328. * - BABYLON.VertexBuffer.UV2Kind
  23329. * - BABYLON.VertexBuffer.UV3Kind
  23330. * - BABYLON.VertexBuffer.UV4Kind
  23331. * - BABYLON.VertexBuffer.UV5Kind
  23332. * - BABYLON.VertexBuffer.UV6Kind
  23333. * - BABYLON.VertexBuffer.ColorKind
  23334. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23335. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23336. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23337. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23338. */
  23339. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  23340. if (!this._geometry) {
  23341. return null;
  23342. }
  23343. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  23344. };
  23345. /**
  23346. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23347. * Returns `null` if the mesh has no geometry.
  23348. * Possible `kind` values :
  23349. * - BABYLON.VertexBuffer.PositionKind
  23350. * - BABYLON.VertexBuffer.UVKind
  23351. * - BABYLON.VertexBuffer.UV2Kind
  23352. * - BABYLON.VertexBuffer.UV3Kind
  23353. * - BABYLON.VertexBuffer.UV4Kind
  23354. * - BABYLON.VertexBuffer.UV5Kind
  23355. * - BABYLON.VertexBuffer.UV6Kind
  23356. * - BABYLON.VertexBuffer.ColorKind
  23357. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23358. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23359. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23360. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23361. */
  23362. Mesh.prototype.getVertexBuffer = function (kind) {
  23363. if (!this._geometry) {
  23364. return null;
  23365. }
  23366. return this._geometry.getVertexBuffer(kind);
  23367. };
  23368. /**
  23369. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23370. * Possible `kind` values :
  23371. * - BABYLON.VertexBuffer.PositionKind
  23372. * - BABYLON.VertexBuffer.UVKind
  23373. * - BABYLON.VertexBuffer.UV2Kind
  23374. * - BABYLON.VertexBuffer.UV3Kind
  23375. * - BABYLON.VertexBuffer.UV4Kind
  23376. * - BABYLON.VertexBuffer.UV5Kind
  23377. * - BABYLON.VertexBuffer.UV6Kind
  23378. * - BABYLON.VertexBuffer.ColorKind
  23379. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23380. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23381. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23382. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23383. */
  23384. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23385. if (!this._geometry) {
  23386. if (this._delayInfo) {
  23387. return this._delayInfo.indexOf(kind) !== -1;
  23388. }
  23389. return false;
  23390. }
  23391. return this._geometry.isVerticesDataPresent(kind);
  23392. };
  23393. /**
  23394. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  23395. * Possible `kind` values :
  23396. * - BABYLON.VertexBuffer.PositionKind
  23397. * - BABYLON.VertexBuffer.UVKind
  23398. * - BABYLON.VertexBuffer.UV2Kind
  23399. * - BABYLON.VertexBuffer.UV3Kind
  23400. * - BABYLON.VertexBuffer.UV4Kind
  23401. * - BABYLON.VertexBuffer.UV5Kind
  23402. * - BABYLON.VertexBuffer.UV6Kind
  23403. * - BABYLON.VertexBuffer.ColorKind
  23404. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23405. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23406. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23407. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23408. */
  23409. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  23410. if (!this._geometry) {
  23411. if (this._delayInfo) {
  23412. return this._delayInfo.indexOf(kind) !== -1;
  23413. }
  23414. return false;
  23415. }
  23416. return this._geometry.isVertexBufferUpdatable(kind);
  23417. };
  23418. /**
  23419. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23420. * Possible `kind` values :
  23421. * - BABYLON.VertexBuffer.PositionKind
  23422. * - BABYLON.VertexBuffer.UVKind
  23423. * - BABYLON.VertexBuffer.UV2Kind
  23424. * - BABYLON.VertexBuffer.UV3Kind
  23425. * - BABYLON.VertexBuffer.UV4Kind
  23426. * - BABYLON.VertexBuffer.UV5Kind
  23427. * - BABYLON.VertexBuffer.UV6Kind
  23428. * - BABYLON.VertexBuffer.ColorKind
  23429. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23430. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23431. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23432. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23433. */
  23434. Mesh.prototype.getVerticesDataKinds = function () {
  23435. if (!this._geometry) {
  23436. var result = new Array();
  23437. if (this._delayInfo) {
  23438. this._delayInfo.forEach(function (kind, index, array) {
  23439. result.push(kind);
  23440. });
  23441. }
  23442. return result;
  23443. }
  23444. return this._geometry.getVerticesDataKinds();
  23445. };
  23446. /**
  23447. * Returns a positive integer : the total number of indices in this mesh geometry.
  23448. * Returns zero if the mesh has no geometry.
  23449. */
  23450. Mesh.prototype.getTotalIndices = function () {
  23451. if (!this._geometry) {
  23452. return 0;
  23453. }
  23454. return this._geometry.getTotalIndices();
  23455. };
  23456. /**
  23457. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23458. * 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.
  23459. * Returns an empty array if the mesh has no geometry.
  23460. */
  23461. Mesh.prototype.getIndices = function (copyWhenShared) {
  23462. if (!this._geometry) {
  23463. return [];
  23464. }
  23465. return this._geometry.getIndices(copyWhenShared);
  23466. };
  23467. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23468. get: function () {
  23469. return this._masterMesh !== null && this._masterMesh !== undefined;
  23470. },
  23471. enumerable: true,
  23472. configurable: true
  23473. });
  23474. /**
  23475. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23476. */
  23477. Mesh.prototype.isReady = function () {
  23478. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23479. return false;
  23480. }
  23481. return _super.prototype.isReady.call(this);
  23482. };
  23483. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23484. /**
  23485. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23486. * This property is pertinent only for updatable parametric shapes.
  23487. */
  23488. get: function () {
  23489. return this._areNormalsFrozen;
  23490. },
  23491. enumerable: true,
  23492. configurable: true
  23493. });
  23494. /**
  23495. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23496. * It has no effect at all on other shapes.
  23497. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23498. * Returns the Mesh.
  23499. */
  23500. Mesh.prototype.freezeNormals = function () {
  23501. this._areNormalsFrozen = true;
  23502. return this;
  23503. };
  23504. /**
  23505. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23506. * It has no effect at all on other shapes.
  23507. * It reactivates the mesh normals computation if it was previously frozen.
  23508. * Returns the Mesh.
  23509. */
  23510. Mesh.prototype.unfreezeNormals = function () {
  23511. this._areNormalsFrozen = false;
  23512. return this;
  23513. };
  23514. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23515. /**
  23516. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23517. */
  23518. set: function (count) {
  23519. this._overridenInstanceCount = count;
  23520. },
  23521. enumerable: true,
  23522. configurable: true
  23523. });
  23524. // Methods
  23525. Mesh.prototype._preActivate = function () {
  23526. var sceneRenderId = this.getScene().getRenderId();
  23527. if (this._preActivateId === sceneRenderId) {
  23528. return this;
  23529. }
  23530. this._preActivateId = sceneRenderId;
  23531. this._visibleInstances = null;
  23532. return this;
  23533. };
  23534. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23535. if (this._visibleInstances) {
  23536. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23537. }
  23538. return this;
  23539. };
  23540. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23541. if (!this._visibleInstances) {
  23542. this._visibleInstances = {};
  23543. this._visibleInstances.defaultRenderId = renderId;
  23544. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23545. }
  23546. if (!this._visibleInstances[renderId]) {
  23547. this._visibleInstances[renderId] = new Array();
  23548. }
  23549. this._visibleInstances[renderId].push(instance);
  23550. return this;
  23551. };
  23552. /**
  23553. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23554. * This means the mesh underlying bounding box and sphere are recomputed.
  23555. * Returns the Mesh.
  23556. */
  23557. Mesh.prototype.refreshBoundingInfo = function () {
  23558. if (this._boundingInfo && this._boundingInfo.isLocked) {
  23559. return this;
  23560. }
  23561. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23562. if (data) {
  23563. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23564. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23565. }
  23566. if (this.subMeshes) {
  23567. for (var index = 0; index < this.subMeshes.length; index++) {
  23568. this.subMeshes[index].refreshBoundingInfo();
  23569. }
  23570. }
  23571. this._updateBoundingInfo();
  23572. return this;
  23573. };
  23574. Mesh.prototype._createGlobalSubMesh = function (force) {
  23575. var totalVertices = this.getTotalVertices();
  23576. if (!totalVertices || !this.getIndices()) {
  23577. return null;
  23578. }
  23579. // Check if we need to recreate the submeshes
  23580. if (this.subMeshes && this.subMeshes.length > 0) {
  23581. var ib = this.getIndices();
  23582. if (!ib) {
  23583. return null;
  23584. }
  23585. var totalIndices = ib.length;
  23586. var needToRecreate = false;
  23587. if (force) {
  23588. needToRecreate = true;
  23589. }
  23590. else {
  23591. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  23592. var submesh = _a[_i];
  23593. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  23594. needToRecreate = true;
  23595. break;
  23596. }
  23597. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  23598. needToRecreate = true;
  23599. break;
  23600. }
  23601. }
  23602. }
  23603. if (!needToRecreate) {
  23604. return this.subMeshes[0];
  23605. }
  23606. }
  23607. this.releaseSubMeshes();
  23608. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23609. };
  23610. Mesh.prototype.subdivide = function (count) {
  23611. if (count < 1) {
  23612. return;
  23613. }
  23614. var totalIndices = this.getTotalIndices();
  23615. var subdivisionSize = (totalIndices / count) | 0;
  23616. var offset = 0;
  23617. // Ensure that subdivisionSize is a multiple of 3
  23618. while (subdivisionSize % 3 !== 0) {
  23619. subdivisionSize++;
  23620. }
  23621. this.releaseSubMeshes();
  23622. for (var index = 0; index < count; index++) {
  23623. if (offset >= totalIndices) {
  23624. break;
  23625. }
  23626. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23627. offset += subdivisionSize;
  23628. }
  23629. this.synchronizeInstances();
  23630. };
  23631. /**
  23632. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23633. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23634. * The `data` are either a numeric array either a Float32Array.
  23635. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23636. * 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).
  23637. * Note that a new underlying VertexBuffer object is created each call.
  23638. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23639. *
  23640. * Possible `kind` values :
  23641. * - BABYLON.VertexBuffer.PositionKind
  23642. * - BABYLON.VertexBuffer.UVKind
  23643. * - BABYLON.VertexBuffer.UV2Kind
  23644. * - BABYLON.VertexBuffer.UV3Kind
  23645. * - BABYLON.VertexBuffer.UV4Kind
  23646. * - BABYLON.VertexBuffer.UV5Kind
  23647. * - BABYLON.VertexBuffer.UV6Kind
  23648. * - BABYLON.VertexBuffer.ColorKind
  23649. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23650. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23651. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23652. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23653. *
  23654. * Returns the Mesh.
  23655. */
  23656. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23657. if (updatable === void 0) { updatable = false; }
  23658. if (!this._geometry) {
  23659. var vertexData = new BABYLON.VertexData();
  23660. vertexData.set(data, kind);
  23661. var scene = this.getScene();
  23662. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23663. }
  23664. else {
  23665. this._geometry.setVerticesData(kind, data, updatable, stride);
  23666. }
  23667. return this;
  23668. };
  23669. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23670. if (updatable === void 0) { updatable = true; }
  23671. var vb = this.getVertexBuffer(kind);
  23672. if (!vb || vb.isUpdatable() === updatable) {
  23673. return;
  23674. }
  23675. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23676. };
  23677. /**
  23678. * Sets the mesh VertexBuffer.
  23679. * Returns the Mesh.
  23680. */
  23681. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23682. if (!this._geometry) {
  23683. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  23684. }
  23685. this._geometry.setVerticesBuffer(buffer);
  23686. return this;
  23687. };
  23688. /**
  23689. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23690. * If the mesh has no geometry, it is simply returned as it is.
  23691. * The `data` are either a numeric array either a Float32Array.
  23692. * No new underlying VertexBuffer object is created.
  23693. * 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.
  23694. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23695. *
  23696. * Possible `kind` values :
  23697. * - BABYLON.VertexBuffer.PositionKind
  23698. * - BABYLON.VertexBuffer.UVKind
  23699. * - BABYLON.VertexBuffer.UV2Kind
  23700. * - BABYLON.VertexBuffer.UV3Kind
  23701. * - BABYLON.VertexBuffer.UV4Kind
  23702. * - BABYLON.VertexBuffer.UV5Kind
  23703. * - BABYLON.VertexBuffer.UV6Kind
  23704. * - BABYLON.VertexBuffer.ColorKind
  23705. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23706. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23707. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23708. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23709. *
  23710. * Returns the Mesh.
  23711. */
  23712. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23713. if (!this._geometry) {
  23714. return this;
  23715. }
  23716. if (!makeItUnique) {
  23717. this._geometry.updateVerticesData(kind, data, updateExtends);
  23718. }
  23719. else {
  23720. this.makeGeometryUnique();
  23721. this.updateVerticesData(kind, data, updateExtends, false);
  23722. }
  23723. return this;
  23724. };
  23725. /**
  23726. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23727. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23728. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23729. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23730. * Returns the Mesh.
  23731. */
  23732. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23733. if (computeNormals === void 0) { computeNormals = true; }
  23734. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23735. if (!positions) {
  23736. return this;
  23737. }
  23738. positionFunction(positions);
  23739. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23740. if (computeNormals) {
  23741. var indices = this.getIndices();
  23742. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23743. if (!normals) {
  23744. return this;
  23745. }
  23746. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23747. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23748. }
  23749. return this;
  23750. };
  23751. /**
  23752. * Creates a un-shared specific occurence of the geometry for the mesh.
  23753. * Returns the Mesh.
  23754. */
  23755. Mesh.prototype.makeGeometryUnique = function () {
  23756. if (!this._geometry) {
  23757. return this;
  23758. }
  23759. var oldGeometry = this._geometry;
  23760. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23761. oldGeometry.releaseForMesh(this, true);
  23762. geometry.applyToMesh(this);
  23763. return this;
  23764. };
  23765. /**
  23766. * Sets the mesh indices.
  23767. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23768. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  23769. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23770. * This method creates a new index buffer each call.
  23771. * Returns the Mesh.
  23772. */
  23773. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  23774. if (totalVertices === void 0) { totalVertices = null; }
  23775. if (updatable === void 0) { updatable = false; }
  23776. if (!this._geometry) {
  23777. var vertexData = new BABYLON.VertexData();
  23778. vertexData.indices = indices;
  23779. var scene = this.getScene();
  23780. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23781. }
  23782. else {
  23783. this._geometry.setIndices(indices, totalVertices, updatable);
  23784. }
  23785. return this;
  23786. };
  23787. /**
  23788. * Update the current index buffer
  23789. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  23790. * Returns the Mesh.
  23791. */
  23792. Mesh.prototype.updateIndices = function (indices, offset) {
  23793. if (!this._geometry) {
  23794. return this;
  23795. }
  23796. this._geometry.updateIndices(indices, offset);
  23797. return this;
  23798. };
  23799. /**
  23800. * Invert the geometry to move from a right handed system to a left handed one.
  23801. * Returns the Mesh.
  23802. */
  23803. Mesh.prototype.toLeftHanded = function () {
  23804. if (!this._geometry) {
  23805. return this;
  23806. }
  23807. this._geometry.toLeftHanded();
  23808. return this;
  23809. };
  23810. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23811. if (!this._geometry) {
  23812. return this;
  23813. }
  23814. var engine = this.getScene().getEngine();
  23815. // Wireframe
  23816. var indexToBind;
  23817. if (this._unIndexed) {
  23818. indexToBind = null;
  23819. }
  23820. else {
  23821. switch (fillMode) {
  23822. case BABYLON.Material.PointFillMode:
  23823. indexToBind = null;
  23824. break;
  23825. case BABYLON.Material.WireFrameFillMode:
  23826. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23827. break;
  23828. default:
  23829. case BABYLON.Material.TriangleFillMode:
  23830. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23831. break;
  23832. }
  23833. }
  23834. // VBOs
  23835. this._geometry._bind(effect, indexToBind);
  23836. return this;
  23837. };
  23838. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  23839. if (alternate === void 0) { alternate = false; }
  23840. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23841. return this;
  23842. }
  23843. this.onBeforeDrawObservable.notifyObservers(this);
  23844. var scene = this.getScene();
  23845. var engine = scene.getEngine();
  23846. // Draw order
  23847. switch (fillMode) {
  23848. case BABYLON.Material.PointFillMode:
  23849. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23850. break;
  23851. case BABYLON.Material.WireFrameFillMode:
  23852. if (this._unIndexed) {
  23853. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23854. }
  23855. else {
  23856. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  23857. }
  23858. break;
  23859. default:
  23860. if (this._unIndexed) {
  23861. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23862. }
  23863. else {
  23864. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23865. }
  23866. }
  23867. if (scene._isAlternateRenderingEnabled && !alternate) {
  23868. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  23869. if (!effect || !scene.activeCamera) {
  23870. return this;
  23871. }
  23872. scene._switchToAlternateCameraConfiguration(true);
  23873. this._effectiveMaterial.bindView(effect);
  23874. this._effectiveMaterial.bindViewProjection(effect);
  23875. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  23876. this._draw(subMesh, fillMode, instancesCount, true);
  23877. engine.setViewport(scene.activeCamera.viewport);
  23878. scene._switchToAlternateCameraConfiguration(false);
  23879. this._effectiveMaterial.bindView(effect);
  23880. this._effectiveMaterial.bindViewProjection(effect);
  23881. }
  23882. return this;
  23883. };
  23884. /**
  23885. * Registers for this mesh a javascript function called just before the rendering process.
  23886. * This function is passed the current mesh.
  23887. * Return the Mesh.
  23888. */
  23889. Mesh.prototype.registerBeforeRender = function (func) {
  23890. this.onBeforeRenderObservable.add(func);
  23891. return this;
  23892. };
  23893. /**
  23894. * Disposes a previously registered javascript function called before the rendering.
  23895. * This function is passed the current mesh.
  23896. * Returns the Mesh.
  23897. */
  23898. Mesh.prototype.unregisterBeforeRender = function (func) {
  23899. this.onBeforeRenderObservable.removeCallback(func);
  23900. return this;
  23901. };
  23902. /**
  23903. * Registers for this mesh a javascript function called just after the rendering is complete.
  23904. * This function is passed the current mesh.
  23905. * Returns the Mesh.
  23906. */
  23907. Mesh.prototype.registerAfterRender = function (func) {
  23908. this.onAfterRenderObservable.add(func);
  23909. return this;
  23910. };
  23911. /**
  23912. * Disposes a previously registered javascript function called after the rendering.
  23913. * This function is passed the current mesh.
  23914. * Return the Mesh.
  23915. */
  23916. Mesh.prototype.unregisterAfterRender = function (func) {
  23917. this.onAfterRenderObservable.removeCallback(func);
  23918. return this;
  23919. };
  23920. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23921. var scene = this.getScene();
  23922. this._batchCache.mustReturn = false;
  23923. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23924. this._batchCache.visibleInstances[subMeshId] = null;
  23925. if (this._visibleInstances) {
  23926. var currentRenderId = scene.getRenderId();
  23927. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23928. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23929. var selfRenderId = this._renderId;
  23930. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23931. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23932. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23933. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23934. }
  23935. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  23936. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  23937. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23938. this._batchCache.mustReturn = true;
  23939. return this._batchCache;
  23940. }
  23941. if (currentRenderId !== selfRenderId) {
  23942. this._batchCache.renderSelf[subMeshId] = false;
  23943. }
  23944. }
  23945. this._renderIdForInstances[subMeshId] = currentRenderId;
  23946. }
  23947. return this._batchCache;
  23948. };
  23949. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23950. var visibleInstances = batch.visibleInstances[subMesh._id];
  23951. if (!visibleInstances) {
  23952. return this;
  23953. }
  23954. var matricesCount = visibleInstances.length + 1;
  23955. var bufferSize = matricesCount * 16 * 4;
  23956. var currentInstancesBufferSize = this._instancesBufferSize;
  23957. var instancesBuffer = this._instancesBuffer;
  23958. while (this._instancesBufferSize < bufferSize) {
  23959. this._instancesBufferSize *= 2;
  23960. }
  23961. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23962. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23963. }
  23964. var offset = 0;
  23965. var instancesCount = 0;
  23966. var world = this.getWorldMatrix();
  23967. if (batch.renderSelf[subMesh._id]) {
  23968. world.copyToArray(this._instancesData, offset);
  23969. offset += 16;
  23970. instancesCount++;
  23971. }
  23972. if (visibleInstances) {
  23973. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23974. var instance = visibleInstances[instanceIndex];
  23975. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23976. offset += 16;
  23977. instancesCount++;
  23978. }
  23979. }
  23980. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23981. if (instancesBuffer) {
  23982. instancesBuffer.dispose();
  23983. }
  23984. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23985. this._instancesBuffer = instancesBuffer;
  23986. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23987. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23988. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23989. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23990. }
  23991. else {
  23992. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23993. }
  23994. this._bind(subMesh, effect, fillMode);
  23995. this._draw(subMesh, fillMode, instancesCount);
  23996. engine.unbindInstanceAttributes();
  23997. return this;
  23998. };
  23999. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  24000. var scene = this.getScene();
  24001. var engine = scene.getEngine();
  24002. if (hardwareInstancedRendering) {
  24003. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  24004. }
  24005. else {
  24006. if (batch.renderSelf[subMesh._id]) {
  24007. // Draw
  24008. if (onBeforeDraw) {
  24009. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  24010. }
  24011. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  24012. }
  24013. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  24014. if (visibleInstancesForSubMesh) {
  24015. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  24016. var instance = visibleInstancesForSubMesh[instanceIndex];
  24017. // World
  24018. var world = instance.getWorldMatrix();
  24019. if (onBeforeDraw) {
  24020. onBeforeDraw(true, world, effectiveMaterial);
  24021. }
  24022. // Draw
  24023. this._draw(subMesh, fillMode);
  24024. }
  24025. }
  24026. }
  24027. return this;
  24028. };
  24029. /**
  24030. * Triggers the draw call for the mesh.
  24031. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  24032. * Returns the Mesh.
  24033. */
  24034. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  24035. this.checkOcclusionQuery();
  24036. if (this._isOccluded) {
  24037. return this;
  24038. }
  24039. var scene = this.getScene();
  24040. // Managing instances
  24041. var batch = this._getInstancesRenderList(subMesh._id);
  24042. if (batch.mustReturn) {
  24043. return this;
  24044. }
  24045. // Checking geometry state
  24046. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24047. return this;
  24048. }
  24049. this.onBeforeRenderObservable.notifyObservers(this);
  24050. var engine = scene.getEngine();
  24051. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24052. // Material
  24053. var material = subMesh.getMaterial();
  24054. if (!material) {
  24055. return this;
  24056. }
  24057. this._effectiveMaterial = material;
  24058. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24059. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  24060. return this;
  24061. }
  24062. }
  24063. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  24064. return this;
  24065. }
  24066. // Alpha mode
  24067. if (enableAlphaMode) {
  24068. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  24069. }
  24070. // Outline - step 1
  24071. var savedDepthWrite = engine.getDepthWrite();
  24072. if (this.renderOutline) {
  24073. engine.setDepthWrite(false);
  24074. scene.getOutlineRenderer().render(subMesh, batch);
  24075. engine.setDepthWrite(savedDepthWrite);
  24076. }
  24077. var effect;
  24078. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24079. effect = subMesh.effect;
  24080. }
  24081. else {
  24082. effect = this._effectiveMaterial.getEffect();
  24083. }
  24084. if (!effect) {
  24085. return this;
  24086. }
  24087. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  24088. if (this._effectiveMaterial.forceDepthWrite) {
  24089. engine.setDepthWrite(true);
  24090. }
  24091. // Bind
  24092. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  24093. if (!hardwareInstancedRendering) {
  24094. this._bind(subMesh, effect, fillMode);
  24095. }
  24096. var world = this.getWorldMatrix();
  24097. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24098. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  24099. }
  24100. else {
  24101. this._effectiveMaterial.bind(world, this);
  24102. }
  24103. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  24104. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  24105. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24106. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  24107. }
  24108. // Draw
  24109. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24110. // Unbind
  24111. this._effectiveMaterial.unbind();
  24112. // Outline - step 2
  24113. if (this.renderOutline && savedDepthWrite) {
  24114. engine.setDepthWrite(true);
  24115. engine.setColorWrite(false);
  24116. scene.getOutlineRenderer().render(subMesh, batch);
  24117. engine.setColorWrite(true);
  24118. }
  24119. // Overlay
  24120. if (this.renderOverlay) {
  24121. var currentMode = engine.getAlphaMode();
  24122. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24123. scene.getOutlineRenderer().render(subMesh, batch, true);
  24124. engine.setAlphaMode(currentMode);
  24125. }
  24126. this.onAfterRenderObservable.notifyObservers(this);
  24127. return this;
  24128. };
  24129. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  24130. if (isInstance && effectiveMaterial) {
  24131. effectiveMaterial.bindOnlyWorldMatrix(world);
  24132. }
  24133. };
  24134. /**
  24135. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  24136. */
  24137. Mesh.prototype.getEmittedParticleSystems = function () {
  24138. var results = new Array();
  24139. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24140. var particleSystem = this.getScene().particleSystems[index];
  24141. if (particleSystem.emitter === this) {
  24142. results.push(particleSystem);
  24143. }
  24144. }
  24145. return results;
  24146. };
  24147. /**
  24148. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  24149. */
  24150. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  24151. var results = new Array();
  24152. var descendants = this.getDescendants();
  24153. descendants.push(this);
  24154. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24155. var particleSystem = this.getScene().particleSystems[index];
  24156. var emitter = particleSystem.emitter;
  24157. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  24158. results.push(particleSystem);
  24159. }
  24160. }
  24161. return results;
  24162. };
  24163. Mesh.prototype._checkDelayState = function () {
  24164. var scene = this.getScene();
  24165. if (this._geometry) {
  24166. this._geometry.load(scene);
  24167. }
  24168. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24169. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24170. this._queueLoad(this, scene);
  24171. }
  24172. return this;
  24173. };
  24174. Mesh.prototype._queueLoad = function (mesh, scene) {
  24175. var _this = this;
  24176. scene._addPendingData(mesh);
  24177. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  24178. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24179. if (data instanceof ArrayBuffer) {
  24180. _this._delayLoadingFunction(data, _this);
  24181. }
  24182. else {
  24183. _this._delayLoadingFunction(JSON.parse(data), _this);
  24184. }
  24185. _this.instances.forEach(function (instance) {
  24186. instance._syncSubMeshes();
  24187. });
  24188. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24189. scene._removePendingData(_this);
  24190. }, function () { }, scene.database, getBinaryData);
  24191. return this;
  24192. };
  24193. /**
  24194. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  24195. */
  24196. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  24197. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24198. return false;
  24199. }
  24200. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  24201. return false;
  24202. }
  24203. this._checkDelayState();
  24204. return true;
  24205. };
  24206. /**
  24207. * Sets the mesh material by the material or multiMaterial `id` property.
  24208. * The material `id` is a string identifying the material or the multiMaterial.
  24209. * This method returns the Mesh.
  24210. */
  24211. Mesh.prototype.setMaterialByID = function (id) {
  24212. var materials = this.getScene().materials;
  24213. var index;
  24214. for (index = materials.length - 1; index > -1; index--) {
  24215. if (materials[index].id === id) {
  24216. this.material = materials[index];
  24217. return this;
  24218. }
  24219. }
  24220. // Multi
  24221. var multiMaterials = this.getScene().multiMaterials;
  24222. for (index = multiMaterials.length - 1; index > -1; index--) {
  24223. if (multiMaterials[index].id === id) {
  24224. this.material = multiMaterials[index];
  24225. return this;
  24226. }
  24227. }
  24228. return this;
  24229. };
  24230. /**
  24231. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  24232. */
  24233. Mesh.prototype.getAnimatables = function () {
  24234. var results = new Array();
  24235. if (this.material) {
  24236. results.push(this.material);
  24237. }
  24238. if (this.skeleton) {
  24239. results.push(this.skeleton);
  24240. }
  24241. return results;
  24242. };
  24243. /**
  24244. * Modifies the mesh geometry according to the passed transformation matrix.
  24245. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  24246. * The mesh normals are modified accordingly the same transformation.
  24247. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24248. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24249. * Returns the Mesh.
  24250. */
  24251. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  24252. // Position
  24253. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24254. return this;
  24255. }
  24256. var submeshes = this.subMeshes.splice(0);
  24257. this._resetPointsArrayCache();
  24258. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24259. var temp = new Array();
  24260. var index;
  24261. for (index = 0; index < data.length; index += 3) {
  24262. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  24263. }
  24264. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  24265. // Normals
  24266. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24267. return this;
  24268. }
  24269. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24270. temp = [];
  24271. for (index = 0; index < data.length; index += 3) {
  24272. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  24273. }
  24274. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  24275. // flip faces?
  24276. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  24277. this.flipFaces();
  24278. }
  24279. // Restore submeshes
  24280. this.releaseSubMeshes();
  24281. this.subMeshes = submeshes;
  24282. return this;
  24283. };
  24284. /**
  24285. * Modifies the mesh geometry according to its own current World Matrix.
  24286. * The mesh World Matrix is then reset.
  24287. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  24288. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24289. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24290. * Returns the Mesh.
  24291. */
  24292. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  24293. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  24294. this.scaling.copyFromFloats(1, 1, 1);
  24295. this.position.copyFromFloats(0, 0, 0);
  24296. this.rotation.copyFromFloats(0, 0, 0);
  24297. //only if quaternion is already set
  24298. if (this.rotationQuaternion) {
  24299. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  24300. }
  24301. this._worldMatrix = BABYLON.Matrix.Identity();
  24302. return this;
  24303. };
  24304. Object.defineProperty(Mesh.prototype, "_positions", {
  24305. // Cache
  24306. get: function () {
  24307. if (this._geometry) {
  24308. return this._geometry._positions;
  24309. }
  24310. return null;
  24311. },
  24312. enumerable: true,
  24313. configurable: true
  24314. });
  24315. Mesh.prototype._resetPointsArrayCache = function () {
  24316. if (this._geometry) {
  24317. this._geometry._resetPointsArrayCache();
  24318. }
  24319. return this;
  24320. };
  24321. Mesh.prototype._generatePointsArray = function () {
  24322. if (this._geometry) {
  24323. return this._geometry._generatePointsArray();
  24324. }
  24325. return false;
  24326. };
  24327. /**
  24328. * Returns a new Mesh object generated from the current mesh properties.
  24329. * This method must not get confused with createInstance().
  24330. * The parameter `name` is a string, the name given to the new mesh.
  24331. * The optional parameter `newParent` can be any Node object (default `null`).
  24332. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  24333. * 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.
  24334. */
  24335. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  24336. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24337. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  24338. };
  24339. /**
  24340. * Disposes the Mesh.
  24341. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  24342. * Returns nothing.
  24343. */
  24344. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  24345. var _this = this;
  24346. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  24347. this.morphTargetManager = null;
  24348. if (this._geometry) {
  24349. this._geometry.releaseForMesh(this, true);
  24350. }
  24351. // Sources
  24352. var meshes = this.getScene().meshes;
  24353. meshes.forEach(function (abstractMesh) {
  24354. var mesh = abstractMesh;
  24355. if (mesh._source && mesh._source === _this) {
  24356. mesh._source = null;
  24357. }
  24358. });
  24359. this._source = null;
  24360. // Instances
  24361. if (this._instancesBuffer) {
  24362. this._instancesBuffer.dispose();
  24363. this._instancesBuffer = null;
  24364. }
  24365. while (this.instances.length) {
  24366. this.instances[0].dispose();
  24367. }
  24368. // Highlight layers.
  24369. var highlightLayers = this.getScene().highlightLayers;
  24370. for (var i = 0; i < highlightLayers.length; i++) {
  24371. var highlightLayer = highlightLayers[i];
  24372. if (highlightLayer) {
  24373. highlightLayer.removeMesh(this);
  24374. highlightLayer.removeExcludedMesh(this);
  24375. }
  24376. }
  24377. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  24378. };
  24379. /**
  24380. * Modifies the mesh geometry according to a displacement map.
  24381. * 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.
  24382. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24383. * This method returns nothing.
  24384. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  24385. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24386. * 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.
  24387. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24388. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24389. *
  24390. * Returns the Mesh.
  24391. */
  24392. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  24393. var _this = this;
  24394. var scene = this.getScene();
  24395. var onload = function (img) {
  24396. // Getting height map data
  24397. var canvas = document.createElement("canvas");
  24398. var context = canvas.getContext("2d");
  24399. var heightMapWidth = img.width;
  24400. var heightMapHeight = img.height;
  24401. canvas.width = heightMapWidth;
  24402. canvas.height = heightMapHeight;
  24403. context.drawImage(img, 0, 0);
  24404. // Create VertexData from map data
  24405. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24406. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24407. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24408. //execute success callback, if set
  24409. if (onSuccess) {
  24410. onSuccess(_this);
  24411. }
  24412. };
  24413. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24414. return this;
  24415. };
  24416. /**
  24417. * Modifies the mesh geometry according to a displacementMap buffer.
  24418. * 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.
  24419. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24420. * This method returns nothing.
  24421. * 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.
  24422. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24423. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24424. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24425. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24426. *
  24427. * Returns the Mesh.
  24428. */
  24429. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24430. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24431. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24432. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24433. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24434. return this;
  24435. }
  24436. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24437. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24438. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24439. var position = BABYLON.Vector3.Zero();
  24440. var normal = BABYLON.Vector3.Zero();
  24441. var uv = BABYLON.Vector2.Zero();
  24442. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24443. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24444. for (var index = 0; index < positions.length; index += 3) {
  24445. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24446. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24447. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24448. // Compute height
  24449. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24450. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24451. var pos = (u + v * heightMapWidth) * 4;
  24452. var r = buffer[pos] / 255.0;
  24453. var g = buffer[pos + 1] / 255.0;
  24454. var b = buffer[pos + 2] / 255.0;
  24455. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24456. normal.normalize();
  24457. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24458. position = position.add(normal);
  24459. position.toArray(positions, index);
  24460. }
  24461. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24462. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24463. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24464. return this;
  24465. };
  24466. /**
  24467. * Modify the mesh to get a flat shading rendering.
  24468. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24469. * This method returns the Mesh.
  24470. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24471. */
  24472. Mesh.prototype.convertToFlatShadedMesh = function () {
  24473. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24474. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24475. var kinds = this.getVerticesDataKinds();
  24476. var vbs = {};
  24477. var data = {};
  24478. var newdata = {};
  24479. var updatableNormals = false;
  24480. var kindIndex;
  24481. var kind;
  24482. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24483. kind = kinds[kindIndex];
  24484. var vertexBuffer = this.getVertexBuffer(kind);
  24485. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24486. updatableNormals = vertexBuffer.isUpdatable();
  24487. kinds.splice(kindIndex, 1);
  24488. kindIndex--;
  24489. continue;
  24490. }
  24491. vbs[kind] = vertexBuffer;
  24492. data[kind] = vbs[kind].getData();
  24493. newdata[kind] = [];
  24494. }
  24495. // Save previous submeshes
  24496. var previousSubmeshes = this.subMeshes.slice(0);
  24497. var indices = this.getIndices();
  24498. var totalIndices = this.getTotalIndices();
  24499. // Generating unique vertices per face
  24500. var index;
  24501. for (index = 0; index < totalIndices; index++) {
  24502. var vertexIndex = indices[index];
  24503. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24504. kind = kinds[kindIndex];
  24505. var stride = vbs[kind].getStrideSize();
  24506. for (var offset = 0; offset < stride; offset++) {
  24507. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24508. }
  24509. }
  24510. }
  24511. // Updating faces & normal
  24512. var normals = [];
  24513. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24514. for (index = 0; index < totalIndices; index += 3) {
  24515. indices[index] = index;
  24516. indices[index + 1] = index + 1;
  24517. indices[index + 2] = index + 2;
  24518. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24519. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24520. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24521. var p1p2 = p1.subtract(p2);
  24522. var p3p2 = p3.subtract(p2);
  24523. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24524. // Store same normals for every vertex
  24525. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24526. normals.push(normal.x);
  24527. normals.push(normal.y);
  24528. normals.push(normal.z);
  24529. }
  24530. }
  24531. this.setIndices(indices);
  24532. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24533. // Updating vertex buffers
  24534. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24535. kind = kinds[kindIndex];
  24536. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24537. }
  24538. // Updating submeshes
  24539. this.releaseSubMeshes();
  24540. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24541. var previousOne = previousSubmeshes[submeshIndex];
  24542. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24543. }
  24544. this.synchronizeInstances();
  24545. return this;
  24546. };
  24547. /**
  24548. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24549. * In other words, more vertices, no more indices and a single bigger VBO.
  24550. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24551. * Returns the Mesh.
  24552. */
  24553. Mesh.prototype.convertToUnIndexedMesh = function () {
  24554. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24555. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24556. var kinds = this.getVerticesDataKinds();
  24557. var vbs = {};
  24558. var data = {};
  24559. var newdata = {};
  24560. var kindIndex;
  24561. var kind;
  24562. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24563. kind = kinds[kindIndex];
  24564. var vertexBuffer = this.getVertexBuffer(kind);
  24565. vbs[kind] = vertexBuffer;
  24566. data[kind] = vbs[kind].getData();
  24567. newdata[kind] = [];
  24568. }
  24569. // Save previous submeshes
  24570. var previousSubmeshes = this.subMeshes.slice(0);
  24571. var indices = this.getIndices();
  24572. var totalIndices = this.getTotalIndices();
  24573. // Generating unique vertices per face
  24574. var index;
  24575. for (index = 0; index < totalIndices; index++) {
  24576. var vertexIndex = indices[index];
  24577. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24578. kind = kinds[kindIndex];
  24579. var stride = vbs[kind].getStrideSize();
  24580. for (var offset = 0; offset < stride; offset++) {
  24581. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24582. }
  24583. }
  24584. }
  24585. // Updating indices
  24586. for (index = 0; index < totalIndices; index += 3) {
  24587. indices[index] = index;
  24588. indices[index + 1] = index + 1;
  24589. indices[index + 2] = index + 2;
  24590. }
  24591. this.setIndices(indices);
  24592. // Updating vertex buffers
  24593. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24594. kind = kinds[kindIndex];
  24595. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24596. }
  24597. // Updating submeshes
  24598. this.releaseSubMeshes();
  24599. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24600. var previousOne = previousSubmeshes[submeshIndex];
  24601. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24602. }
  24603. this._unIndexed = true;
  24604. this.synchronizeInstances();
  24605. return this;
  24606. };
  24607. /**
  24608. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24609. * This method returns the Mesh.
  24610. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24611. */
  24612. Mesh.prototype.flipFaces = function (flipNormals) {
  24613. if (flipNormals === void 0) { flipNormals = false; }
  24614. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24615. var i;
  24616. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  24617. for (i = 0; i < vertex_data.normals.length; i++) {
  24618. vertex_data.normals[i] *= -1;
  24619. }
  24620. }
  24621. if (vertex_data.indices) {
  24622. var temp;
  24623. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24624. // reassign indices
  24625. temp = vertex_data.indices[i + 1];
  24626. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24627. vertex_data.indices[i + 2] = temp;
  24628. }
  24629. }
  24630. vertex_data.applyToMesh(this);
  24631. return this;
  24632. };
  24633. // Instances
  24634. /**
  24635. * Creates a new InstancedMesh object from the mesh model.
  24636. * An instance shares the same properties and the same material than its model.
  24637. * Only these properties of each instance can then be set individually :
  24638. * - position
  24639. * - rotation
  24640. * - rotationQuaternion
  24641. * - setPivotMatrix
  24642. * - scaling
  24643. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24644. * Warning : this method is not supported for Line mesh and LineSystem
  24645. */
  24646. Mesh.prototype.createInstance = function (name) {
  24647. return new BABYLON.InstancedMesh(name, this);
  24648. };
  24649. /**
  24650. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24651. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24652. * This method returns the Mesh.
  24653. */
  24654. Mesh.prototype.synchronizeInstances = function () {
  24655. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24656. var instance = this.instances[instanceIndex];
  24657. instance._syncSubMeshes();
  24658. }
  24659. return this;
  24660. };
  24661. /**
  24662. * Simplify the mesh according to the given array of settings.
  24663. * Function will return immediately and will simplify async. It returns the Mesh.
  24664. * @param settings a collection of simplification settings.
  24665. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24666. * @param type the type of simplification to run.
  24667. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24668. */
  24669. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24670. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24671. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24672. this.getScene().simplificationQueue.addTask({
  24673. settings: settings,
  24674. parallelProcessing: parallelProcessing,
  24675. mesh: this,
  24676. simplificationType: simplificationType,
  24677. successCallback: successCallback
  24678. });
  24679. return this;
  24680. };
  24681. /**
  24682. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24683. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24684. * This should be used together with the simplification to avoid disappearing triangles.
  24685. * Returns the Mesh.
  24686. * @param successCallback an optional success callback to be called after the optimization finished.
  24687. */
  24688. Mesh.prototype.optimizeIndices = function (successCallback) {
  24689. var _this = this;
  24690. var indices = this.getIndices();
  24691. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24692. if (!positions || !indices) {
  24693. return this;
  24694. }
  24695. var vectorPositions = new Array();
  24696. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24697. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24698. }
  24699. var dupes = new Array();
  24700. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24701. var realPos = vectorPositions.length - 1 - iteration;
  24702. var testedPosition = vectorPositions[realPos];
  24703. for (var j = 0; j < realPos; ++j) {
  24704. var againstPosition = vectorPositions[j];
  24705. if (testedPosition.equals(againstPosition)) {
  24706. dupes[realPos] = j;
  24707. break;
  24708. }
  24709. }
  24710. }, function () {
  24711. for (var i = 0; i < indices.length; ++i) {
  24712. indices[i] = dupes[indices[i]] || indices[i];
  24713. }
  24714. //indices are now reordered
  24715. var originalSubMeshes = _this.subMeshes.slice(0);
  24716. _this.setIndices(indices);
  24717. _this.subMeshes = originalSubMeshes;
  24718. if (successCallback) {
  24719. successCallback(_this);
  24720. }
  24721. });
  24722. return this;
  24723. };
  24724. Mesh.prototype.serialize = function (serializationObject) {
  24725. serializationObject.name = this.name;
  24726. serializationObject.id = this.id;
  24727. serializationObject.type = this.getClassName();
  24728. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  24729. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24730. }
  24731. serializationObject.position = this.position.asArray();
  24732. if (this.rotationQuaternion) {
  24733. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24734. }
  24735. else if (this.rotation) {
  24736. serializationObject.rotation = this.rotation.asArray();
  24737. }
  24738. serializationObject.scaling = this.scaling.asArray();
  24739. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24740. serializationObject.isEnabled = this.isEnabled();
  24741. serializationObject.isVisible = this.isVisible;
  24742. serializationObject.infiniteDistance = this.infiniteDistance;
  24743. serializationObject.pickable = this.isPickable;
  24744. serializationObject.receiveShadows = this.receiveShadows;
  24745. serializationObject.billboardMode = this.billboardMode;
  24746. serializationObject.visibility = this.visibility;
  24747. serializationObject.checkCollisions = this.checkCollisions;
  24748. serializationObject.isBlocker = this.isBlocker;
  24749. // Parent
  24750. if (this.parent) {
  24751. serializationObject.parentId = this.parent.id;
  24752. }
  24753. // Geometry
  24754. var geometry = this._geometry;
  24755. if (geometry) {
  24756. var geometryId = geometry.id;
  24757. serializationObject.geometryId = geometryId;
  24758. // SubMeshes
  24759. serializationObject.subMeshes = [];
  24760. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24761. var subMesh = this.subMeshes[subIndex];
  24762. serializationObject.subMeshes.push({
  24763. materialIndex: subMesh.materialIndex,
  24764. verticesStart: subMesh.verticesStart,
  24765. verticesCount: subMesh.verticesCount,
  24766. indexStart: subMesh.indexStart,
  24767. indexCount: subMesh.indexCount
  24768. });
  24769. }
  24770. }
  24771. // Material
  24772. if (this.material) {
  24773. serializationObject.materialId = this.material.id;
  24774. }
  24775. else {
  24776. this.material = null;
  24777. }
  24778. // Morph targets
  24779. if (this.morphTargetManager) {
  24780. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  24781. }
  24782. // Skeleton
  24783. if (this.skeleton) {
  24784. serializationObject.skeletonId = this.skeleton.id;
  24785. }
  24786. // Physics
  24787. //TODO implement correct serialization for physics impostors.
  24788. var impostor = this.getPhysicsImpostor();
  24789. if (impostor) {
  24790. serializationObject.physicsMass = impostor.getParam("mass");
  24791. serializationObject.physicsFriction = impostor.getParam("friction");
  24792. serializationObject.physicsRestitution = impostor.getParam("mass");
  24793. serializationObject.physicsImpostor = impostor.type;
  24794. }
  24795. // Metadata
  24796. if (this.metadata) {
  24797. serializationObject.metadata = this.metadata;
  24798. }
  24799. // Instances
  24800. serializationObject.instances = [];
  24801. for (var index = 0; index < this.instances.length; index++) {
  24802. var instance = this.instances[index];
  24803. var serializationInstance = {
  24804. name: instance.name,
  24805. position: instance.position.asArray(),
  24806. scaling: instance.scaling.asArray()
  24807. };
  24808. if (instance.rotationQuaternion) {
  24809. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24810. }
  24811. else if (instance.rotation) {
  24812. serializationInstance.rotation = instance.rotation.asArray();
  24813. }
  24814. serializationObject.instances.push(serializationInstance);
  24815. // Animations
  24816. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24817. serializationInstance.ranges = instance.serializeAnimationRanges();
  24818. }
  24819. //
  24820. // Animations
  24821. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24822. serializationObject.ranges = this.serializeAnimationRanges();
  24823. // Layer mask
  24824. serializationObject.layerMask = this.layerMask;
  24825. // Alpha
  24826. serializationObject.alphaIndex = this.alphaIndex;
  24827. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24828. // Overlay
  24829. serializationObject.overlayAlpha = this.overlayAlpha;
  24830. serializationObject.overlayColor = this.overlayColor.asArray();
  24831. serializationObject.renderOverlay = this.renderOverlay;
  24832. // Fog
  24833. serializationObject.applyFog = this.applyFog;
  24834. // Action Manager
  24835. if (this.actionManager) {
  24836. serializationObject.actions = this.actionManager.serialize(this.name);
  24837. }
  24838. };
  24839. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  24840. if (!this.geometry) {
  24841. return;
  24842. }
  24843. this._markSubMeshesAsAttributesDirty();
  24844. var morphTargetManager = this._morphTargetManager;
  24845. if (morphTargetManager && morphTargetManager.vertexCount) {
  24846. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  24847. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  24848. this.morphTargetManager = null;
  24849. return;
  24850. }
  24851. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  24852. var morphTarget = morphTargetManager.getActiveTarget(index);
  24853. var positions = morphTarget.getPositions();
  24854. if (!positions) {
  24855. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  24856. return;
  24857. }
  24858. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  24859. var normals = morphTarget.getNormals();
  24860. if (normals) {
  24861. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  24862. }
  24863. var tangents = morphTarget.getTangents();
  24864. if (tangents) {
  24865. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  24866. }
  24867. }
  24868. }
  24869. else {
  24870. var index = 0;
  24871. // Positions
  24872. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  24873. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  24874. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  24875. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  24876. }
  24877. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  24878. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  24879. }
  24880. index++;
  24881. }
  24882. }
  24883. };
  24884. // Statics
  24885. /**
  24886. * Returns a new Mesh object parsed from the source provided.
  24887. * The parameter `parsedMesh` is the source.
  24888. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24889. */
  24890. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24891. var mesh;
  24892. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24893. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24894. }
  24895. else {
  24896. mesh = new Mesh(parsedMesh.name, scene);
  24897. }
  24898. mesh.id = parsedMesh.id;
  24899. if (BABYLON.Tags) {
  24900. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24901. }
  24902. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24903. if (parsedMesh.metadata !== undefined) {
  24904. mesh.metadata = parsedMesh.metadata;
  24905. }
  24906. if (parsedMesh.rotationQuaternion) {
  24907. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24908. }
  24909. else if (parsedMesh.rotation) {
  24910. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24911. }
  24912. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24913. if (parsedMesh.localMatrix) {
  24914. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24915. }
  24916. else if (parsedMesh.pivotMatrix) {
  24917. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24918. }
  24919. mesh.setEnabled(parsedMesh.isEnabled);
  24920. mesh.isVisible = parsedMesh.isVisible;
  24921. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24922. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24923. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24924. if (parsedMesh.applyFog !== undefined) {
  24925. mesh.applyFog = parsedMesh.applyFog;
  24926. }
  24927. if (parsedMesh.pickable !== undefined) {
  24928. mesh.isPickable = parsedMesh.pickable;
  24929. }
  24930. if (parsedMesh.alphaIndex !== undefined) {
  24931. mesh.alphaIndex = parsedMesh.alphaIndex;
  24932. }
  24933. mesh.receiveShadows = parsedMesh.receiveShadows;
  24934. mesh.billboardMode = parsedMesh.billboardMode;
  24935. if (parsedMesh.visibility !== undefined) {
  24936. mesh.visibility = parsedMesh.visibility;
  24937. }
  24938. mesh.checkCollisions = parsedMesh.checkCollisions;
  24939. if (parsedMesh.isBlocker !== undefined) {
  24940. mesh.isBlocker = parsedMesh.isBlocker;
  24941. }
  24942. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24943. // freezeWorldMatrix
  24944. if (parsedMesh.freezeWorldMatrix) {
  24945. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24946. }
  24947. // Parent
  24948. if (parsedMesh.parentId) {
  24949. mesh._waitingParentId = parsedMesh.parentId;
  24950. }
  24951. // Actions
  24952. if (parsedMesh.actions !== undefined) {
  24953. mesh._waitingActions = parsedMesh.actions;
  24954. }
  24955. // Overlay
  24956. if (parsedMesh.overlayAlpha !== undefined) {
  24957. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24958. }
  24959. if (parsedMesh.overlayColor !== undefined) {
  24960. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24961. }
  24962. if (parsedMesh.renderOverlay !== undefined) {
  24963. mesh.renderOverlay = parsedMesh.renderOverlay;
  24964. }
  24965. // Geometry
  24966. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24967. if (parsedMesh.delayLoadingFile) {
  24968. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24969. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24970. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24971. if (parsedMesh._binaryInfo) {
  24972. mesh._binaryInfo = parsedMesh._binaryInfo;
  24973. }
  24974. mesh._delayInfo = [];
  24975. if (parsedMesh.hasUVs) {
  24976. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24977. }
  24978. if (parsedMesh.hasUVs2) {
  24979. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24980. }
  24981. if (parsedMesh.hasUVs3) {
  24982. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24983. }
  24984. if (parsedMesh.hasUVs4) {
  24985. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24986. }
  24987. if (parsedMesh.hasUVs5) {
  24988. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24989. }
  24990. if (parsedMesh.hasUVs6) {
  24991. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24992. }
  24993. if (parsedMesh.hasColors) {
  24994. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24995. }
  24996. if (parsedMesh.hasMatricesIndices) {
  24997. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24998. }
  24999. if (parsedMesh.hasMatricesWeights) {
  25000. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25001. }
  25002. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  25003. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  25004. mesh._checkDelayState();
  25005. }
  25006. }
  25007. else {
  25008. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  25009. }
  25010. // Material
  25011. if (parsedMesh.materialId) {
  25012. mesh.setMaterialByID(parsedMesh.materialId);
  25013. }
  25014. else {
  25015. mesh.material = null;
  25016. }
  25017. // Morph targets
  25018. if (parsedMesh.morphTargetManagerId > -1) {
  25019. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  25020. }
  25021. // Skeleton
  25022. if (parsedMesh.skeletonId > -1) {
  25023. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  25024. if (parsedMesh.numBoneInfluencers) {
  25025. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  25026. }
  25027. }
  25028. // Animations
  25029. if (parsedMesh.animations) {
  25030. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25031. var parsedAnimation = parsedMesh.animations[animationIndex];
  25032. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25033. }
  25034. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  25035. }
  25036. if (parsedMesh.autoAnimate) {
  25037. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  25038. }
  25039. // Layer Mask
  25040. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  25041. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  25042. }
  25043. else {
  25044. mesh.layerMask = 0x0FFFFFFF;
  25045. }
  25046. // Physics
  25047. if (parsedMesh.physicsImpostor) {
  25048. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  25049. mass: parsedMesh.physicsMass,
  25050. friction: parsedMesh.physicsFriction,
  25051. restitution: parsedMesh.physicsRestitution
  25052. }, scene);
  25053. }
  25054. // Instances
  25055. if (parsedMesh.instances) {
  25056. for (var index = 0; index < parsedMesh.instances.length; index++) {
  25057. var parsedInstance = parsedMesh.instances[index];
  25058. var instance = mesh.createInstance(parsedInstance.name);
  25059. if (BABYLON.Tags) {
  25060. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  25061. }
  25062. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  25063. if (parsedInstance.parentId) {
  25064. instance._waitingParentId = parsedInstance.parentId;
  25065. }
  25066. if (parsedInstance.rotationQuaternion) {
  25067. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  25068. }
  25069. else if (parsedInstance.rotation) {
  25070. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  25071. }
  25072. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  25073. instance.checkCollisions = mesh.checkCollisions;
  25074. if (parsedMesh.animations) {
  25075. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25076. parsedAnimation = parsedMesh.animations[animationIndex];
  25077. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25078. }
  25079. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  25080. }
  25081. }
  25082. }
  25083. return mesh;
  25084. };
  25085. /**
  25086. * Creates a ribbon mesh.
  25087. * Please consider using the same method from the MeshBuilder class instead.
  25088. * 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.
  25089. *
  25090. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25091. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25092. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25093. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25094. * 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.
  25095. * 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.
  25096. * 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
  25097. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25098. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25099. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25100. */
  25101. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  25102. if (closeArray === void 0) { closeArray = false; }
  25103. if (updatable === void 0) { updatable = false; }
  25104. return BABYLON.MeshBuilder.CreateRibbon(name, {
  25105. pathArray: pathArray,
  25106. closeArray: closeArray,
  25107. closePath: closePath,
  25108. offset: offset,
  25109. updatable: updatable,
  25110. sideOrientation: sideOrientation,
  25111. instance: instance
  25112. }, scene);
  25113. };
  25114. /**
  25115. * Creates a plane polygonal mesh. By default, this is a disc.
  25116. * Please consider using the same method from the MeshBuilder class instead.
  25117. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25118. * 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.
  25119. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25120. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25121. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25122. */
  25123. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  25124. if (scene === void 0) { scene = null; }
  25125. var options = {
  25126. radius: radius,
  25127. tessellation: tessellation,
  25128. sideOrientation: sideOrientation,
  25129. updatable: updatable
  25130. };
  25131. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  25132. };
  25133. /**
  25134. * Creates a box mesh.
  25135. * Please consider using the same method from the MeshBuilder class instead.
  25136. * The parameter `size` sets the size (float) of each box side (default 1).
  25137. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25138. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25139. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25140. */
  25141. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  25142. if (scene === void 0) { scene = null; }
  25143. var options = {
  25144. size: size,
  25145. sideOrientation: sideOrientation,
  25146. updatable: updatable
  25147. };
  25148. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  25149. };
  25150. /**
  25151. * Creates a sphere mesh.
  25152. * Please consider using the same method from the MeshBuilder class instead.
  25153. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25154. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25155. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25156. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25157. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25158. */
  25159. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  25160. var options = {
  25161. segments: segments,
  25162. diameterX: diameter,
  25163. diameterY: diameter,
  25164. diameterZ: diameter,
  25165. sideOrientation: sideOrientation,
  25166. updatable: updatable
  25167. };
  25168. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  25169. };
  25170. /**
  25171. * Creates a cylinder or a cone mesh.
  25172. * Please consider using the same method from the MeshBuilder class instead.
  25173. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25174. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25175. * 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.
  25176. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25177. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25178. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25179. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25180. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25181. */
  25182. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  25183. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  25184. if (scene !== undefined) {
  25185. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  25186. updatable = scene;
  25187. }
  25188. scene = subdivisions;
  25189. subdivisions = 1;
  25190. }
  25191. var options = {
  25192. height: height,
  25193. diameterTop: diameterTop,
  25194. diameterBottom: diameterBottom,
  25195. tessellation: tessellation,
  25196. subdivisions: subdivisions,
  25197. sideOrientation: sideOrientation,
  25198. updatable: updatable
  25199. };
  25200. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  25201. };
  25202. // Torus (Code from SharpDX.org)
  25203. /**
  25204. * Creates a torus mesh.
  25205. * Please consider using the same method from the MeshBuilder class instead.
  25206. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25207. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25208. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25209. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25210. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25211. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25212. */
  25213. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  25214. var options = {
  25215. diameter: diameter,
  25216. thickness: thickness,
  25217. tessellation: tessellation,
  25218. sideOrientation: sideOrientation,
  25219. updatable: updatable
  25220. };
  25221. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  25222. };
  25223. /**
  25224. * Creates a torus knot mesh.
  25225. * Please consider using the same method from the MeshBuilder class instead.
  25226. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25227. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25228. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25229. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25230. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25231. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25232. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25233. */
  25234. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  25235. var options = {
  25236. radius: radius,
  25237. tube: tube,
  25238. radialSegments: radialSegments,
  25239. tubularSegments: tubularSegments,
  25240. p: p,
  25241. q: q,
  25242. sideOrientation: sideOrientation,
  25243. updatable: updatable
  25244. };
  25245. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  25246. };
  25247. /**
  25248. * Creates a line mesh.
  25249. * Please consider using the same method from the MeshBuilder class instead.
  25250. * 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.
  25251. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25252. * The parameter `points` is an array successive Vector3.
  25253. * 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
  25254. * When updating an instance, remember that only point positions can change, not the number of points.
  25255. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25256. */
  25257. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  25258. if (scene === void 0) { scene = null; }
  25259. if (updatable === void 0) { updatable = false; }
  25260. if (instance === void 0) { instance = null; }
  25261. var options = {
  25262. points: points,
  25263. updatable: updatable,
  25264. instance: instance
  25265. };
  25266. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  25267. };
  25268. /**
  25269. * Creates a dashed line mesh.
  25270. * Please consider using the same method from the MeshBuilder class instead.
  25271. * 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.
  25272. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25273. * The parameter `points` is an array successive Vector3.
  25274. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25275. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25276. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25277. * 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
  25278. * When updating an instance, remember that only point positions can change, not the number of points.
  25279. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25280. */
  25281. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  25282. if (scene === void 0) { scene = null; }
  25283. var options = {
  25284. points: points,
  25285. dashSize: dashSize,
  25286. gapSize: gapSize,
  25287. dashNb: dashNb,
  25288. updatable: updatable,
  25289. instance: instance
  25290. };
  25291. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  25292. };
  25293. /**
  25294. * Creates a polygon mesh.
  25295. * Please consider using the same method from the MeshBuilder class instead.
  25296. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  25297. * 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.
  25298. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25299. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25300. * Remember you can only change the shape positions, not their number when updating a polygon.
  25301. */
  25302. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  25303. var options = {
  25304. shape: shape,
  25305. holes: holes,
  25306. updatable: updatable,
  25307. sideOrientation: sideOrientation
  25308. };
  25309. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  25310. };
  25311. /**
  25312. * Creates an extruded polygon mesh, with depth in the Y direction.
  25313. * Please consider using the same method from the MeshBuilder class instead.
  25314. */
  25315. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  25316. var options = {
  25317. shape: shape,
  25318. holes: holes,
  25319. depth: depth,
  25320. updatable: updatable,
  25321. sideOrientation: sideOrientation
  25322. };
  25323. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  25324. };
  25325. /**
  25326. * Creates an extruded shape mesh.
  25327. * 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.
  25328. * Please consider using the same method from the MeshBuilder class instead.
  25329. *
  25330. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25331. * 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
  25332. * extruded along the Z axis.
  25333. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25334. * 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.
  25335. * The parameter `scale` (float, default 1) is the value to scale the shape.
  25336. * 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
  25337. * 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
  25338. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25339. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25340. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25341. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25342. */
  25343. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  25344. if (scene === void 0) { scene = null; }
  25345. var options = {
  25346. shape: shape,
  25347. path: path,
  25348. scale: scale,
  25349. rotation: rotation,
  25350. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25351. sideOrientation: sideOrientation,
  25352. instance: instance,
  25353. updatable: updatable
  25354. };
  25355. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  25356. };
  25357. /**
  25358. * Creates an custom extruded shape mesh.
  25359. * 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.
  25360. * Please consider using the same method from the MeshBuilder class instead.
  25361. *
  25362. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25363. * 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
  25364. * extruded along the Z axis.
  25365. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25366. * 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
  25367. * and the distance of this point from the begining of the path :
  25368. * ```javascript
  25369. * var rotationFunction = function(i, distance) {
  25370. * // do things
  25371. * return rotationValue; }
  25372. * ```
  25373. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25374. * 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
  25375. * and the distance of this point from the begining of the path :
  25376. * ```javascript
  25377. * var scaleFunction = function(i, distance) {
  25378. * // do things
  25379. * return scaleValue;}
  25380. * ```
  25381. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25382. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25383. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25384. * 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
  25385. * 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
  25386. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25387. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25388. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25389. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25390. */
  25391. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  25392. var options = {
  25393. shape: shape,
  25394. path: path,
  25395. scaleFunction: scaleFunction,
  25396. rotationFunction: rotationFunction,
  25397. ribbonCloseArray: ribbonCloseArray,
  25398. ribbonClosePath: ribbonClosePath,
  25399. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25400. sideOrientation: sideOrientation,
  25401. instance: instance,
  25402. updatable: updatable
  25403. };
  25404. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  25405. };
  25406. /**
  25407. * Creates lathe mesh.
  25408. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25409. * Please consider using the same method from the MeshBuilder class instead.
  25410. * 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
  25411. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25412. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25413. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25414. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25415. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25416. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25417. */
  25418. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  25419. var options = {
  25420. shape: shape,
  25421. radius: radius,
  25422. tessellation: tessellation,
  25423. sideOrientation: sideOrientation,
  25424. updatable: updatable
  25425. };
  25426. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  25427. };
  25428. /**
  25429. * Creates a plane mesh.
  25430. * Please consider using the same method from the MeshBuilder class instead.
  25431. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25432. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25433. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25434. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25435. */
  25436. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  25437. var options = {
  25438. size: size,
  25439. width: size,
  25440. height: size,
  25441. sideOrientation: sideOrientation,
  25442. updatable: updatable
  25443. };
  25444. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  25445. };
  25446. /**
  25447. * Creates a ground mesh.
  25448. * Please consider using the same method from the MeshBuilder class instead.
  25449. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25450. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25451. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25452. */
  25453. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25454. var options = {
  25455. width: width,
  25456. height: height,
  25457. subdivisions: subdivisions,
  25458. updatable: updatable
  25459. };
  25460. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25461. };
  25462. /**
  25463. * Creates a tiled ground mesh.
  25464. * Please consider using the same method from the MeshBuilder class instead.
  25465. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25466. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25467. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25468. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25469. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25470. * numbers of subdivisions on the ground width and height of each tile.
  25471. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25472. */
  25473. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25474. var options = {
  25475. xmin: xmin,
  25476. zmin: zmin,
  25477. xmax: xmax,
  25478. zmax: zmax,
  25479. subdivisions: subdivisions,
  25480. precision: precision,
  25481. updatable: updatable
  25482. };
  25483. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25484. };
  25485. /**
  25486. * Creates a ground mesh from a height map.
  25487. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25488. * Please consider using the same method from the MeshBuilder class instead.
  25489. * The parameter `url` sets the URL of the height map image resource.
  25490. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25491. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25492. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25493. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25494. * 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).
  25495. * This function is passed the newly built mesh :
  25496. * ```javascript
  25497. * function(mesh) { // do things
  25498. * return; }
  25499. * ```
  25500. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25501. */
  25502. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25503. var options = {
  25504. width: width,
  25505. height: height,
  25506. subdivisions: subdivisions,
  25507. minHeight: minHeight,
  25508. maxHeight: maxHeight,
  25509. updatable: updatable,
  25510. onReady: onReady
  25511. };
  25512. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25513. };
  25514. /**
  25515. * Creates a tube mesh.
  25516. * 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.
  25517. * Please consider using the same method from the MeshBuilder class instead.
  25518. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25519. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25520. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25521. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25522. * 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.
  25523. * It must return a radius value (positive float) :
  25524. * ```javascript
  25525. * var radiusFunction = function(i, distance) {
  25526. * // do things
  25527. * return radius; }
  25528. * ```
  25529. * 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
  25530. * 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
  25531. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25532. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25534. */
  25535. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25536. var options = {
  25537. path: path,
  25538. radius: radius,
  25539. tessellation: tessellation,
  25540. radiusFunction: radiusFunction,
  25541. arc: 1,
  25542. cap: cap,
  25543. updatable: updatable,
  25544. sideOrientation: sideOrientation,
  25545. instance: instance
  25546. };
  25547. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25548. };
  25549. /**
  25550. * Creates a polyhedron mesh.
  25551. * Please consider using the same method from the MeshBuilder class instead.
  25552. * 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
  25553. * to choose the wanted type.
  25554. * The parameter `size` (positive float, default 1) sets the polygon size.
  25555. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25556. * 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`.
  25557. * 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
  25558. * 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)`).
  25559. * 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
  25560. * 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.
  25561. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25562. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25563. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25564. */
  25565. Mesh.CreatePolyhedron = function (name, options, scene) {
  25566. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25567. };
  25568. /**
  25569. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25570. * Please consider using the same method from the MeshBuilder class instead.
  25571. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25572. * 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`).
  25573. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25574. * 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.
  25575. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25576. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25577. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25578. */
  25579. Mesh.CreateIcoSphere = function (name, options, scene) {
  25580. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25581. };
  25582. /**
  25583. * Creates a decal mesh.
  25584. * Please consider using the same method from the MeshBuilder class instead.
  25585. * 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.
  25586. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25587. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25588. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25589. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25590. */
  25591. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25592. var options = {
  25593. position: position,
  25594. normal: normal,
  25595. size: size,
  25596. angle: angle
  25597. };
  25598. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25599. };
  25600. // Skeletons
  25601. /**
  25602. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25603. */
  25604. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25605. if (!this._sourcePositions) {
  25606. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25607. if (!source) {
  25608. return this._sourcePositions;
  25609. }
  25610. this._sourcePositions = new Float32Array(source);
  25611. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  25612. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25613. }
  25614. }
  25615. return this._sourcePositions;
  25616. };
  25617. /**
  25618. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25619. */
  25620. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25621. if (!this._sourceNormals) {
  25622. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25623. if (!source) {
  25624. return this._sourceNormals;
  25625. }
  25626. this._sourceNormals = new Float32Array(source);
  25627. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  25628. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25629. }
  25630. }
  25631. return this._sourceNormals;
  25632. };
  25633. /**
  25634. * Updates the vertex buffer by applying transformation from the bones.
  25635. * Returns the Mesh.
  25636. *
  25637. * @param {skeleton} skeleton to apply
  25638. */
  25639. Mesh.prototype.applySkeleton = function (skeleton) {
  25640. if (!this.geometry) {
  25641. return this;
  25642. }
  25643. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25644. return this;
  25645. }
  25646. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25647. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25648. return this;
  25649. }
  25650. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25651. return this;
  25652. }
  25653. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25654. return this;
  25655. }
  25656. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25657. return this;
  25658. }
  25659. if (!this._sourcePositions) {
  25660. var submeshes = this.subMeshes.slice();
  25661. this.setPositionsForCPUSkinning();
  25662. this.subMeshes = submeshes;
  25663. }
  25664. if (!this._sourceNormals) {
  25665. this.setNormalsForCPUSkinning();
  25666. }
  25667. // positionsData checks for not being Float32Array will only pass at most once
  25668. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25669. if (!positionsData) {
  25670. return this;
  25671. }
  25672. if (!(positionsData instanceof Float32Array)) {
  25673. positionsData = new Float32Array(positionsData);
  25674. }
  25675. // normalsData checks for not being Float32Array will only pass at most once
  25676. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25677. if (!normalsData) {
  25678. return this;
  25679. }
  25680. if (!(normalsData instanceof Float32Array)) {
  25681. normalsData = new Float32Array(normalsData);
  25682. }
  25683. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25684. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25685. if (!matricesWeightsData || !matricesIndicesData) {
  25686. return this;
  25687. }
  25688. var needExtras = this.numBoneInfluencers > 4;
  25689. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25690. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25691. if (!matricesWeightsExtraData || !matricesIndicesExtraData) {
  25692. return this;
  25693. }
  25694. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25695. var tempVector3 = BABYLON.Vector3.Zero();
  25696. var finalMatrix = new BABYLON.Matrix();
  25697. var tempMatrix = new BABYLON.Matrix();
  25698. var matWeightIdx = 0;
  25699. var inf;
  25700. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25701. var weight;
  25702. for (inf = 0; inf < 4; inf++) {
  25703. weight = matricesWeightsData[matWeightIdx + inf];
  25704. if (weight > 0) {
  25705. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25706. finalMatrix.addToSelf(tempMatrix);
  25707. }
  25708. else
  25709. break;
  25710. }
  25711. if (needExtras) {
  25712. for (inf = 0; inf < 4; inf++) {
  25713. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25714. if (weight > 0) {
  25715. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25716. finalMatrix.addToSelf(tempMatrix);
  25717. }
  25718. else
  25719. break;
  25720. }
  25721. }
  25722. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25723. tempVector3.toArray(positionsData, index);
  25724. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25725. tempVector3.toArray(normalsData, index);
  25726. finalMatrix.reset();
  25727. }
  25728. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25729. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25730. return this;
  25731. };
  25732. // Tools
  25733. /**
  25734. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25735. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25736. */
  25737. Mesh.MinMax = function (meshes) {
  25738. var minVector = null;
  25739. var maxVector = null;
  25740. meshes.forEach(function (mesh, index, array) {
  25741. var boundingInfo = mesh.getBoundingInfo();
  25742. var boundingBox = boundingInfo.boundingBox;
  25743. if (!minVector || !maxVector) {
  25744. minVector = boundingBox.minimumWorld;
  25745. maxVector = boundingBox.maximumWorld;
  25746. }
  25747. else {
  25748. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25749. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25750. }
  25751. });
  25752. if (!minVector || !maxVector) {
  25753. return {
  25754. min: BABYLON.Vector3.Zero(),
  25755. max: BABYLON.Vector3.Zero()
  25756. };
  25757. }
  25758. return {
  25759. min: minVector,
  25760. max: maxVector
  25761. };
  25762. };
  25763. /**
  25764. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25765. */
  25766. Mesh.Center = function (meshesOrMinMaxVector) {
  25767. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25768. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25769. };
  25770. /**
  25771. * Merge the array of meshes into a single mesh for performance reasons.
  25772. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25773. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25774. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25775. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25776. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25777. */
  25778. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25779. if (disposeSource === void 0) { disposeSource = true; }
  25780. var index;
  25781. if (!allow32BitsIndices) {
  25782. var totalVertices = 0;
  25783. // Counting vertices
  25784. for (index = 0; index < meshes.length; index++) {
  25785. if (meshes[index]) {
  25786. totalVertices += meshes[index].getTotalVertices();
  25787. if (totalVertices > 65536) {
  25788. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25789. return null;
  25790. }
  25791. }
  25792. }
  25793. }
  25794. // Merge
  25795. var vertexData = null;
  25796. var otherVertexData;
  25797. var indiceArray = new Array();
  25798. var source = null;
  25799. for (index = 0; index < meshes.length; index++) {
  25800. if (meshes[index]) {
  25801. meshes[index].computeWorldMatrix(true);
  25802. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25803. otherVertexData.transform(meshes[index].getWorldMatrix());
  25804. if (vertexData) {
  25805. vertexData.merge(otherVertexData);
  25806. }
  25807. else {
  25808. vertexData = otherVertexData;
  25809. source = meshes[index];
  25810. }
  25811. if (subdivideWithSubMeshes) {
  25812. indiceArray.push(meshes[index].getTotalIndices());
  25813. }
  25814. }
  25815. }
  25816. source = source;
  25817. if (!meshSubclass) {
  25818. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25819. }
  25820. vertexData.applyToMesh(meshSubclass);
  25821. // Setting properties
  25822. meshSubclass.material = source.material;
  25823. meshSubclass.checkCollisions = source.checkCollisions;
  25824. // Cleaning
  25825. if (disposeSource) {
  25826. for (index = 0; index < meshes.length; index++) {
  25827. if (meshes[index]) {
  25828. meshes[index].dispose();
  25829. }
  25830. }
  25831. }
  25832. // Subdivide
  25833. if (subdivideWithSubMeshes) {
  25834. //-- Suppresions du submesh global
  25835. meshSubclass.releaseSubMeshes();
  25836. index = 0;
  25837. var offset = 0;
  25838. //-- aplique la subdivision en fonction du tableau d'indices
  25839. while (index < indiceArray.length) {
  25840. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25841. offset += indiceArray[index];
  25842. index++;
  25843. }
  25844. }
  25845. return meshSubclass;
  25846. };
  25847. // Consts
  25848. Mesh._FRONTSIDE = 0;
  25849. Mesh._BACKSIDE = 1;
  25850. Mesh._DOUBLESIDE = 2;
  25851. Mesh._DEFAULTSIDE = 0;
  25852. Mesh._NO_CAP = 0;
  25853. Mesh._CAP_START = 1;
  25854. Mesh._CAP_END = 2;
  25855. Mesh._CAP_ALL = 3;
  25856. return Mesh;
  25857. }(BABYLON.AbstractMesh));
  25858. BABYLON.Mesh = Mesh;
  25859. })(BABYLON || (BABYLON = {}));
  25860. //# sourceMappingURL=babylon.mesh.js.map
  25861. var BABYLON;
  25862. (function (BABYLON) {
  25863. var BaseSubMesh = /** @class */ (function () {
  25864. function BaseSubMesh() {
  25865. }
  25866. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  25867. get: function () {
  25868. return this._materialEffect;
  25869. },
  25870. enumerable: true,
  25871. configurable: true
  25872. });
  25873. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  25874. if (defines === void 0) { defines = null; }
  25875. if (this._materialEffect === effect) {
  25876. if (!effect) {
  25877. this._materialDefines = null;
  25878. }
  25879. return;
  25880. }
  25881. this._materialDefines = defines;
  25882. this._materialEffect = effect;
  25883. };
  25884. return BaseSubMesh;
  25885. }());
  25886. BABYLON.BaseSubMesh = BaseSubMesh;
  25887. var SubMesh = /** @class */ (function (_super) {
  25888. __extends(SubMesh, _super);
  25889. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25890. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25891. var _this = _super.call(this) || this;
  25892. _this.materialIndex = materialIndex;
  25893. _this.verticesStart = verticesStart;
  25894. _this.verticesCount = verticesCount;
  25895. _this.indexStart = indexStart;
  25896. _this.indexCount = indexCount;
  25897. _this._renderId = 0;
  25898. _this._mesh = mesh;
  25899. _this._renderingMesh = renderingMesh || mesh;
  25900. mesh.subMeshes.push(_this);
  25901. _this._trianglePlanes = [];
  25902. _this._id = mesh.subMeshes.length - 1;
  25903. if (createBoundingBox) {
  25904. _this.refreshBoundingInfo();
  25905. mesh.computeWorldMatrix(true);
  25906. }
  25907. return _this;
  25908. }
  25909. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25910. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25911. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  25912. };
  25913. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25914. get: function () {
  25915. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25916. },
  25917. enumerable: true,
  25918. configurable: true
  25919. });
  25920. /**
  25921. * Returns the submesh BoudingInfo object.
  25922. */
  25923. SubMesh.prototype.getBoundingInfo = function () {
  25924. if (this.IsGlobal) {
  25925. return this._mesh.getBoundingInfo();
  25926. }
  25927. return this._boundingInfo;
  25928. };
  25929. /**
  25930. * Sets the submesh BoundingInfo.
  25931. * Return the SubMesh.
  25932. */
  25933. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25934. this._boundingInfo = boundingInfo;
  25935. return this;
  25936. };
  25937. /**
  25938. * Returns the mesh of the current submesh.
  25939. */
  25940. SubMesh.prototype.getMesh = function () {
  25941. return this._mesh;
  25942. };
  25943. /**
  25944. * Returns the rendering mesh of the submesh.
  25945. */
  25946. SubMesh.prototype.getRenderingMesh = function () {
  25947. return this._renderingMesh;
  25948. };
  25949. /**
  25950. * Returns the submesh material.
  25951. */
  25952. SubMesh.prototype.getMaterial = function () {
  25953. var rootMaterial = this._renderingMesh.material;
  25954. if (rootMaterial && rootMaterial.getSubMaterial) {
  25955. var multiMaterial = rootMaterial;
  25956. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  25957. if (this._currentMaterial !== effectiveMaterial) {
  25958. this._currentMaterial = effectiveMaterial;
  25959. this._materialDefines = null;
  25960. }
  25961. return effectiveMaterial;
  25962. }
  25963. if (!rootMaterial) {
  25964. return this._mesh.getScene().defaultMaterial;
  25965. }
  25966. return rootMaterial;
  25967. };
  25968. // Methods
  25969. /**
  25970. * Sets a new updated BoundingInfo object to the submesh.
  25971. * Returns the SubMesh.
  25972. */
  25973. SubMesh.prototype.refreshBoundingInfo = function () {
  25974. this._lastColliderWorldVertices = null;
  25975. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  25976. return this;
  25977. }
  25978. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25979. if (!data) {
  25980. this._boundingInfo = this._mesh.getBoundingInfo();
  25981. return this;
  25982. }
  25983. var indices = this._renderingMesh.getIndices();
  25984. var extend;
  25985. //is this the only submesh?
  25986. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25987. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25988. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25989. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  25990. }
  25991. else {
  25992. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25993. }
  25994. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25995. return this;
  25996. };
  25997. SubMesh.prototype._checkCollision = function (collider) {
  25998. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25999. return boundingInfo._checkCollision(collider);
  26000. };
  26001. /**
  26002. * Updates the submesh BoundingInfo.
  26003. * Returns the Submesh.
  26004. */
  26005. SubMesh.prototype.updateBoundingInfo = function (world) {
  26006. var boundingInfo = this.getBoundingInfo();
  26007. if (!boundingInfo) {
  26008. this.refreshBoundingInfo();
  26009. boundingInfo = this.getBoundingInfo();
  26010. }
  26011. boundingInfo.update(world);
  26012. return this;
  26013. };
  26014. /**
  26015. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  26016. * Boolean returned.
  26017. */
  26018. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  26019. var boundingInfo = this.getBoundingInfo();
  26020. if (!boundingInfo) {
  26021. return false;
  26022. }
  26023. return boundingInfo.isInFrustum(frustumPlanes);
  26024. };
  26025. /**
  26026. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  26027. * Boolean returned.
  26028. */
  26029. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  26030. var boundingInfo = this.getBoundingInfo();
  26031. if (!boundingInfo) {
  26032. return false;
  26033. }
  26034. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  26035. };
  26036. /**
  26037. * Renders the submesh.
  26038. * Returns it.
  26039. */
  26040. SubMesh.prototype.render = function (enableAlphaMode) {
  26041. this._renderingMesh.render(this, enableAlphaMode);
  26042. return this;
  26043. };
  26044. /**
  26045. * Returns a new Index Buffer.
  26046. * Type returned : WebGLBuffer.
  26047. */
  26048. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  26049. if (!this._linesIndexBuffer) {
  26050. var linesIndices = [];
  26051. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26052. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  26053. }
  26054. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  26055. this.linesIndexCount = linesIndices.length;
  26056. }
  26057. return this._linesIndexBuffer;
  26058. };
  26059. /**
  26060. * True is the passed Ray intersects the submesh bounding box.
  26061. * Boolean returned.
  26062. */
  26063. SubMesh.prototype.canIntersects = function (ray) {
  26064. var boundingInfo = this.getBoundingInfo();
  26065. if (!boundingInfo) {
  26066. return false;
  26067. }
  26068. return ray.intersectsBox(boundingInfo.boundingBox);
  26069. };
  26070. /**
  26071. * Returns an object IntersectionInfo.
  26072. */
  26073. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  26074. var intersectInfo = null;
  26075. // LineMesh first as it's also a Mesh...
  26076. if (this._mesh instanceof BABYLON.LinesMesh) {
  26077. var lineMesh = this._mesh;
  26078. // Line test
  26079. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  26080. var p0 = positions[indices[index]];
  26081. var p1 = positions[indices[index + 1]];
  26082. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  26083. if (length < 0) {
  26084. continue;
  26085. }
  26086. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  26087. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  26088. if (fastCheck) {
  26089. break;
  26090. }
  26091. }
  26092. }
  26093. }
  26094. else {
  26095. // Triangles test
  26096. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26097. var p0 = positions[indices[index]];
  26098. var p1 = positions[indices[index + 1]];
  26099. var p2 = positions[indices[index + 2]];
  26100. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  26101. if (currentIntersectInfo) {
  26102. if (currentIntersectInfo.distance < 0) {
  26103. continue;
  26104. }
  26105. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  26106. intersectInfo = currentIntersectInfo;
  26107. intersectInfo.faceId = index / 3;
  26108. if (fastCheck) {
  26109. break;
  26110. }
  26111. }
  26112. }
  26113. }
  26114. }
  26115. return intersectInfo;
  26116. };
  26117. SubMesh.prototype._rebuild = function () {
  26118. if (this._linesIndexBuffer) {
  26119. this._linesIndexBuffer = null;
  26120. }
  26121. };
  26122. // Clone
  26123. /**
  26124. * Creates a new Submesh from the passed Mesh.
  26125. */
  26126. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  26127. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  26128. if (!this.IsGlobal) {
  26129. var boundingInfo = this.getBoundingInfo();
  26130. if (!boundingInfo) {
  26131. return result;
  26132. }
  26133. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  26134. }
  26135. return result;
  26136. };
  26137. // Dispose
  26138. /**
  26139. * Disposes the Submesh.
  26140. * Returns nothing.
  26141. */
  26142. SubMesh.prototype.dispose = function () {
  26143. if (this._linesIndexBuffer) {
  26144. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  26145. this._linesIndexBuffer = null;
  26146. }
  26147. // Remove from mesh
  26148. var index = this._mesh.subMeshes.indexOf(this);
  26149. this._mesh.subMeshes.splice(index, 1);
  26150. };
  26151. // Statics
  26152. /**
  26153. * Creates a new Submesh from the passed parameters :
  26154. * - materialIndex (integer) : the index of the main mesh material.
  26155. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  26156. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  26157. * - mesh (Mesh) : the main mesh to create the submesh from.
  26158. * - renderingMesh (optional Mesh) : rendering mesh.
  26159. */
  26160. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  26161. var minVertexIndex = Number.MAX_VALUE;
  26162. var maxVertexIndex = -Number.MAX_VALUE;
  26163. renderingMesh = (renderingMesh || mesh);
  26164. var indices = renderingMesh.getIndices();
  26165. for (var index = startIndex; index < startIndex + indexCount; index++) {
  26166. var vertexIndex = indices[index];
  26167. if (vertexIndex < minVertexIndex)
  26168. minVertexIndex = vertexIndex;
  26169. if (vertexIndex > maxVertexIndex)
  26170. maxVertexIndex = vertexIndex;
  26171. }
  26172. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  26173. };
  26174. return SubMesh;
  26175. }(BaseSubMesh));
  26176. BABYLON.SubMesh = SubMesh;
  26177. })(BABYLON || (BABYLON = {}));
  26178. //# sourceMappingURL=babylon.subMesh.js.map
  26179. var BABYLON;
  26180. (function (BABYLON) {
  26181. var EffectFallbacks = /** @class */ (function () {
  26182. function EffectFallbacks() {
  26183. this._defines = {};
  26184. this._currentRank = 32;
  26185. this._maxRank = -1;
  26186. }
  26187. EffectFallbacks.prototype.unBindMesh = function () {
  26188. this._mesh = null;
  26189. };
  26190. EffectFallbacks.prototype.addFallback = function (rank, define) {
  26191. if (!this._defines[rank]) {
  26192. if (rank < this._currentRank) {
  26193. this._currentRank = rank;
  26194. }
  26195. if (rank > this._maxRank) {
  26196. this._maxRank = rank;
  26197. }
  26198. this._defines[rank] = new Array();
  26199. }
  26200. this._defines[rank].push(define);
  26201. };
  26202. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  26203. this._mesh = mesh;
  26204. if (rank < this._currentRank) {
  26205. this._currentRank = rank;
  26206. }
  26207. if (rank > this._maxRank) {
  26208. this._maxRank = rank;
  26209. }
  26210. };
  26211. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  26212. get: function () {
  26213. return this._currentRank <= this._maxRank;
  26214. },
  26215. enumerable: true,
  26216. configurable: true
  26217. });
  26218. EffectFallbacks.prototype.reduce = function (currentDefines) {
  26219. // First we try to switch to CPU skinning
  26220. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  26221. this._mesh.computeBonesUsingShaders = false;
  26222. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  26223. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  26224. var scene = this._mesh.getScene();
  26225. for (var index = 0; index < scene.meshes.length; index++) {
  26226. var otherMesh = scene.meshes[index];
  26227. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  26228. otherMesh.computeBonesUsingShaders = false;
  26229. }
  26230. }
  26231. }
  26232. else {
  26233. var currentFallbacks = this._defines[this._currentRank];
  26234. if (currentFallbacks) {
  26235. for (var index = 0; index < currentFallbacks.length; index++) {
  26236. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  26237. }
  26238. }
  26239. this._currentRank++;
  26240. }
  26241. return currentDefines;
  26242. };
  26243. return EffectFallbacks;
  26244. }());
  26245. BABYLON.EffectFallbacks = EffectFallbacks;
  26246. var EffectCreationOptions = /** @class */ (function () {
  26247. function EffectCreationOptions() {
  26248. }
  26249. return EffectCreationOptions;
  26250. }());
  26251. BABYLON.EffectCreationOptions = EffectCreationOptions;
  26252. var Effect = /** @class */ (function () {
  26253. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  26254. if (samplers === void 0) { samplers = null; }
  26255. if (defines === void 0) { defines = null; }
  26256. if (fallbacks === void 0) { fallbacks = null; }
  26257. if (onCompiled === void 0) { onCompiled = null; }
  26258. if (onError === void 0) { onError = null; }
  26259. var _this = this;
  26260. this.uniqueId = 0;
  26261. this.onCompileObservable = new BABYLON.Observable();
  26262. this.onErrorObservable = new BABYLON.Observable();
  26263. this.onBindObservable = new BABYLON.Observable();
  26264. this._uniformBuffersNames = {};
  26265. this._isReady = false;
  26266. this._compilationError = "";
  26267. this.name = baseName;
  26268. if (attributesNamesOrOptions.attributes) {
  26269. var options = attributesNamesOrOptions;
  26270. this._engine = uniformsNamesOrEngine;
  26271. this._attributesNames = options.attributes;
  26272. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  26273. this._samplers = options.samplers;
  26274. this.defines = options.defines;
  26275. this.onError = options.onError;
  26276. this.onCompiled = options.onCompiled;
  26277. this._fallbacks = options.fallbacks;
  26278. this._indexParameters = options.indexParameters;
  26279. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  26280. if (options.uniformBuffersNames) {
  26281. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  26282. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  26283. }
  26284. }
  26285. }
  26286. else {
  26287. this._engine = engine;
  26288. this.defines = defines;
  26289. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  26290. this._samplers = samplers;
  26291. this._attributesNames = attributesNamesOrOptions;
  26292. this.onError = onError;
  26293. this.onCompiled = onCompiled;
  26294. this._indexParameters = indexParameters;
  26295. this._fallbacks = fallbacks;
  26296. }
  26297. this.uniqueId = Effect._uniqueIdSeed++;
  26298. var vertexSource;
  26299. var fragmentSource;
  26300. if (baseName.vertexElement) {
  26301. vertexSource = document.getElementById(baseName.vertexElement);
  26302. if (!vertexSource) {
  26303. vertexSource = baseName.vertexElement;
  26304. }
  26305. }
  26306. else {
  26307. vertexSource = baseName.vertex || baseName;
  26308. }
  26309. if (baseName.fragmentElement) {
  26310. fragmentSource = document.getElementById(baseName.fragmentElement);
  26311. if (!fragmentSource) {
  26312. fragmentSource = baseName.fragmentElement;
  26313. }
  26314. }
  26315. else {
  26316. fragmentSource = baseName.fragment || baseName;
  26317. }
  26318. this._loadVertexShader(vertexSource, function (vertexCode) {
  26319. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  26320. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  26321. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  26322. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  26323. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  26324. if (baseName) {
  26325. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  26326. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  26327. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  26328. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  26329. }
  26330. else {
  26331. _this._vertexSourceCode = migratedVertexCode;
  26332. _this._fragmentSourceCode = migratedFragmentCode;
  26333. }
  26334. _this._prepareEffect();
  26335. });
  26336. });
  26337. });
  26338. });
  26339. });
  26340. });
  26341. }
  26342. Object.defineProperty(Effect.prototype, "key", {
  26343. get: function () {
  26344. return this._key;
  26345. },
  26346. enumerable: true,
  26347. configurable: true
  26348. });
  26349. // Properties
  26350. Effect.prototype.isReady = function () {
  26351. return this._isReady;
  26352. };
  26353. Effect.prototype.getEngine = function () {
  26354. return this._engine;
  26355. };
  26356. Effect.prototype.getProgram = function () {
  26357. return this._program;
  26358. };
  26359. Effect.prototype.getAttributesNames = function () {
  26360. return this._attributesNames;
  26361. };
  26362. Effect.prototype.getAttributeLocation = function (index) {
  26363. return this._attributes[index];
  26364. };
  26365. Effect.prototype.getAttributeLocationByName = function (name) {
  26366. var index = this._attributesNames.indexOf(name);
  26367. return this._attributes[index];
  26368. };
  26369. Effect.prototype.getAttributesCount = function () {
  26370. return this._attributes.length;
  26371. };
  26372. Effect.prototype.getUniformIndex = function (uniformName) {
  26373. return this._uniformsNames.indexOf(uniformName);
  26374. };
  26375. Effect.prototype.getUniform = function (uniformName) {
  26376. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  26377. };
  26378. Effect.prototype.getSamplers = function () {
  26379. return this._samplers;
  26380. };
  26381. Effect.prototype.getCompilationError = function () {
  26382. return this._compilationError;
  26383. };
  26384. // Methods
  26385. Effect.prototype.executeWhenCompiled = function (func) {
  26386. if (this.isReady()) {
  26387. func(this);
  26388. return;
  26389. }
  26390. this.onCompileObservable.add(function (effect) {
  26391. func(effect);
  26392. });
  26393. };
  26394. Effect.prototype._loadVertexShader = function (vertex, callback) {
  26395. if (BABYLON.Tools.IsWindowObjectExist()) {
  26396. // DOM element ?
  26397. if (vertex instanceof HTMLElement) {
  26398. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  26399. callback(vertexCode);
  26400. return;
  26401. }
  26402. }
  26403. // Base64 encoded ?
  26404. if (vertex.substr(0, 7) === "base64:") {
  26405. var vertexBinary = window.atob(vertex.substr(7));
  26406. callback(vertexBinary);
  26407. return;
  26408. }
  26409. // Is in local store ?
  26410. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  26411. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  26412. return;
  26413. }
  26414. var vertexShaderUrl;
  26415. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  26416. vertexShaderUrl = vertex;
  26417. }
  26418. else {
  26419. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  26420. }
  26421. // Vertex shader
  26422. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  26423. };
  26424. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  26425. if (BABYLON.Tools.IsWindowObjectExist()) {
  26426. // DOM element ?
  26427. if (fragment instanceof HTMLElement) {
  26428. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  26429. callback(fragmentCode);
  26430. return;
  26431. }
  26432. }
  26433. // Base64 encoded ?
  26434. if (fragment.substr(0, 7) === "base64:") {
  26435. var fragmentBinary = window.atob(fragment.substr(7));
  26436. callback(fragmentBinary);
  26437. return;
  26438. }
  26439. // Is in local store ?
  26440. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  26441. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  26442. return;
  26443. }
  26444. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  26445. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  26446. return;
  26447. }
  26448. var fragmentShaderUrl;
  26449. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  26450. fragmentShaderUrl = fragment;
  26451. }
  26452. else {
  26453. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  26454. }
  26455. // Fragment shader
  26456. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  26457. };
  26458. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  26459. // Rebuild shaders source code
  26460. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  26461. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  26462. vertexCode = prefix + vertexCode;
  26463. fragmentCode = prefix + fragmentCode;
  26464. // Number lines of shaders source code
  26465. var i = 2;
  26466. var regex = /\n/gm;
  26467. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26468. i = 2;
  26469. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26470. // Dump shaders name and formatted source code
  26471. if (this.name.vertexElement) {
  26472. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  26473. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  26474. }
  26475. else if (this.name.vertex) {
  26476. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  26477. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  26478. }
  26479. else {
  26480. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  26481. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  26482. }
  26483. };
  26484. ;
  26485. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  26486. var preparedSourceCode = this._processPrecision(sourceCode);
  26487. if (this._engine.webGLVersion == 1) {
  26488. callback(preparedSourceCode);
  26489. return;
  26490. }
  26491. // Already converted
  26492. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  26493. callback(preparedSourceCode.replace("#version 300 es", ""));
  26494. return;
  26495. }
  26496. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  26497. // Remove extensions
  26498. // #extension GL_OES_standard_derivatives : enable
  26499. // #extension GL_EXT_shader_texture_lod : enable
  26500. // #extension GL_EXT_frag_depth : enable
  26501. // #extension GL_EXT_draw_buffers : require
  26502. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  26503. var result = preparedSourceCode.replace(regex, "");
  26504. // Migrate to GLSL v300
  26505. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  26506. result = result.replace(/attribute[ \t]/g, "in ");
  26507. result = result.replace(/[ \t]attribute/g, " in");
  26508. if (isFragment) {
  26509. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  26510. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  26511. result = result.replace(/texture2D\s*\(/g, "texture(");
  26512. result = result.replace(/textureCube\s*\(/g, "texture(");
  26513. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  26514. result = result.replace(/gl_FragColor/g, "glFragColor");
  26515. result = result.replace(/gl_FragData/g, "glFragData");
  26516. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  26517. }
  26518. callback(result);
  26519. };
  26520. Effect.prototype._processIncludes = function (sourceCode, callback) {
  26521. var _this = this;
  26522. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  26523. var match = regex.exec(sourceCode);
  26524. var returnValue = new String(sourceCode);
  26525. while (match != null) {
  26526. var includeFile = match[1];
  26527. // Uniform declaration
  26528. if (includeFile.indexOf("__decl__") !== -1) {
  26529. includeFile = includeFile.replace(/__decl__/, "");
  26530. if (this._engine.supportsUniformBuffers) {
  26531. includeFile = includeFile.replace(/Vertex/, "Ubo");
  26532. includeFile = includeFile.replace(/Fragment/, "Ubo");
  26533. }
  26534. includeFile = includeFile + "Declaration";
  26535. }
  26536. if (Effect.IncludesShadersStore[includeFile]) {
  26537. // Substitution
  26538. var includeContent = Effect.IncludesShadersStore[includeFile];
  26539. if (match[2]) {
  26540. var splits = match[3].split(",");
  26541. for (var index = 0; index < splits.length; index += 2) {
  26542. var source = new RegExp(splits[index], "g");
  26543. var dest = splits[index + 1];
  26544. includeContent = includeContent.replace(source, dest);
  26545. }
  26546. }
  26547. if (match[4]) {
  26548. var indexString = match[5];
  26549. if (indexString.indexOf("..") !== -1) {
  26550. var indexSplits = indexString.split("..");
  26551. var minIndex = parseInt(indexSplits[0]);
  26552. var maxIndex = parseInt(indexSplits[1]);
  26553. var sourceIncludeContent = includeContent.slice(0);
  26554. includeContent = "";
  26555. if (isNaN(maxIndex)) {
  26556. maxIndex = this._indexParameters[indexSplits[1]];
  26557. }
  26558. for (var i = minIndex; i < maxIndex; i++) {
  26559. if (!this._engine.supportsUniformBuffers) {
  26560. // Ubo replacement
  26561. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26562. return p1 + "{X}";
  26563. });
  26564. }
  26565. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  26566. }
  26567. }
  26568. else {
  26569. if (!this._engine.supportsUniformBuffers) {
  26570. // Ubo replacement
  26571. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26572. return p1 + "{X}";
  26573. });
  26574. }
  26575. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26576. }
  26577. }
  26578. // Replace
  26579. returnValue = returnValue.replace(match[0], includeContent);
  26580. }
  26581. else {
  26582. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26583. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26584. Effect.IncludesShadersStore[includeFile] = fileContent;
  26585. _this._processIncludes(returnValue, callback);
  26586. });
  26587. return;
  26588. }
  26589. match = regex.exec(sourceCode);
  26590. }
  26591. callback(returnValue);
  26592. };
  26593. Effect.prototype._processPrecision = function (source) {
  26594. if (source.indexOf("precision highp float") === -1) {
  26595. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26596. source = "precision mediump float;\n" + source;
  26597. }
  26598. else {
  26599. source = "precision highp float;\n" + source;
  26600. }
  26601. }
  26602. else {
  26603. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26604. source = source.replace("precision highp float", "precision mediump float");
  26605. }
  26606. }
  26607. return source;
  26608. };
  26609. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  26610. var _this = this;
  26611. this._isReady = false;
  26612. this._vertexSourceCodeOverride = vertexSourceCode;
  26613. this._fragmentSourceCodeOverride = fragmentSourceCode;
  26614. this.onError = function (effect, error) {
  26615. if (onError) {
  26616. onError(error);
  26617. }
  26618. };
  26619. this.onCompiled = function () {
  26620. var scenes = _this.getEngine().scenes;
  26621. for (var i = 0; i < scenes.length; i++) {
  26622. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26623. }
  26624. if (onCompiled) {
  26625. onCompiled(_this._program);
  26626. }
  26627. };
  26628. this._fallbacks = null;
  26629. this._prepareEffect();
  26630. };
  26631. Effect.prototype._prepareEffect = function () {
  26632. var attributesNames = this._attributesNames;
  26633. var defines = this.defines;
  26634. var fallbacks = this._fallbacks;
  26635. this._valueCache = {};
  26636. var previousProgram = this._program;
  26637. try {
  26638. var engine = this._engine;
  26639. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  26640. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  26641. }
  26642. else {
  26643. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  26644. }
  26645. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  26646. if (engine.webGLVersion > 1) {
  26647. for (var name in this._uniformBuffersNames) {
  26648. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  26649. }
  26650. }
  26651. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26652. this._attributes = engine.getAttributes(this._program, attributesNames);
  26653. var index;
  26654. for (index = 0; index < this._samplers.length; index++) {
  26655. var sampler = this.getUniform(this._samplers[index]);
  26656. if (sampler == null) {
  26657. this._samplers.splice(index, 1);
  26658. index--;
  26659. }
  26660. }
  26661. engine.bindSamplers(this);
  26662. this._compilationError = "";
  26663. this._isReady = true;
  26664. if (this.onCompiled) {
  26665. this.onCompiled(this);
  26666. }
  26667. this.onCompileObservable.notifyObservers(this);
  26668. this.onCompileObservable.clear();
  26669. // Unbind mesh reference in fallbacks
  26670. if (this._fallbacks) {
  26671. this._fallbacks.unBindMesh();
  26672. }
  26673. if (previousProgram) {
  26674. this.getEngine()._deleteProgram(previousProgram);
  26675. }
  26676. }
  26677. catch (e) {
  26678. this._compilationError = e.message;
  26679. // Let's go through fallbacks then
  26680. BABYLON.Tools.Error("Unable to compile effect:");
  26681. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  26682. return " " + uniform;
  26683. }));
  26684. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  26685. return " " + attribute;
  26686. }));
  26687. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  26688. BABYLON.Tools.Error("Error: " + this._compilationError);
  26689. if (previousProgram) {
  26690. this._program = previousProgram;
  26691. this._isReady = true;
  26692. if (this.onError) {
  26693. this.onError(this, this._compilationError);
  26694. }
  26695. this.onErrorObservable.notifyObservers(this);
  26696. }
  26697. if (fallbacks && fallbacks.isMoreFallbacks) {
  26698. BABYLON.Tools.Error("Trying next fallback.");
  26699. this.defines = fallbacks.reduce(this.defines);
  26700. this._prepareEffect();
  26701. }
  26702. else {
  26703. if (this.onError) {
  26704. this.onError(this, this._compilationError);
  26705. }
  26706. this.onErrorObservable.notifyObservers(this);
  26707. this.onErrorObservable.clear();
  26708. // Unbind mesh reference in fallbacks
  26709. if (this._fallbacks) {
  26710. this._fallbacks.unBindMesh();
  26711. }
  26712. }
  26713. }
  26714. };
  26715. Object.defineProperty(Effect.prototype, "isSupported", {
  26716. get: function () {
  26717. return this._compilationError === "";
  26718. },
  26719. enumerable: true,
  26720. configurable: true
  26721. });
  26722. Effect.prototype._bindTexture = function (channel, texture) {
  26723. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26724. };
  26725. Effect.prototype.setTexture = function (channel, texture) {
  26726. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26727. };
  26728. Effect.prototype.setTextureArray = function (channel, textures) {
  26729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26730. var initialPos = this._samplers.indexOf(channel);
  26731. for (var index = 1; index < textures.length; index++) {
  26732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26733. }
  26734. }
  26735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26736. };
  26737. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26738. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26739. };
  26740. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26741. var cache = this._valueCache[uniformName];
  26742. var flag = matrix.updateFlag;
  26743. if (cache !== undefined && cache === flag) {
  26744. return false;
  26745. }
  26746. this._valueCache[uniformName] = flag;
  26747. return true;
  26748. };
  26749. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26750. var cache = this._valueCache[uniformName];
  26751. if (!cache) {
  26752. cache = [x, y];
  26753. this._valueCache[uniformName] = cache;
  26754. return true;
  26755. }
  26756. var changed = false;
  26757. if (cache[0] !== x) {
  26758. cache[0] = x;
  26759. changed = true;
  26760. }
  26761. if (cache[1] !== y) {
  26762. cache[1] = y;
  26763. changed = true;
  26764. }
  26765. return changed;
  26766. };
  26767. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26768. var cache = this._valueCache[uniformName];
  26769. if (!cache) {
  26770. cache = [x, y, z];
  26771. this._valueCache[uniformName] = cache;
  26772. return true;
  26773. }
  26774. var changed = false;
  26775. if (cache[0] !== x) {
  26776. cache[0] = x;
  26777. changed = true;
  26778. }
  26779. if (cache[1] !== y) {
  26780. cache[1] = y;
  26781. changed = true;
  26782. }
  26783. if (cache[2] !== z) {
  26784. cache[2] = z;
  26785. changed = true;
  26786. }
  26787. return changed;
  26788. };
  26789. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26790. var cache = this._valueCache[uniformName];
  26791. if (!cache) {
  26792. cache = [x, y, z, w];
  26793. this._valueCache[uniformName] = cache;
  26794. return true;
  26795. }
  26796. var changed = false;
  26797. if (cache[0] !== x) {
  26798. cache[0] = x;
  26799. changed = true;
  26800. }
  26801. if (cache[1] !== y) {
  26802. cache[1] = y;
  26803. changed = true;
  26804. }
  26805. if (cache[2] !== z) {
  26806. cache[2] = z;
  26807. changed = true;
  26808. }
  26809. if (cache[3] !== w) {
  26810. cache[3] = w;
  26811. changed = true;
  26812. }
  26813. return changed;
  26814. };
  26815. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  26816. var bufferName = this._uniformBuffersNames[name];
  26817. if (Effect._baseCache[bufferName] === buffer) {
  26818. return;
  26819. }
  26820. Effect._baseCache[bufferName] = buffer;
  26821. this._engine.bindUniformBufferBase(buffer, bufferName);
  26822. };
  26823. Effect.prototype.bindUniformBlock = function (blockName, index) {
  26824. this._engine.bindUniformBlock(this._program, blockName, index);
  26825. };
  26826. Effect.prototype.setIntArray = function (uniformName, array) {
  26827. this._valueCache[uniformName] = null;
  26828. this._engine.setIntArray(this.getUniform(uniformName), array);
  26829. return this;
  26830. };
  26831. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26832. this._valueCache[uniformName] = null;
  26833. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26834. return this;
  26835. };
  26836. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26837. this._valueCache[uniformName] = null;
  26838. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26839. return this;
  26840. };
  26841. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26842. this._valueCache[uniformName] = null;
  26843. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26844. return this;
  26845. };
  26846. Effect.prototype.setFloatArray = function (uniformName, array) {
  26847. this._valueCache[uniformName] = null;
  26848. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26849. return this;
  26850. };
  26851. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26852. this._valueCache[uniformName] = null;
  26853. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26854. return this;
  26855. };
  26856. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26857. this._valueCache[uniformName] = null;
  26858. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26859. return this;
  26860. };
  26861. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26862. this._valueCache[uniformName] = null;
  26863. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26864. return this;
  26865. };
  26866. Effect.prototype.setArray = function (uniformName, array) {
  26867. this._valueCache[uniformName] = null;
  26868. this._engine.setArray(this.getUniform(uniformName), array);
  26869. return this;
  26870. };
  26871. Effect.prototype.setArray2 = function (uniformName, array) {
  26872. this._valueCache[uniformName] = null;
  26873. this._engine.setArray2(this.getUniform(uniformName), array);
  26874. return this;
  26875. };
  26876. Effect.prototype.setArray3 = function (uniformName, array) {
  26877. this._valueCache[uniformName] = null;
  26878. this._engine.setArray3(this.getUniform(uniformName), array);
  26879. return this;
  26880. };
  26881. Effect.prototype.setArray4 = function (uniformName, array) {
  26882. this._valueCache[uniformName] = null;
  26883. this._engine.setArray4(this.getUniform(uniformName), array);
  26884. return this;
  26885. };
  26886. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26887. if (!matrices) {
  26888. return this;
  26889. }
  26890. this._valueCache[uniformName] = null;
  26891. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26892. return this;
  26893. };
  26894. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26895. if (this._cacheMatrix(uniformName, matrix)) {
  26896. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26897. }
  26898. return this;
  26899. };
  26900. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26901. this._valueCache[uniformName] = null;
  26902. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26903. return this;
  26904. };
  26905. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26906. this._valueCache[uniformName] = null;
  26907. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26908. return this;
  26909. };
  26910. Effect.prototype.setFloat = function (uniformName, value) {
  26911. var cache = this._valueCache[uniformName];
  26912. if (cache !== undefined && cache === value)
  26913. return this;
  26914. this._valueCache[uniformName] = value;
  26915. this._engine.setFloat(this.getUniform(uniformName), value);
  26916. return this;
  26917. };
  26918. Effect.prototype.setBool = function (uniformName, bool) {
  26919. var cache = this._valueCache[uniformName];
  26920. if (cache !== undefined && cache === bool)
  26921. return this;
  26922. this._valueCache[uniformName] = bool;
  26923. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26924. return this;
  26925. };
  26926. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26927. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26928. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26929. }
  26930. return this;
  26931. };
  26932. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26933. if (this._cacheFloat2(uniformName, x, y)) {
  26934. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26935. }
  26936. return this;
  26937. };
  26938. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26939. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26940. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26941. }
  26942. return this;
  26943. };
  26944. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26945. if (this._cacheFloat3(uniformName, x, y, z)) {
  26946. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26947. }
  26948. return this;
  26949. };
  26950. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26951. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26952. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26953. }
  26954. return this;
  26955. };
  26956. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26957. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26958. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26959. }
  26960. return this;
  26961. };
  26962. Effect.prototype.setColor3 = function (uniformName, color3) {
  26963. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26964. this._engine.setColor3(this.getUniform(uniformName), color3);
  26965. }
  26966. return this;
  26967. };
  26968. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26969. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26970. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26971. }
  26972. return this;
  26973. };
  26974. Effect.ResetCache = function () {
  26975. Effect._baseCache = {};
  26976. };
  26977. Effect._uniqueIdSeed = 0;
  26978. Effect._baseCache = {};
  26979. // Statics
  26980. Effect.ShadersStore = {};
  26981. Effect.IncludesShadersStore = {};
  26982. return Effect;
  26983. }());
  26984. BABYLON.Effect = Effect;
  26985. })(BABYLON || (BABYLON = {}));
  26986. //# sourceMappingURL=babylon.effect.js.map
  26987. var BABYLON;
  26988. (function (BABYLON) {
  26989. var MaterialHelper = /** @class */ (function () {
  26990. function MaterialHelper() {
  26991. }
  26992. MaterialHelper.BindEyePosition = function (effect, scene) {
  26993. if (scene._forcedViewPosition) {
  26994. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  26995. return;
  26996. }
  26997. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  26998. };
  26999. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  27000. defines._needUVs = true;
  27001. defines[key] = true;
  27002. if (texture.getTextureMatrix().isIdentity(true)) {
  27003. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  27004. if (texture.coordinatesIndex === 0) {
  27005. defines["MAINUV1"] = true;
  27006. }
  27007. else {
  27008. defines["MAINUV2"] = true;
  27009. }
  27010. }
  27011. else {
  27012. defines[key + "DIRECTUV"] = 0;
  27013. }
  27014. };
  27015. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  27016. var matrix = texture.getTextureMatrix();
  27017. if (!matrix.isIdentity(true)) {
  27018. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  27019. }
  27020. };
  27021. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  27022. if (defines._areMiscDirty) {
  27023. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  27024. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  27025. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  27026. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  27027. }
  27028. };
  27029. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  27030. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  27031. var changed = false;
  27032. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  27033. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  27034. changed = true;
  27035. }
  27036. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  27037. defines["ALPHATEST"] = !defines["ALPHATEST"];
  27038. changed = true;
  27039. }
  27040. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  27041. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  27042. changed = true;
  27043. }
  27044. if (defines["INSTANCES"] !== useInstances) {
  27045. defines["INSTANCES"] = useInstances;
  27046. changed = true;
  27047. }
  27048. if (changed) {
  27049. defines.markAsUnprocessed();
  27050. }
  27051. };
  27052. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  27053. if (useMorphTargets === void 0) { useMorphTargets = false; }
  27054. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  27055. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  27056. return false;
  27057. }
  27058. defines._normals = defines._needNormals;
  27059. defines._uvs = defines._needUVs;
  27060. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  27061. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  27062. defines["TANGENT"] = true;
  27063. }
  27064. if (defines._needUVs) {
  27065. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  27066. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  27067. }
  27068. else {
  27069. defines["UV1"] = false;
  27070. defines["UV2"] = false;
  27071. }
  27072. if (useVertexColor) {
  27073. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  27074. defines["VERTEXCOLOR"] = hasVertexColors;
  27075. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  27076. }
  27077. if (useBones) {
  27078. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  27079. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  27080. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  27081. }
  27082. else {
  27083. defines["NUM_BONE_INFLUENCERS"] = 0;
  27084. defines["BonesPerMesh"] = 0;
  27085. }
  27086. }
  27087. if (useMorphTargets) {
  27088. var manager = mesh.morphTargetManager;
  27089. if (manager) {
  27090. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  27091. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  27092. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  27093. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  27094. }
  27095. else {
  27096. defines["MORPHTARGETS_TANGENT"] = false;
  27097. defines["MORPHTARGETS_NORMAL"] = false;
  27098. defines["MORPHTARGETS"] = false;
  27099. defines["NUM_MORPH_INFLUENCERS"] = 0;
  27100. }
  27101. }
  27102. return true;
  27103. };
  27104. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  27105. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27106. if (disableLighting === void 0) { disableLighting = false; }
  27107. if (!defines._areLightsDirty) {
  27108. return defines._needNormals;
  27109. }
  27110. var lightIndex = 0;
  27111. var needNormals = false;
  27112. var needRebuild = false;
  27113. var lightmapMode = false;
  27114. var shadowEnabled = false;
  27115. var specularEnabled = false;
  27116. if (scene.lightsEnabled && !disableLighting) {
  27117. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  27118. var light = _a[_i];
  27119. needNormals = true;
  27120. if (defines["LIGHT" + lightIndex] === undefined) {
  27121. needRebuild = true;
  27122. }
  27123. defines["LIGHT" + lightIndex] = true;
  27124. defines["SPOTLIGHT" + lightIndex] = false;
  27125. defines["HEMILIGHT" + lightIndex] = false;
  27126. defines["POINTLIGHT" + lightIndex] = false;
  27127. defines["DIRLIGHT" + lightIndex] = false;
  27128. var type;
  27129. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  27130. type = "SPOTLIGHT" + lightIndex;
  27131. }
  27132. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  27133. type = "HEMILIGHT" + lightIndex;
  27134. }
  27135. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  27136. type = "POINTLIGHT" + lightIndex;
  27137. }
  27138. else {
  27139. type = "DIRLIGHT" + lightIndex;
  27140. }
  27141. defines[type] = true;
  27142. // Specular
  27143. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  27144. specularEnabled = true;
  27145. }
  27146. // Shadows
  27147. defines["SHADOW" + lightIndex] = false;
  27148. defines["SHADOWPCF" + lightIndex] = false;
  27149. defines["SHADOWESM" + lightIndex] = false;
  27150. defines["SHADOWCUBE" + lightIndex] = false;
  27151. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  27152. var shadowGenerator = light.getShadowGenerator();
  27153. if (shadowGenerator) {
  27154. shadowEnabled = true;
  27155. shadowGenerator.prepareDefines(defines, lightIndex);
  27156. }
  27157. }
  27158. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  27159. lightmapMode = true;
  27160. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  27161. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  27162. }
  27163. else {
  27164. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  27165. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  27166. }
  27167. lightIndex++;
  27168. if (lightIndex === maxSimultaneousLights)
  27169. break;
  27170. }
  27171. }
  27172. defines["SPECULARTERM"] = specularEnabled;
  27173. defines["SHADOWS"] = shadowEnabled;
  27174. // Resetting all other lights if any
  27175. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  27176. if (defines["LIGHT" + index] !== undefined) {
  27177. defines["LIGHT" + index] = false;
  27178. defines["HEMILIGHT" + lightIndex] = false;
  27179. defines["POINTLIGHT" + lightIndex] = false;
  27180. defines["DIRLIGHT" + lightIndex] = false;
  27181. defines["SPOTLIGHT" + lightIndex] = false;
  27182. defines["SHADOW" + lightIndex] = false;
  27183. }
  27184. }
  27185. var caps = scene.getEngine().getCaps();
  27186. if (defines["SHADOWFLOAT"] === undefined) {
  27187. needRebuild = true;
  27188. }
  27189. defines["SHADOWFLOAT"] = shadowEnabled &&
  27190. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  27191. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  27192. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  27193. if (needRebuild) {
  27194. defines.rebuild();
  27195. }
  27196. return needNormals;
  27197. };
  27198. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  27199. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27200. var uniformsList;
  27201. var uniformBuffersList = null;
  27202. if (uniformsListOrOptions.uniformsNames) {
  27203. var options = uniformsListOrOptions;
  27204. uniformsList = options.uniformsNames;
  27205. uniformBuffersList = options.uniformBuffersNames;
  27206. samplersList = options.samplers;
  27207. defines = options.defines;
  27208. maxSimultaneousLights = options.maxSimultaneousLights;
  27209. }
  27210. else {
  27211. uniformsList = uniformsListOrOptions;
  27212. if (!samplersList) {
  27213. samplersList = [];
  27214. }
  27215. }
  27216. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  27217. if (!defines["LIGHT" + lightIndex]) {
  27218. break;
  27219. }
  27220. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  27221. if (uniformBuffersList) {
  27222. uniformBuffersList.push("Light" + lightIndex);
  27223. }
  27224. samplersList.push("shadowSampler" + lightIndex);
  27225. }
  27226. if (defines["NUM_MORPH_INFLUENCERS"]) {
  27227. uniformsList.push("morphTargetInfluences");
  27228. }
  27229. };
  27230. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  27231. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27232. if (rank === void 0) { rank = 0; }
  27233. var lightFallbackRank = 0;
  27234. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  27235. if (!defines["LIGHT" + lightIndex]) {
  27236. break;
  27237. }
  27238. if (lightIndex > 0) {
  27239. lightFallbackRank = rank + lightIndex;
  27240. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  27241. }
  27242. if (!defines["SHADOWS"]) {
  27243. if (defines["SHADOW" + lightIndex]) {
  27244. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  27245. }
  27246. if (defines["SHADOWPCF" + lightIndex]) {
  27247. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  27248. }
  27249. if (defines["SHADOWESM" + lightIndex]) {
  27250. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  27251. }
  27252. }
  27253. }
  27254. return lightFallbackRank++;
  27255. };
  27256. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  27257. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  27258. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  27259. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  27260. var manager = mesh.morphTargetManager;
  27261. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  27262. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  27263. for (var index = 0; index < influencers; index++) {
  27264. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  27265. if (normal) {
  27266. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  27267. }
  27268. if (tangent) {
  27269. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  27270. }
  27271. if (attribs.length > maxAttributesCount) {
  27272. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  27273. }
  27274. }
  27275. }
  27276. };
  27277. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  27278. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  27279. fallbacks.addCPUSkinningFallback(0, mesh);
  27280. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27281. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27282. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  27283. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  27284. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  27285. }
  27286. }
  27287. };
  27288. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  27289. if (defines["INSTANCES"]) {
  27290. attribs.push("world0");
  27291. attribs.push("world1");
  27292. attribs.push("world2");
  27293. attribs.push("world3");
  27294. }
  27295. };
  27296. // Bindings
  27297. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  27298. if (light.shadowEnabled && mesh.receiveShadows) {
  27299. var shadowGenerator = light.getShadowGenerator();
  27300. if (shadowGenerator) {
  27301. shadowGenerator.bindShadowLight(lightIndex, effect);
  27302. }
  27303. }
  27304. };
  27305. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  27306. light.transferToEffect(effect, lightIndex + "");
  27307. };
  27308. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  27309. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27310. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  27311. var lightIndex = 0;
  27312. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  27313. var light = _a[_i];
  27314. var scaledIntensity = light.getScaledIntensity();
  27315. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  27316. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  27317. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  27318. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  27319. if (defines["SPECULARTERM"]) {
  27320. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  27321. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  27322. }
  27323. // Shadows
  27324. if (scene.shadowsEnabled) {
  27325. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  27326. }
  27327. light._uniformBuffer.update();
  27328. lightIndex++;
  27329. if (lightIndex === maxSimultaneousLights)
  27330. break;
  27331. }
  27332. };
  27333. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  27334. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  27335. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  27336. effect.setColor3("vFogColor", scene.fogColor);
  27337. }
  27338. };
  27339. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  27340. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  27341. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  27342. if (matrices && effect) {
  27343. effect.setMatrices("mBones", matrices);
  27344. }
  27345. }
  27346. };
  27347. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  27348. var manager = abstractMesh.morphTargetManager;
  27349. if (!abstractMesh || !manager) {
  27350. return;
  27351. }
  27352. effect.setFloatArray("morphTargetInfluences", manager.influences);
  27353. };
  27354. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  27355. if (defines["LOGARITHMICDEPTH"]) {
  27356. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  27357. }
  27358. };
  27359. MaterialHelper.BindClipPlane = function (effect, scene) {
  27360. if (scene.clipPlane) {
  27361. var clipPlane = scene.clipPlane;
  27362. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  27363. }
  27364. };
  27365. return MaterialHelper;
  27366. }());
  27367. BABYLON.MaterialHelper = MaterialHelper;
  27368. })(BABYLON || (BABYLON = {}));
  27369. //# sourceMappingURL=babylon.materialHelper.js.map
  27370. var __assign = (this && this.__assign) || Object.assign || function(t) {
  27371. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27372. s = arguments[i];
  27373. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  27374. t[p] = s[p];
  27375. }
  27376. return t;
  27377. };
  27378. var BABYLON;
  27379. (function (BABYLON) {
  27380. var MaterialDefines = /** @class */ (function () {
  27381. function MaterialDefines() {
  27382. this._isDirty = true;
  27383. this._areLightsDirty = true;
  27384. this._areAttributesDirty = true;
  27385. this._areTexturesDirty = true;
  27386. this._areFresnelDirty = true;
  27387. this._areMiscDirty = true;
  27388. this._areImageProcessingDirty = true;
  27389. this._normals = false;
  27390. this._uvs = false;
  27391. this._needNormals = false;
  27392. this._needUVs = false;
  27393. }
  27394. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  27395. get: function () {
  27396. return this._isDirty;
  27397. },
  27398. enumerable: true,
  27399. configurable: true
  27400. });
  27401. MaterialDefines.prototype.markAsProcessed = function () {
  27402. this._isDirty = false;
  27403. this._areAttributesDirty = false;
  27404. this._areTexturesDirty = false;
  27405. this._areFresnelDirty = false;
  27406. this._areLightsDirty = false;
  27407. this._areMiscDirty = false;
  27408. this._areImageProcessingDirty = false;
  27409. };
  27410. MaterialDefines.prototype.markAsUnprocessed = function () {
  27411. this._isDirty = true;
  27412. };
  27413. MaterialDefines.prototype.markAllAsDirty = function () {
  27414. this._areTexturesDirty = true;
  27415. this._areAttributesDirty = true;
  27416. this._areLightsDirty = true;
  27417. this._areFresnelDirty = true;
  27418. this._areMiscDirty = true;
  27419. this._areImageProcessingDirty = true;
  27420. this._isDirty = true;
  27421. };
  27422. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27423. this._areImageProcessingDirty = true;
  27424. this._isDirty = true;
  27425. };
  27426. MaterialDefines.prototype.markAsLightDirty = function () {
  27427. this._areLightsDirty = true;
  27428. this._isDirty = true;
  27429. };
  27430. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27431. this._areAttributesDirty = true;
  27432. this._isDirty = true;
  27433. };
  27434. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27435. this._areTexturesDirty = true;
  27436. this._isDirty = true;
  27437. };
  27438. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27439. this._areFresnelDirty = true;
  27440. this._isDirty = true;
  27441. };
  27442. MaterialDefines.prototype.markAsMiscDirty = function () {
  27443. this._areMiscDirty = true;
  27444. this._isDirty = true;
  27445. };
  27446. MaterialDefines.prototype.rebuild = function () {
  27447. if (this._keys) {
  27448. delete this._keys;
  27449. }
  27450. this._keys = [];
  27451. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27452. var key = _a[_i];
  27453. if (key[0] === "_") {
  27454. continue;
  27455. }
  27456. this._keys.push(key);
  27457. }
  27458. };
  27459. MaterialDefines.prototype.isEqual = function (other) {
  27460. if (this._keys.length !== other._keys.length) {
  27461. return false;
  27462. }
  27463. for (var index = 0; index < this._keys.length; index++) {
  27464. var prop = this._keys[index];
  27465. if (this[prop] !== other[prop]) {
  27466. return false;
  27467. }
  27468. }
  27469. return true;
  27470. };
  27471. MaterialDefines.prototype.cloneTo = function (other) {
  27472. if (this._keys.length !== other._keys.length) {
  27473. other._keys = this._keys.slice(0);
  27474. }
  27475. for (var index = 0; index < this._keys.length; index++) {
  27476. var prop = this._keys[index];
  27477. other[prop] = this[prop];
  27478. }
  27479. };
  27480. MaterialDefines.prototype.reset = function () {
  27481. for (var index = 0; index < this._keys.length; index++) {
  27482. var prop = this._keys[index];
  27483. if (typeof (this[prop]) === "number") {
  27484. this[prop] = 0;
  27485. }
  27486. else {
  27487. this[prop] = false;
  27488. }
  27489. }
  27490. };
  27491. MaterialDefines.prototype.toString = function () {
  27492. var result = "";
  27493. for (var index = 0; index < this._keys.length; index++) {
  27494. var prop = this._keys[index];
  27495. var value = this[prop];
  27496. if (typeof (value) === "number") {
  27497. result += "#define " + prop + " " + this[prop] + "\n";
  27498. }
  27499. else if (value) {
  27500. result += "#define " + prop + "\n";
  27501. }
  27502. }
  27503. return result;
  27504. };
  27505. return MaterialDefines;
  27506. }());
  27507. BABYLON.MaterialDefines = MaterialDefines;
  27508. var Material = /** @class */ (function () {
  27509. function Material(name, scene, doNotAdd) {
  27510. this.checkReadyOnEveryCall = false;
  27511. this.checkReadyOnlyOnce = false;
  27512. this.state = "";
  27513. this.alpha = 1.0;
  27514. this._backFaceCulling = true;
  27515. this.doNotSerialize = false;
  27516. this.storeEffectOnSubMeshes = false;
  27517. /**
  27518. * An event triggered when the material is disposed.
  27519. * @type {BABYLON.Observable}
  27520. */
  27521. this.onDisposeObservable = new BABYLON.Observable();
  27522. /**
  27523. * An event triggered when the material is bound.
  27524. * @type {BABYLON.Observable}
  27525. */
  27526. this.onBindObservable = new BABYLON.Observable();
  27527. /**
  27528. * An event triggered when the material is unbound.
  27529. * @type {BABYLON.Observable}
  27530. */
  27531. this.onUnBindObservable = new BABYLON.Observable();
  27532. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27533. this._needDepthPrePass = false;
  27534. this.disableDepthWrite = false;
  27535. this.forceDepthWrite = false;
  27536. this.separateCullingPass = false;
  27537. this._fogEnabled = true;
  27538. this.pointSize = 1.0;
  27539. this.zOffset = 0;
  27540. this._wasPreviouslyReady = false;
  27541. this._fillMode = Material.TriangleFillMode;
  27542. this.name = name;
  27543. this.id = name || BABYLON.Tools.RandomId();
  27544. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27545. if (this._scene.useRightHandedSystem) {
  27546. this.sideOrientation = Material.ClockWiseSideOrientation;
  27547. }
  27548. else {
  27549. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27550. }
  27551. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27552. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27553. if (!doNotAdd) {
  27554. this._scene.materials.push(this);
  27555. }
  27556. }
  27557. Object.defineProperty(Material, "TriangleFillMode", {
  27558. get: function () {
  27559. return Material._TriangleFillMode;
  27560. },
  27561. enumerable: true,
  27562. configurable: true
  27563. });
  27564. Object.defineProperty(Material, "WireFrameFillMode", {
  27565. get: function () {
  27566. return Material._WireFrameFillMode;
  27567. },
  27568. enumerable: true,
  27569. configurable: true
  27570. });
  27571. Object.defineProperty(Material, "PointFillMode", {
  27572. get: function () {
  27573. return Material._PointFillMode;
  27574. },
  27575. enumerable: true,
  27576. configurable: true
  27577. });
  27578. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27579. get: function () {
  27580. return Material._ClockWiseSideOrientation;
  27581. },
  27582. enumerable: true,
  27583. configurable: true
  27584. });
  27585. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27586. get: function () {
  27587. return Material._CounterClockWiseSideOrientation;
  27588. },
  27589. enumerable: true,
  27590. configurable: true
  27591. });
  27592. Object.defineProperty(Material, "TextureDirtyFlag", {
  27593. get: function () {
  27594. return Material._TextureDirtyFlag;
  27595. },
  27596. enumerable: true,
  27597. configurable: true
  27598. });
  27599. Object.defineProperty(Material, "LightDirtyFlag", {
  27600. get: function () {
  27601. return Material._LightDirtyFlag;
  27602. },
  27603. enumerable: true,
  27604. configurable: true
  27605. });
  27606. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27607. get: function () {
  27608. return Material._FresnelDirtyFlag;
  27609. },
  27610. enumerable: true,
  27611. configurable: true
  27612. });
  27613. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27614. get: function () {
  27615. return Material._AttributesDirtyFlag;
  27616. },
  27617. enumerable: true,
  27618. configurable: true
  27619. });
  27620. Object.defineProperty(Material, "MiscDirtyFlag", {
  27621. get: function () {
  27622. return Material._MiscDirtyFlag;
  27623. },
  27624. enumerable: true,
  27625. configurable: true
  27626. });
  27627. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27628. get: function () {
  27629. return this._backFaceCulling;
  27630. },
  27631. set: function (value) {
  27632. if (this._backFaceCulling === value) {
  27633. return;
  27634. }
  27635. this._backFaceCulling = value;
  27636. this.markAsDirty(Material.TextureDirtyFlag);
  27637. },
  27638. enumerable: true,
  27639. configurable: true
  27640. });
  27641. Object.defineProperty(Material.prototype, "onDispose", {
  27642. set: function (callback) {
  27643. if (this._onDisposeObserver) {
  27644. this.onDisposeObservable.remove(this._onDisposeObserver);
  27645. }
  27646. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27647. },
  27648. enumerable: true,
  27649. configurable: true
  27650. });
  27651. Object.defineProperty(Material.prototype, "onBind", {
  27652. set: function (callback) {
  27653. if (this._onBindObserver) {
  27654. this.onBindObservable.remove(this._onBindObserver);
  27655. }
  27656. this._onBindObserver = this.onBindObservable.add(callback);
  27657. },
  27658. enumerable: true,
  27659. configurable: true
  27660. });
  27661. Object.defineProperty(Material.prototype, "alphaMode", {
  27662. get: function () {
  27663. return this._alphaMode;
  27664. },
  27665. set: function (value) {
  27666. if (this._alphaMode === value) {
  27667. return;
  27668. }
  27669. this._alphaMode = value;
  27670. this.markAsDirty(Material.TextureDirtyFlag);
  27671. },
  27672. enumerable: true,
  27673. configurable: true
  27674. });
  27675. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27676. get: function () {
  27677. return this._needDepthPrePass;
  27678. },
  27679. set: function (value) {
  27680. if (this._needDepthPrePass === value) {
  27681. return;
  27682. }
  27683. this._needDepthPrePass = value;
  27684. if (this._needDepthPrePass) {
  27685. this.checkReadyOnEveryCall = true;
  27686. }
  27687. },
  27688. enumerable: true,
  27689. configurable: true
  27690. });
  27691. Object.defineProperty(Material.prototype, "fogEnabled", {
  27692. get: function () {
  27693. return this._fogEnabled;
  27694. },
  27695. set: function (value) {
  27696. if (this._fogEnabled === value) {
  27697. return;
  27698. }
  27699. this._fogEnabled = value;
  27700. this.markAsDirty(Material.MiscDirtyFlag);
  27701. },
  27702. enumerable: true,
  27703. configurable: true
  27704. });
  27705. Object.defineProperty(Material.prototype, "wireframe", {
  27706. get: function () {
  27707. return this._fillMode === Material.WireFrameFillMode;
  27708. },
  27709. set: function (value) {
  27710. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27711. },
  27712. enumerable: true,
  27713. configurable: true
  27714. });
  27715. Object.defineProperty(Material.prototype, "pointsCloud", {
  27716. get: function () {
  27717. return this._fillMode === Material.PointFillMode;
  27718. },
  27719. set: function (value) {
  27720. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27721. },
  27722. enumerable: true,
  27723. configurable: true
  27724. });
  27725. Object.defineProperty(Material.prototype, "fillMode", {
  27726. get: function () {
  27727. return this._fillMode;
  27728. },
  27729. set: function (value) {
  27730. if (this._fillMode === value) {
  27731. return;
  27732. }
  27733. this._fillMode = value;
  27734. this.markAsDirty(Material.MiscDirtyFlag);
  27735. },
  27736. enumerable: true,
  27737. configurable: true
  27738. });
  27739. /**
  27740. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27741. * subclasses should override adding information pertainent to themselves
  27742. */
  27743. Material.prototype.toString = function (fullDetails) {
  27744. var ret = "Name: " + this.name;
  27745. if (fullDetails) {
  27746. }
  27747. return ret;
  27748. };
  27749. /**
  27750. * Child classes can use it to update shaders
  27751. */
  27752. Material.prototype.getClassName = function () {
  27753. return "Material";
  27754. };
  27755. Object.defineProperty(Material.prototype, "isFrozen", {
  27756. get: function () {
  27757. return this.checkReadyOnlyOnce;
  27758. },
  27759. enumerable: true,
  27760. configurable: true
  27761. });
  27762. Material.prototype.freeze = function () {
  27763. this.checkReadyOnlyOnce = true;
  27764. };
  27765. Material.prototype.unfreeze = function () {
  27766. this.checkReadyOnlyOnce = false;
  27767. };
  27768. Material.prototype.isReady = function (mesh, useInstances) {
  27769. return true;
  27770. };
  27771. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27772. return false;
  27773. };
  27774. Material.prototype.getEffect = function () {
  27775. return this._effect;
  27776. };
  27777. Material.prototype.getScene = function () {
  27778. return this._scene;
  27779. };
  27780. Material.prototype.needAlphaBlending = function () {
  27781. return (this.alpha < 1.0);
  27782. };
  27783. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  27784. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  27785. };
  27786. Material.prototype.needAlphaTesting = function () {
  27787. return false;
  27788. };
  27789. Material.prototype.getAlphaTestTexture = function () {
  27790. return null;
  27791. };
  27792. Material.prototype.markDirty = function () {
  27793. this._wasPreviouslyReady = false;
  27794. };
  27795. Material.prototype._preBind = function (effect, overrideOrientation) {
  27796. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27797. var engine = this._scene.getEngine();
  27798. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27799. var reverse = orientation === Material.ClockWiseSideOrientation;
  27800. engine.enableEffect(effect ? effect : this._effect);
  27801. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27802. return reverse;
  27803. };
  27804. Material.prototype.bind = function (world, mesh) {
  27805. };
  27806. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27807. };
  27808. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27809. };
  27810. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27811. sceneUbo.bindToEffect(effect, "Scene");
  27812. };
  27813. Material.prototype.bindView = function (effect) {
  27814. if (!this._useUBO) {
  27815. effect.setMatrix("view", this.getScene().getViewMatrix());
  27816. }
  27817. else {
  27818. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27819. }
  27820. };
  27821. Material.prototype.bindViewProjection = function (effect) {
  27822. if (!this._useUBO) {
  27823. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27824. }
  27825. else {
  27826. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27827. }
  27828. };
  27829. Material.prototype._afterBind = function (mesh) {
  27830. this._scene._cachedMaterial = this;
  27831. if (mesh) {
  27832. this._scene._cachedVisibility = mesh.visibility;
  27833. }
  27834. else {
  27835. this._scene._cachedVisibility = 1;
  27836. }
  27837. if (mesh) {
  27838. this.onBindObservable.notifyObservers(mesh);
  27839. }
  27840. if (this.disableDepthWrite) {
  27841. var engine = this._scene.getEngine();
  27842. this._cachedDepthWriteState = engine.getDepthWrite();
  27843. engine.setDepthWrite(false);
  27844. }
  27845. };
  27846. Material.prototype.unbind = function () {
  27847. this.onUnBindObservable.notifyObservers(this);
  27848. if (this.disableDepthWrite) {
  27849. var engine = this._scene.getEngine();
  27850. engine.setDepthWrite(this._cachedDepthWriteState);
  27851. }
  27852. };
  27853. Material.prototype.getActiveTextures = function () {
  27854. return [];
  27855. };
  27856. Material.prototype.hasTexture = function (texture) {
  27857. return false;
  27858. };
  27859. Material.prototype.clone = function (name) {
  27860. return null;
  27861. };
  27862. Material.prototype.getBindedMeshes = function () {
  27863. var result = new Array();
  27864. for (var index = 0; index < this._scene.meshes.length; index++) {
  27865. var mesh = this._scene.meshes[index];
  27866. if (mesh.material === this) {
  27867. result.push(mesh);
  27868. }
  27869. }
  27870. return result;
  27871. };
  27872. /**
  27873. * Force shader compilation including textures ready check
  27874. */
  27875. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27876. var _this = this;
  27877. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  27878. var subMesh = new BABYLON.BaseSubMesh();
  27879. var scene = this.getScene();
  27880. var engine = scene.getEngine();
  27881. var checkReady = function () {
  27882. if (!_this._scene || !_this._scene.getEngine()) {
  27883. return;
  27884. }
  27885. if (subMesh._materialDefines) {
  27886. subMesh._materialDefines._renderId = -1;
  27887. }
  27888. var alphaTestState = engine.getAlphaTesting();
  27889. var clipPlaneState = scene.clipPlane;
  27890. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  27891. if (localOptions.clipPlane) {
  27892. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27893. }
  27894. if (_this.storeEffectOnSubMeshes) {
  27895. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27896. if (onCompiled) {
  27897. onCompiled(_this);
  27898. }
  27899. }
  27900. else {
  27901. setTimeout(checkReady, 16);
  27902. }
  27903. }
  27904. else {
  27905. if (_this.isReady(mesh)) {
  27906. if (onCompiled) {
  27907. onCompiled(_this);
  27908. }
  27909. }
  27910. else {
  27911. setTimeout(checkReady, 16);
  27912. }
  27913. }
  27914. engine.setAlphaTesting(alphaTestState);
  27915. if (options && options.clipPlane) {
  27916. scene.clipPlane = clipPlaneState;
  27917. }
  27918. };
  27919. checkReady();
  27920. };
  27921. Material.prototype.markAsDirty = function (flag) {
  27922. if (flag & Material.TextureDirtyFlag) {
  27923. this._markAllSubMeshesAsTexturesDirty();
  27924. }
  27925. if (flag & Material.LightDirtyFlag) {
  27926. this._markAllSubMeshesAsLightsDirty();
  27927. }
  27928. if (flag & Material.FresnelDirtyFlag) {
  27929. this._markAllSubMeshesAsFresnelDirty();
  27930. }
  27931. if (flag & Material.AttributesDirtyFlag) {
  27932. this._markAllSubMeshesAsAttributesDirty();
  27933. }
  27934. if (flag & Material.MiscDirtyFlag) {
  27935. this._markAllSubMeshesAsMiscDirty();
  27936. }
  27937. this.getScene().resetCachedMaterial();
  27938. };
  27939. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27940. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27941. var mesh = _a[_i];
  27942. if (!mesh.subMeshes) {
  27943. continue;
  27944. }
  27945. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27946. var subMesh = _c[_b];
  27947. if (subMesh.getMaterial() !== this) {
  27948. continue;
  27949. }
  27950. if (!subMesh._materialDefines) {
  27951. continue;
  27952. }
  27953. func(subMesh._materialDefines);
  27954. }
  27955. }
  27956. };
  27957. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  27958. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  27959. };
  27960. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  27961. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  27962. };
  27963. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  27964. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  27965. };
  27966. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  27967. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  27968. };
  27969. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  27970. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  27971. };
  27972. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  27973. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  27974. };
  27975. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27976. // Animations
  27977. this.getScene().stopAnimation(this);
  27978. // Remove from scene
  27979. var index = this._scene.materials.indexOf(this);
  27980. if (index >= 0) {
  27981. this._scene.materials.splice(index, 1);
  27982. }
  27983. // Remove from meshes
  27984. for (index = 0; index < this._scene.meshes.length; index++) {
  27985. var mesh = this._scene.meshes[index];
  27986. if (mesh.material === this) {
  27987. mesh.material = null;
  27988. if (mesh.geometry) {
  27989. var geometry = (mesh.geometry);
  27990. if (this.storeEffectOnSubMeshes) {
  27991. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  27992. var subMesh = _a[_i];
  27993. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  27994. if (forceDisposeEffect && subMesh._materialEffect) {
  27995. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  27996. }
  27997. }
  27998. }
  27999. else {
  28000. geometry._releaseVertexArrayObject(this._effect);
  28001. }
  28002. }
  28003. }
  28004. }
  28005. this._uniformBuffer.dispose();
  28006. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28007. if (forceDisposeEffect && this._effect) {
  28008. if (!this.storeEffectOnSubMeshes) {
  28009. this._scene.getEngine()._releaseEffect(this._effect);
  28010. }
  28011. this._effect = null;
  28012. }
  28013. // Callback
  28014. this.onDisposeObservable.notifyObservers(this);
  28015. this.onDisposeObservable.clear();
  28016. this.onBindObservable.clear();
  28017. this.onUnBindObservable.clear();
  28018. };
  28019. Material.prototype.serialize = function () {
  28020. return BABYLON.SerializationHelper.Serialize(this);
  28021. };
  28022. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28023. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28024. multiMaterial.id = parsedMultiMaterial.id;
  28025. if (BABYLON.Tags) {
  28026. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28027. }
  28028. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28029. var subMatId = parsedMultiMaterial.materials[matIndex];
  28030. if (subMatId) {
  28031. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28032. }
  28033. else {
  28034. multiMaterial.subMaterials.push(null);
  28035. }
  28036. }
  28037. return multiMaterial;
  28038. };
  28039. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28040. if (!parsedMaterial.customType) {
  28041. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28042. }
  28043. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28044. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28045. if (!BABYLON.LegacyPBRMaterial) {
  28046. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28047. return;
  28048. }
  28049. }
  28050. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28051. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28052. ;
  28053. };
  28054. Material._TriangleFillMode = 0;
  28055. Material._WireFrameFillMode = 1;
  28056. Material._PointFillMode = 2;
  28057. Material._ClockWiseSideOrientation = 0;
  28058. Material._CounterClockWiseSideOrientation = 1;
  28059. Material._TextureDirtyFlag = 1;
  28060. Material._LightDirtyFlag = 2;
  28061. Material._FresnelDirtyFlag = 4;
  28062. Material._AttributesDirtyFlag = 8;
  28063. Material._MiscDirtyFlag = 16;
  28064. __decorate([
  28065. BABYLON.serialize()
  28066. ], Material.prototype, "id", void 0);
  28067. __decorate([
  28068. BABYLON.serialize()
  28069. ], Material.prototype, "name", void 0);
  28070. __decorate([
  28071. BABYLON.serialize()
  28072. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28073. __decorate([
  28074. BABYLON.serialize()
  28075. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28076. __decorate([
  28077. BABYLON.serialize()
  28078. ], Material.prototype, "state", void 0);
  28079. __decorate([
  28080. BABYLON.serialize()
  28081. ], Material.prototype, "alpha", void 0);
  28082. __decorate([
  28083. BABYLON.serialize("backFaceCulling")
  28084. ], Material.prototype, "_backFaceCulling", void 0);
  28085. __decorate([
  28086. BABYLON.serialize()
  28087. ], Material.prototype, "sideOrientation", void 0);
  28088. __decorate([
  28089. BABYLON.serialize("alphaMode")
  28090. ], Material.prototype, "_alphaMode", void 0);
  28091. __decorate([
  28092. BABYLON.serialize()
  28093. ], Material.prototype, "_needDepthPrePass", void 0);
  28094. __decorate([
  28095. BABYLON.serialize()
  28096. ], Material.prototype, "disableDepthWrite", void 0);
  28097. __decorate([
  28098. BABYLON.serialize()
  28099. ], Material.prototype, "forceDepthWrite", void 0);
  28100. __decorate([
  28101. BABYLON.serialize()
  28102. ], Material.prototype, "separateCullingPass", void 0);
  28103. __decorate([
  28104. BABYLON.serialize("fogEnabled")
  28105. ], Material.prototype, "_fogEnabled", void 0);
  28106. __decorate([
  28107. BABYLON.serialize()
  28108. ], Material.prototype, "pointSize", void 0);
  28109. __decorate([
  28110. BABYLON.serialize()
  28111. ], Material.prototype, "zOffset", void 0);
  28112. __decorate([
  28113. BABYLON.serialize()
  28114. ], Material.prototype, "wireframe", null);
  28115. __decorate([
  28116. BABYLON.serialize()
  28117. ], Material.prototype, "pointsCloud", null);
  28118. __decorate([
  28119. BABYLON.serialize()
  28120. ], Material.prototype, "fillMode", null);
  28121. return Material;
  28122. }());
  28123. BABYLON.Material = Material;
  28124. })(BABYLON || (BABYLON = {}));
  28125. //# sourceMappingURL=babylon.material.js.map
  28126. var BABYLON;
  28127. (function (BABYLON) {
  28128. var UniformBuffer = /** @class */ (function () {
  28129. /**
  28130. * Uniform buffer objects.
  28131. *
  28132. * Handles blocks of uniform on the GPU.
  28133. *
  28134. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28135. *
  28136. * For more information, please refer to :
  28137. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28138. */
  28139. function UniformBuffer(engine, data, dynamic) {
  28140. this._engine = engine;
  28141. this._noUBO = !engine.supportsUniformBuffers;
  28142. this._dynamic = dynamic;
  28143. this._data = data || [];
  28144. this._uniformLocations = {};
  28145. this._uniformSizes = {};
  28146. this._uniformLocationPointer = 0;
  28147. this._needSync = false;
  28148. if (this._noUBO) {
  28149. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28150. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28151. this.updateFloat = this._updateFloatForEffect;
  28152. this.updateFloat2 = this._updateFloat2ForEffect;
  28153. this.updateFloat3 = this._updateFloat3ForEffect;
  28154. this.updateFloat4 = this._updateFloat4ForEffect;
  28155. this.updateMatrix = this._updateMatrixForEffect;
  28156. this.updateVector3 = this._updateVector3ForEffect;
  28157. this.updateVector4 = this._updateVector4ForEffect;
  28158. this.updateColor3 = this._updateColor3ForEffect;
  28159. this.updateColor4 = this._updateColor4ForEffect;
  28160. }
  28161. else {
  28162. this._engine._uniformBuffers.push(this);
  28163. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28164. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28165. this.updateFloat = this._updateFloatForUniform;
  28166. this.updateFloat2 = this._updateFloat2ForUniform;
  28167. this.updateFloat3 = this._updateFloat3ForUniform;
  28168. this.updateFloat4 = this._updateFloat4ForUniform;
  28169. this.updateMatrix = this._updateMatrixForUniform;
  28170. this.updateVector3 = this._updateVector3ForUniform;
  28171. this.updateVector4 = this._updateVector4ForUniform;
  28172. this.updateColor3 = this._updateColor3ForUniform;
  28173. this.updateColor4 = this._updateColor4ForUniform;
  28174. }
  28175. }
  28176. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28177. // Properties
  28178. /**
  28179. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28180. * or just falling back on setUniformXXX calls.
  28181. */
  28182. get: function () {
  28183. return !this._noUBO;
  28184. },
  28185. enumerable: true,
  28186. configurable: true
  28187. });
  28188. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28189. /**
  28190. * Indicates if the WebGL underlying uniform buffer is in sync
  28191. * with the javascript cache data.
  28192. */
  28193. get: function () {
  28194. return !this._needSync;
  28195. },
  28196. enumerable: true,
  28197. configurable: true
  28198. });
  28199. /**
  28200. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28201. * Also, a dynamic UniformBuffer will disable cache verification and always
  28202. * update the underlying WebGL uniform buffer to the GPU.
  28203. */
  28204. UniformBuffer.prototype.isDynamic = function () {
  28205. return this._dynamic !== undefined;
  28206. };
  28207. /**
  28208. * The data cache on JS side.
  28209. */
  28210. UniformBuffer.prototype.getData = function () {
  28211. return this._bufferData;
  28212. };
  28213. /**
  28214. * The underlying WebGL Uniform buffer.
  28215. */
  28216. UniformBuffer.prototype.getBuffer = function () {
  28217. return this._buffer;
  28218. };
  28219. /**
  28220. * std140 layout specifies how to align data within an UBO structure.
  28221. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28222. * for specs.
  28223. */
  28224. UniformBuffer.prototype._fillAlignment = function (size) {
  28225. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28226. // and 4x4 matrices
  28227. // TODO : change if other types are used
  28228. var alignment;
  28229. if (size <= 2) {
  28230. alignment = size;
  28231. }
  28232. else {
  28233. alignment = 4;
  28234. }
  28235. if ((this._uniformLocationPointer % alignment) !== 0) {
  28236. var oldPointer = this._uniformLocationPointer;
  28237. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28238. var diff = this._uniformLocationPointer - oldPointer;
  28239. for (var i = 0; i < diff; i++) {
  28240. this._data.push(0);
  28241. }
  28242. }
  28243. };
  28244. /**
  28245. * Adds an uniform in the buffer.
  28246. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28247. * for the layout to be correct !
  28248. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28249. * @param {number|number[]} size Data size, or data directly.
  28250. */
  28251. UniformBuffer.prototype.addUniform = function (name, size) {
  28252. if (this._noUBO) {
  28253. return;
  28254. }
  28255. if (this._uniformLocations[name] !== undefined) {
  28256. // Already existing uniform
  28257. return;
  28258. }
  28259. // This function must be called in the order of the shader layout !
  28260. // size can be the size of the uniform, or data directly
  28261. var data;
  28262. if (size instanceof Array) {
  28263. data = size;
  28264. size = data.length;
  28265. }
  28266. else {
  28267. size = size;
  28268. data = [];
  28269. // Fill with zeros
  28270. for (var i = 0; i < size; i++) {
  28271. data.push(0);
  28272. }
  28273. }
  28274. this._fillAlignment(size);
  28275. this._uniformSizes[name] = size;
  28276. this._uniformLocations[name] = this._uniformLocationPointer;
  28277. this._uniformLocationPointer += size;
  28278. for (var i = 0; i < size; i++) {
  28279. this._data.push(data[i]);
  28280. }
  28281. this._needSync = true;
  28282. };
  28283. /**
  28284. * Wrapper for addUniform.
  28285. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28286. * @param {Matrix} mat A 4x4 matrix.
  28287. */
  28288. UniformBuffer.prototype.addMatrix = function (name, mat) {
  28289. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  28290. };
  28291. /**
  28292. * Wrapper for addUniform.
  28293. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28294. * @param {number} x
  28295. * @param {number} y
  28296. */
  28297. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  28298. var temp = [x, y];
  28299. this.addUniform(name, temp);
  28300. };
  28301. /**
  28302. * Wrapper for addUniform.
  28303. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28304. * @param {number} x
  28305. * @param {number} y
  28306. * @param {number} z
  28307. */
  28308. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  28309. var temp = [x, y, z];
  28310. this.addUniform(name, temp);
  28311. };
  28312. /**
  28313. * Wrapper for addUniform.
  28314. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28315. * @param {Color3} color
  28316. */
  28317. UniformBuffer.prototype.addColor3 = function (name, color) {
  28318. var temp = new Array();
  28319. color.toArray(temp);
  28320. this.addUniform(name, temp);
  28321. };
  28322. /**
  28323. * Wrapper for addUniform.
  28324. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28325. * @param {Color3} color
  28326. * @param {number} alpha
  28327. */
  28328. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  28329. var temp = new Array();
  28330. color.toArray(temp);
  28331. temp.push(alpha);
  28332. this.addUniform(name, temp);
  28333. };
  28334. /**
  28335. * Wrapper for addUniform.
  28336. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28337. * @param {Vector3} vector
  28338. */
  28339. UniformBuffer.prototype.addVector3 = function (name, vector) {
  28340. var temp = new Array();
  28341. vector.toArray(temp);
  28342. this.addUniform(name, temp);
  28343. };
  28344. /**
  28345. * Wrapper for addUniform.
  28346. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28347. */
  28348. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  28349. this.addUniform(name, 12);
  28350. };
  28351. /**
  28352. * Wrapper for addUniform.
  28353. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28354. */
  28355. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  28356. this.addUniform(name, 8);
  28357. };
  28358. /**
  28359. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  28360. */
  28361. UniformBuffer.prototype.create = function () {
  28362. if (this._noUBO) {
  28363. return;
  28364. }
  28365. if (this._buffer) {
  28366. return; // nothing to do
  28367. }
  28368. // See spec, alignment must be filled as a vec4
  28369. this._fillAlignment(4);
  28370. this._bufferData = new Float32Array(this._data);
  28371. this._rebuild();
  28372. this._needSync = true;
  28373. };
  28374. UniformBuffer.prototype._rebuild = function () {
  28375. if (this._noUBO) {
  28376. return;
  28377. }
  28378. if (this._dynamic) {
  28379. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  28380. }
  28381. else {
  28382. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  28383. }
  28384. };
  28385. /**
  28386. * Updates the WebGL Uniform Buffer on the GPU.
  28387. * If the `dynamic` flag is set to true, no cache comparison is done.
  28388. * Otherwise, the buffer will be updated only if the cache differs.
  28389. */
  28390. UniformBuffer.prototype.update = function () {
  28391. if (!this._buffer) {
  28392. this.create();
  28393. return;
  28394. }
  28395. if (!this._dynamic && !this._needSync) {
  28396. return;
  28397. }
  28398. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  28399. this._needSync = false;
  28400. };
  28401. /**
  28402. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28403. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28404. * @param {number[]|Float32Array} data Flattened data
  28405. * @param {number} size Size of the data.
  28406. */
  28407. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28408. var location = this._uniformLocations[uniformName];
  28409. if (location === undefined) {
  28410. if (this._buffer) {
  28411. // Cannot add an uniform if the buffer is already created
  28412. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28413. return;
  28414. }
  28415. this.addUniform(uniformName, size);
  28416. location = this._uniformLocations[uniformName];
  28417. }
  28418. if (!this._buffer) {
  28419. this.create();
  28420. }
  28421. if (!this._dynamic) {
  28422. // Cache for static uniform buffers
  28423. var changed = false;
  28424. for (var i = 0; i < size; i++) {
  28425. if (this._bufferData[location + i] !== data[i]) {
  28426. changed = true;
  28427. this._bufferData[location + i] = data[i];
  28428. }
  28429. }
  28430. this._needSync = this._needSync || changed;
  28431. }
  28432. else {
  28433. // No cache for dynamic
  28434. for (var i = 0; i < size; i++) {
  28435. this._bufferData[location + i] = data[i];
  28436. }
  28437. }
  28438. };
  28439. // Update methods
  28440. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28441. // To match std140, matrix must be realigned
  28442. for (var i = 0; i < 3; i++) {
  28443. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28444. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28445. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28446. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28447. }
  28448. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28449. };
  28450. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28451. this._currentEffect.setMatrix3x3(name, matrix);
  28452. };
  28453. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28454. this._currentEffect.setMatrix2x2(name, matrix);
  28455. };
  28456. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28457. // To match std140, matrix must be realigned
  28458. for (var i = 0; i < 2; i++) {
  28459. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28460. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28461. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28462. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28463. }
  28464. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28465. };
  28466. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28467. this._currentEffect.setFloat(name, x);
  28468. };
  28469. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28470. UniformBuffer._tempBuffer[0] = x;
  28471. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28472. };
  28473. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28474. if (suffix === void 0) { suffix = ""; }
  28475. this._currentEffect.setFloat2(name + suffix, x, y);
  28476. };
  28477. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28478. if (suffix === void 0) { suffix = ""; }
  28479. UniformBuffer._tempBuffer[0] = x;
  28480. UniformBuffer._tempBuffer[1] = y;
  28481. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28482. };
  28483. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28484. if (suffix === void 0) { suffix = ""; }
  28485. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28486. };
  28487. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28488. if (suffix === void 0) { suffix = ""; }
  28489. UniformBuffer._tempBuffer[0] = x;
  28490. UniformBuffer._tempBuffer[1] = y;
  28491. UniformBuffer._tempBuffer[2] = z;
  28492. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28493. };
  28494. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28495. if (suffix === void 0) { suffix = ""; }
  28496. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28497. };
  28498. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28499. if (suffix === void 0) { suffix = ""; }
  28500. UniformBuffer._tempBuffer[0] = x;
  28501. UniformBuffer._tempBuffer[1] = y;
  28502. UniformBuffer._tempBuffer[2] = z;
  28503. UniformBuffer._tempBuffer[3] = w;
  28504. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28505. };
  28506. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28507. this._currentEffect.setMatrix(name, mat);
  28508. };
  28509. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28510. this.updateUniform(name, mat.toArray(), 16);
  28511. };
  28512. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28513. this._currentEffect.setVector3(name, vector);
  28514. };
  28515. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28516. vector.toArray(UniformBuffer._tempBuffer);
  28517. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28518. };
  28519. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28520. this._currentEffect.setVector4(name, vector);
  28521. };
  28522. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28523. vector.toArray(UniformBuffer._tempBuffer);
  28524. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28525. };
  28526. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28527. if (suffix === void 0) { suffix = ""; }
  28528. this._currentEffect.setColor3(name + suffix, color);
  28529. };
  28530. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28531. if (suffix === void 0) { suffix = ""; }
  28532. color.toArray(UniformBuffer._tempBuffer);
  28533. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28534. };
  28535. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28536. if (suffix === void 0) { suffix = ""; }
  28537. this._currentEffect.setColor4(name + suffix, color, alpha);
  28538. };
  28539. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  28540. if (suffix === void 0) { suffix = ""; }
  28541. color.toArray(UniformBuffer._tempBuffer);
  28542. UniformBuffer._tempBuffer[3] = alpha;
  28543. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28544. };
  28545. /**
  28546. * Sets a sampler uniform on the effect.
  28547. * @param {string} name Name of the sampler.
  28548. * @param {Texture} texture
  28549. */
  28550. UniformBuffer.prototype.setTexture = function (name, texture) {
  28551. this._currentEffect.setTexture(name, texture);
  28552. };
  28553. /**
  28554. * Directly updates the value of the uniform in the cache AND on the GPU.
  28555. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28556. * @param {number[]|Float32Array} data Flattened data
  28557. */
  28558. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28559. this.updateUniform(uniformName, data, data.length);
  28560. this.update();
  28561. };
  28562. /**
  28563. * Binds this uniform buffer to an effect.
  28564. * @param {Effect} effect
  28565. * @param {string} name Name of the uniform block in the shader.
  28566. */
  28567. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28568. this._currentEffect = effect;
  28569. if (this._noUBO || !this._buffer) {
  28570. return;
  28571. }
  28572. effect.bindUniformBuffer(this._buffer, name);
  28573. };
  28574. /**
  28575. * Disposes the uniform buffer.
  28576. */
  28577. UniformBuffer.prototype.dispose = function () {
  28578. if (this._noUBO) {
  28579. return;
  28580. }
  28581. var index = this._engine._uniformBuffers.indexOf(this);
  28582. if (index !== -1) {
  28583. this._engine._uniformBuffers.splice(index, 1);
  28584. }
  28585. if (!this._buffer) {
  28586. return;
  28587. }
  28588. if (this._engine._releaseBuffer(this._buffer)) {
  28589. this._buffer = null;
  28590. }
  28591. };
  28592. // Pool for avoiding memory leaks
  28593. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28594. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28595. return UniformBuffer;
  28596. }());
  28597. BABYLON.UniformBuffer = UniformBuffer;
  28598. })(BABYLON || (BABYLON = {}));
  28599. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28600. var BABYLON;
  28601. (function (BABYLON) {
  28602. var PushMaterial = /** @class */ (function (_super) {
  28603. __extends(PushMaterial, _super);
  28604. function PushMaterial(name, scene) {
  28605. var _this = _super.call(this, name, scene) || this;
  28606. _this.storeEffectOnSubMeshes = true;
  28607. return _this;
  28608. }
  28609. PushMaterial.prototype.getEffect = function () {
  28610. return this._activeEffect;
  28611. };
  28612. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  28613. if (!mesh) {
  28614. return false;
  28615. }
  28616. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  28617. return true;
  28618. }
  28619. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  28620. };
  28621. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28622. this._activeEffect.setMatrix("world", world);
  28623. };
  28624. PushMaterial.prototype.bind = function (world, mesh) {
  28625. if (!mesh) {
  28626. return;
  28627. }
  28628. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  28629. };
  28630. PushMaterial.prototype._afterBind = function (mesh, effect) {
  28631. if (effect === void 0) { effect = null; }
  28632. _super.prototype._afterBind.call(this, mesh);
  28633. this.getScene()._cachedEffect = effect;
  28634. };
  28635. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  28636. if (visibility === void 0) { visibility = 1; }
  28637. return scene.isCachedMaterialInvalid(this, effect, visibility);
  28638. };
  28639. return PushMaterial;
  28640. }(BABYLON.Material));
  28641. BABYLON.PushMaterial = PushMaterial;
  28642. })(BABYLON || (BABYLON = {}));
  28643. //# sourceMappingURL=babylon.pushMaterial.js.map
  28644. var BABYLON;
  28645. (function (BABYLON) {
  28646. var VertexData = /** @class */ (function () {
  28647. function VertexData() {
  28648. }
  28649. VertexData.prototype.set = function (data, kind) {
  28650. switch (kind) {
  28651. case BABYLON.VertexBuffer.PositionKind:
  28652. this.positions = data;
  28653. break;
  28654. case BABYLON.VertexBuffer.NormalKind:
  28655. this.normals = data;
  28656. break;
  28657. case BABYLON.VertexBuffer.TangentKind:
  28658. this.tangents = data;
  28659. break;
  28660. case BABYLON.VertexBuffer.UVKind:
  28661. this.uvs = data;
  28662. break;
  28663. case BABYLON.VertexBuffer.UV2Kind:
  28664. this.uvs2 = data;
  28665. break;
  28666. case BABYLON.VertexBuffer.UV3Kind:
  28667. this.uvs3 = data;
  28668. break;
  28669. case BABYLON.VertexBuffer.UV4Kind:
  28670. this.uvs4 = data;
  28671. break;
  28672. case BABYLON.VertexBuffer.UV5Kind:
  28673. this.uvs5 = data;
  28674. break;
  28675. case BABYLON.VertexBuffer.UV6Kind:
  28676. this.uvs6 = data;
  28677. break;
  28678. case BABYLON.VertexBuffer.ColorKind:
  28679. this.colors = data;
  28680. break;
  28681. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28682. this.matricesIndices = data;
  28683. break;
  28684. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28685. this.matricesWeights = data;
  28686. break;
  28687. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28688. this.matricesIndicesExtra = data;
  28689. break;
  28690. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28691. this.matricesWeightsExtra = data;
  28692. break;
  28693. }
  28694. };
  28695. /**
  28696. * Associates the vertexData to the passed Mesh.
  28697. * Sets it as updatable or not (default `false`).
  28698. * Returns the VertexData.
  28699. */
  28700. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28701. this._applyTo(mesh, updatable);
  28702. return this;
  28703. };
  28704. /**
  28705. * Associates the vertexData to the passed Geometry.
  28706. * Sets it as updatable or not (default `false`).
  28707. * Returns the VertexData.
  28708. */
  28709. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28710. this._applyTo(geometry, updatable);
  28711. return this;
  28712. };
  28713. /**
  28714. * Updates the associated mesh.
  28715. * Returns the VertexData.
  28716. */
  28717. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28718. this._update(mesh);
  28719. return this;
  28720. };
  28721. /**
  28722. * Updates the associated geometry.
  28723. * Returns the VertexData.
  28724. */
  28725. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28726. this._update(geometry);
  28727. return this;
  28728. };
  28729. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28730. if (updatable === void 0) { updatable = false; }
  28731. if (this.positions) {
  28732. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28733. }
  28734. if (this.normals) {
  28735. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28736. }
  28737. if (this.tangents) {
  28738. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28739. }
  28740. if (this.uvs) {
  28741. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28742. }
  28743. if (this.uvs2) {
  28744. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28745. }
  28746. if (this.uvs3) {
  28747. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28748. }
  28749. if (this.uvs4) {
  28750. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28751. }
  28752. if (this.uvs5) {
  28753. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28754. }
  28755. if (this.uvs6) {
  28756. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28757. }
  28758. if (this.colors) {
  28759. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28760. }
  28761. if (this.matricesIndices) {
  28762. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28763. }
  28764. if (this.matricesWeights) {
  28765. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28766. }
  28767. if (this.matricesIndicesExtra) {
  28768. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28769. }
  28770. if (this.matricesWeightsExtra) {
  28771. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28772. }
  28773. if (this.indices) {
  28774. meshOrGeometry.setIndices(this.indices, null, updatable);
  28775. }
  28776. return this;
  28777. };
  28778. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28779. if (this.positions) {
  28780. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28781. }
  28782. if (this.normals) {
  28783. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28784. }
  28785. if (this.tangents) {
  28786. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28787. }
  28788. if (this.uvs) {
  28789. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28790. }
  28791. if (this.uvs2) {
  28792. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28793. }
  28794. if (this.uvs3) {
  28795. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28796. }
  28797. if (this.uvs4) {
  28798. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28799. }
  28800. if (this.uvs5) {
  28801. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28802. }
  28803. if (this.uvs6) {
  28804. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28805. }
  28806. if (this.colors) {
  28807. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28808. }
  28809. if (this.matricesIndices) {
  28810. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28811. }
  28812. if (this.matricesWeights) {
  28813. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28814. }
  28815. if (this.matricesIndicesExtra) {
  28816. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28817. }
  28818. if (this.matricesWeightsExtra) {
  28819. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28820. }
  28821. if (this.indices) {
  28822. meshOrGeometry.setIndices(this.indices, null);
  28823. }
  28824. return this;
  28825. };
  28826. /**
  28827. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28828. * Returns the VertexData.
  28829. */
  28830. VertexData.prototype.transform = function (matrix) {
  28831. var transformed = BABYLON.Vector3.Zero();
  28832. var index;
  28833. if (this.positions) {
  28834. var position = BABYLON.Vector3.Zero();
  28835. for (index = 0; index < this.positions.length; index += 3) {
  28836. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28837. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28838. this.positions[index] = transformed.x;
  28839. this.positions[index + 1] = transformed.y;
  28840. this.positions[index + 2] = transformed.z;
  28841. }
  28842. }
  28843. if (this.normals) {
  28844. var normal = BABYLON.Vector3.Zero();
  28845. for (index = 0; index < this.normals.length; index += 3) {
  28846. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28847. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28848. this.normals[index] = transformed.x;
  28849. this.normals[index + 1] = transformed.y;
  28850. this.normals[index + 2] = transformed.z;
  28851. }
  28852. }
  28853. if (this.tangents) {
  28854. var tangent = BABYLON.Vector4.Zero();
  28855. var tangentTransformed = BABYLON.Vector4.Zero();
  28856. for (index = 0; index < this.tangents.length; index += 4) {
  28857. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28858. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28859. this.tangents[index] = tangentTransformed.x;
  28860. this.tangents[index + 1] = tangentTransformed.y;
  28861. this.tangents[index + 2] = tangentTransformed.z;
  28862. this.tangents[index + 3] = tangentTransformed.w;
  28863. }
  28864. }
  28865. return this;
  28866. };
  28867. /**
  28868. * Merges the passed VertexData into the current one.
  28869. * Returns the modified VertexData.
  28870. */
  28871. VertexData.prototype.merge = function (other, options) {
  28872. options = options || {};
  28873. if (other.indices) {
  28874. if (!this.indices) {
  28875. this.indices = [];
  28876. }
  28877. var offset = this.positions ? this.positions.length / 3 : 0;
  28878. for (var index = 0; index < other.indices.length; index++) {
  28879. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28880. this.indices.push(other.indices[index] + offset);
  28881. }
  28882. }
  28883. this.positions = this._mergeElement(this.positions, other.positions);
  28884. if (!this.positions) {
  28885. return this;
  28886. }
  28887. var count = this.positions.length / 3;
  28888. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28889. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28890. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28891. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28892. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28893. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28894. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28895. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28896. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  28897. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28898. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28899. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28900. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28901. return this;
  28902. };
  28903. VertexData.prototype._mergeElement = function (source, other, length) {
  28904. if (length === void 0) { length = 0; }
  28905. if (!other && !source) {
  28906. return null;
  28907. }
  28908. if (!other) {
  28909. return this._mergeElement(source, new Float32Array(source.length), length);
  28910. }
  28911. if (!source) {
  28912. if (length === 0 || length === other.length) {
  28913. return other;
  28914. }
  28915. return this._mergeElement(new Float32Array(length - other.length), other, length);
  28916. }
  28917. var len = other.length + source.length;
  28918. var isSrcTypedArray = source instanceof Float32Array;
  28919. var isOthTypedArray = other instanceof Float32Array;
  28920. // use non-loop method when the source is Float32Array
  28921. if (isSrcTypedArray) {
  28922. var ret32 = new Float32Array(len);
  28923. ret32.set(source);
  28924. ret32.set(other, source.length);
  28925. return ret32;
  28926. // source is number[], when other is also use concat
  28927. }
  28928. else if (!isOthTypedArray) {
  28929. return source.concat(other);
  28930. // source is a number[], but other is a Float32Array, loop required
  28931. }
  28932. else {
  28933. var ret = source.slice(0); // copy source to a separate array
  28934. for (var i = 0, len = other.length; i < len; i++) {
  28935. ret.push(other[i]);
  28936. }
  28937. return ret;
  28938. }
  28939. };
  28940. /**
  28941. * Serializes the VertexData.
  28942. * Returns a serialized object.
  28943. */
  28944. VertexData.prototype.serialize = function () {
  28945. var serializationObject = this.serialize();
  28946. if (this.positions) {
  28947. serializationObject.positions = this.positions;
  28948. }
  28949. if (this.normals) {
  28950. serializationObject.normals = this.normals;
  28951. }
  28952. if (this.tangents) {
  28953. serializationObject.tangents = this.tangents;
  28954. }
  28955. if (this.uvs) {
  28956. serializationObject.uvs = this.uvs;
  28957. }
  28958. if (this.uvs2) {
  28959. serializationObject.uvs2 = this.uvs2;
  28960. }
  28961. if (this.uvs3) {
  28962. serializationObject.uvs3 = this.uvs3;
  28963. }
  28964. if (this.uvs4) {
  28965. serializationObject.uvs4 = this.uvs4;
  28966. }
  28967. if (this.uvs5) {
  28968. serializationObject.uvs5 = this.uvs5;
  28969. }
  28970. if (this.uvs6) {
  28971. serializationObject.uvs6 = this.uvs6;
  28972. }
  28973. if (this.colors) {
  28974. serializationObject.colors = this.colors;
  28975. }
  28976. if (this.matricesIndices) {
  28977. serializationObject.matricesIndices = this.matricesIndices;
  28978. serializationObject.matricesIndices._isExpanded = true;
  28979. }
  28980. if (this.matricesWeights) {
  28981. serializationObject.matricesWeights = this.matricesWeights;
  28982. }
  28983. if (this.matricesIndicesExtra) {
  28984. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28985. serializationObject.matricesIndicesExtra._isExpanded = true;
  28986. }
  28987. if (this.matricesWeightsExtra) {
  28988. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28989. }
  28990. serializationObject.indices = this.indices;
  28991. return serializationObject;
  28992. };
  28993. // Statics
  28994. /**
  28995. * Returns the object VertexData associated to the passed mesh.
  28996. */
  28997. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  28998. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  28999. };
  29000. /**
  29001. * Returns the object VertexData associated to the passed geometry.
  29002. */
  29003. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29004. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29005. };
  29006. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29007. var result = new VertexData();
  29008. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29009. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29010. }
  29011. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29012. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29013. }
  29014. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29015. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29016. }
  29017. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29018. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29019. }
  29020. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29021. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29022. }
  29023. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29024. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29025. }
  29026. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29027. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29028. }
  29029. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29030. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29031. }
  29032. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29033. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29034. }
  29035. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29036. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29037. }
  29038. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29039. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29040. }
  29041. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29042. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29043. }
  29044. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29045. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29046. }
  29047. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29048. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29049. }
  29050. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29051. return result;
  29052. };
  29053. /**
  29054. * Creates the vertexData of the Ribbon.
  29055. */
  29056. VertexData.CreateRibbon = function (options) {
  29057. var pathArray = options.pathArray;
  29058. var closeArray = options.closeArray || false;
  29059. var closePath = options.closePath || false;
  29060. var invertUV = options.invertUV || false;
  29061. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29062. var offset = options.offset || defaultOffset;
  29063. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29064. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29065. var customUV = options.uvs;
  29066. var customColors = options.colors;
  29067. var positions = [];
  29068. var indices = [];
  29069. var normals = [];
  29070. var uvs = [];
  29071. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29072. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29073. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29074. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29075. var minlg; // minimal length among all paths from pathArray
  29076. var lg = []; // array of path lengths : nb of vertex per path
  29077. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29078. var p; // path iterator
  29079. var i; // point iterator
  29080. var j; // point iterator
  29081. // if single path in pathArray
  29082. if (pathArray.length < 2) {
  29083. var ar1 = [];
  29084. var ar2 = [];
  29085. for (i = 0; i < pathArray[0].length - offset; i++) {
  29086. ar1.push(pathArray[0][i]);
  29087. ar2.push(pathArray[0][i + offset]);
  29088. }
  29089. pathArray = [ar1, ar2];
  29090. }
  29091. // positions and horizontal distances (u)
  29092. var idc = 0;
  29093. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29094. var path;
  29095. var l;
  29096. minlg = pathArray[0].length;
  29097. var vectlg;
  29098. var dist;
  29099. for (p = 0; p < pathArray.length; p++) {
  29100. uTotalDistance[p] = 0;
  29101. us[p] = [0];
  29102. path = pathArray[p];
  29103. l = path.length;
  29104. minlg = (minlg < l) ? minlg : l;
  29105. j = 0;
  29106. while (j < l) {
  29107. positions.push(path[j].x, path[j].y, path[j].z);
  29108. if (j > 0) {
  29109. vectlg = path[j].subtract(path[j - 1]).length();
  29110. dist = vectlg + uTotalDistance[p];
  29111. us[p].push(dist);
  29112. uTotalDistance[p] = dist;
  29113. }
  29114. j++;
  29115. }
  29116. if (closePath) {
  29117. j--;
  29118. positions.push(path[0].x, path[0].y, path[0].z);
  29119. vectlg = path[j].subtract(path[0]).length();
  29120. dist = vectlg + uTotalDistance[p];
  29121. us[p].push(dist);
  29122. uTotalDistance[p] = dist;
  29123. }
  29124. lg[p] = l + closePathCorr;
  29125. idx[p] = idc;
  29126. idc += (l + closePathCorr);
  29127. }
  29128. // vertical distances (v)
  29129. var path1;
  29130. var path2;
  29131. var vertex1 = null;
  29132. var vertex2 = null;
  29133. for (i = 0; i < minlg + closePathCorr; i++) {
  29134. vTotalDistance[i] = 0;
  29135. vs[i] = [0];
  29136. for (p = 0; p < pathArray.length - 1; p++) {
  29137. path1 = pathArray[p];
  29138. path2 = pathArray[p + 1];
  29139. if (i === minlg) {
  29140. vertex1 = path1[0];
  29141. vertex2 = path2[0];
  29142. }
  29143. else {
  29144. vertex1 = path1[i];
  29145. vertex2 = path2[i];
  29146. }
  29147. vectlg = vertex2.subtract(vertex1).length();
  29148. dist = vectlg + vTotalDistance[i];
  29149. vs[i].push(dist);
  29150. vTotalDistance[i] = dist;
  29151. }
  29152. if (closeArray && vertex2 && vertex1) {
  29153. path1 = pathArray[p];
  29154. path2 = pathArray[0];
  29155. if (i === minlg) {
  29156. vertex2 = path2[0];
  29157. }
  29158. vectlg = vertex2.subtract(vertex1).length();
  29159. dist = vectlg + vTotalDistance[i];
  29160. vTotalDistance[i] = dist;
  29161. }
  29162. }
  29163. // uvs
  29164. var u;
  29165. var v;
  29166. if (customUV) {
  29167. for (p = 0; p < customUV.length; p++) {
  29168. uvs.push(customUV[p].x, customUV[p].y);
  29169. }
  29170. }
  29171. else {
  29172. for (p = 0; p < pathArray.length; p++) {
  29173. for (i = 0; i < minlg + closePathCorr; i++) {
  29174. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29175. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29176. if (invertUV) {
  29177. uvs.push(v, u);
  29178. }
  29179. else {
  29180. uvs.push(u, v);
  29181. }
  29182. }
  29183. }
  29184. }
  29185. // indices
  29186. p = 0; // path index
  29187. var pi = 0; // positions array index
  29188. var l1 = lg[p] - 1; // path1 length
  29189. var l2 = lg[p + 1] - 1; // path2 length
  29190. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29191. var shft = idx[1] - idx[0]; // shift
  29192. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29193. while (pi <= min && p < path1nb) {
  29194. // 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
  29195. indices.push(pi, pi + shft, pi + 1);
  29196. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29197. pi += 1;
  29198. if (pi === min) {
  29199. p++;
  29200. if (p === lg.length - 1) {
  29201. shft = idx[0] - idx[p];
  29202. l1 = lg[p] - 1;
  29203. l2 = lg[0] - 1;
  29204. }
  29205. else {
  29206. shft = idx[p + 1] - idx[p];
  29207. l1 = lg[p] - 1;
  29208. l2 = lg[p + 1] - 1;
  29209. }
  29210. pi = idx[p];
  29211. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29212. }
  29213. }
  29214. // normals
  29215. VertexData.ComputeNormals(positions, indices, normals);
  29216. if (closePath) {
  29217. var indexFirst = 0;
  29218. var indexLast = 0;
  29219. for (p = 0; p < pathArray.length; p++) {
  29220. indexFirst = idx[p] * 3;
  29221. if (p + 1 < pathArray.length) {
  29222. indexLast = (idx[p + 1] - 1) * 3;
  29223. }
  29224. else {
  29225. indexLast = normals.length - 3;
  29226. }
  29227. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29228. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29229. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29230. normals[indexLast] = normals[indexFirst];
  29231. normals[indexLast + 1] = normals[indexFirst + 1];
  29232. normals[indexLast + 2] = normals[indexFirst + 2];
  29233. }
  29234. }
  29235. // sides
  29236. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29237. // Colors
  29238. var colors = null;
  29239. if (customColors) {
  29240. colors = new Float32Array(customColors.length * 4);
  29241. for (var c = 0; c < customColors.length; c++) {
  29242. colors[c * 4] = customColors[c].r;
  29243. colors[c * 4 + 1] = customColors[c].g;
  29244. colors[c * 4 + 2] = customColors[c].b;
  29245. colors[c * 4 + 3] = customColors[c].a;
  29246. }
  29247. }
  29248. // Result
  29249. var vertexData = new VertexData();
  29250. var positions32 = new Float32Array(positions);
  29251. var normals32 = new Float32Array(normals);
  29252. var uvs32 = new Float32Array(uvs);
  29253. vertexData.indices = indices;
  29254. vertexData.positions = positions32;
  29255. vertexData.normals = normals32;
  29256. vertexData.uvs = uvs32;
  29257. if (colors) {
  29258. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29259. }
  29260. if (closePath) {
  29261. vertexData._idx = idx;
  29262. }
  29263. return vertexData;
  29264. };
  29265. /**
  29266. * Creates the VertexData of the Box.
  29267. */
  29268. VertexData.CreateBox = function (options) {
  29269. var normalsSource = [
  29270. new BABYLON.Vector3(0, 0, 1),
  29271. new BABYLON.Vector3(0, 0, -1),
  29272. new BABYLON.Vector3(1, 0, 0),
  29273. new BABYLON.Vector3(-1, 0, 0),
  29274. new BABYLON.Vector3(0, 1, 0),
  29275. new BABYLON.Vector3(0, -1, 0)
  29276. ];
  29277. var indices = [];
  29278. var positions = [];
  29279. var normals = [];
  29280. var uvs = [];
  29281. var width = options.width || options.size || 1;
  29282. var height = options.height || options.size || 1;
  29283. var depth = options.depth || options.size || 1;
  29284. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29285. var faceUV = options.faceUV || new Array(6);
  29286. var faceColors = options.faceColors;
  29287. var colors = [];
  29288. // default face colors and UV if undefined
  29289. for (var f = 0; f < 6; f++) {
  29290. if (faceUV[f] === undefined) {
  29291. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29292. }
  29293. if (faceColors && faceColors[f] === undefined) {
  29294. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29295. }
  29296. }
  29297. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29298. // Create each face in turn.
  29299. for (var index = 0; index < normalsSource.length; index++) {
  29300. var normal = normalsSource[index];
  29301. // Get two vectors perpendicular to the face normal and to each other.
  29302. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29303. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29304. // Six indices (two triangles) per face.
  29305. var verticesLength = positions.length / 3;
  29306. indices.push(verticesLength);
  29307. indices.push(verticesLength + 1);
  29308. indices.push(verticesLength + 2);
  29309. indices.push(verticesLength);
  29310. indices.push(verticesLength + 2);
  29311. indices.push(verticesLength + 3);
  29312. // Four vertices per face.
  29313. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29314. positions.push(vertex.x, vertex.y, vertex.z);
  29315. normals.push(normal.x, normal.y, normal.z);
  29316. uvs.push(faceUV[index].z, faceUV[index].w);
  29317. if (faceColors) {
  29318. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29319. }
  29320. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29321. positions.push(vertex.x, vertex.y, vertex.z);
  29322. normals.push(normal.x, normal.y, normal.z);
  29323. uvs.push(faceUV[index].x, faceUV[index].w);
  29324. if (faceColors) {
  29325. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29326. }
  29327. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29328. positions.push(vertex.x, vertex.y, vertex.z);
  29329. normals.push(normal.x, normal.y, normal.z);
  29330. uvs.push(faceUV[index].x, faceUV[index].y);
  29331. if (faceColors) {
  29332. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29333. }
  29334. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29335. positions.push(vertex.x, vertex.y, vertex.z);
  29336. normals.push(normal.x, normal.y, normal.z);
  29337. uvs.push(faceUV[index].z, faceUV[index].y);
  29338. if (faceColors) {
  29339. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29340. }
  29341. }
  29342. // sides
  29343. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29344. // Result
  29345. var vertexData = new VertexData();
  29346. vertexData.indices = indices;
  29347. vertexData.positions = positions;
  29348. vertexData.normals = normals;
  29349. vertexData.uvs = uvs;
  29350. if (faceColors) {
  29351. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29352. vertexData.colors = totalColors;
  29353. }
  29354. return vertexData;
  29355. };
  29356. /**
  29357. * Creates the VertexData of the Sphere.
  29358. */
  29359. VertexData.CreateSphere = function (options) {
  29360. var segments = options.segments || 32;
  29361. var diameterX = options.diameterX || options.diameter || 1;
  29362. var diameterY = options.diameterY || options.diameter || 1;
  29363. var diameterZ = options.diameterZ || options.diameter || 1;
  29364. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29365. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29366. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29367. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29368. var totalZRotationSteps = 2 + segments;
  29369. var totalYRotationSteps = 2 * totalZRotationSteps;
  29370. var indices = [];
  29371. var positions = [];
  29372. var normals = [];
  29373. var uvs = [];
  29374. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29375. var normalizedZ = zRotationStep / totalZRotationSteps;
  29376. var angleZ = normalizedZ * Math.PI * slice;
  29377. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29378. var normalizedY = yRotationStep / totalYRotationSteps;
  29379. var angleY = normalizedY * Math.PI * 2 * arc;
  29380. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29381. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29382. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29383. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29384. var vertex = complete.multiply(radius);
  29385. var normal = complete.divide(radius).normalize();
  29386. positions.push(vertex.x, vertex.y, vertex.z);
  29387. normals.push(normal.x, normal.y, normal.z);
  29388. uvs.push(normalizedY, normalizedZ);
  29389. }
  29390. if (zRotationStep > 0) {
  29391. var verticesCount = positions.length / 3;
  29392. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29393. indices.push((firstIndex));
  29394. indices.push((firstIndex + 1));
  29395. indices.push(firstIndex + totalYRotationSteps + 1);
  29396. indices.push((firstIndex + totalYRotationSteps + 1));
  29397. indices.push((firstIndex + 1));
  29398. indices.push((firstIndex + totalYRotationSteps + 2));
  29399. }
  29400. }
  29401. }
  29402. // Sides
  29403. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29404. // Result
  29405. var vertexData = new VertexData();
  29406. vertexData.indices = indices;
  29407. vertexData.positions = positions;
  29408. vertexData.normals = normals;
  29409. vertexData.uvs = uvs;
  29410. return vertexData;
  29411. };
  29412. /**
  29413. * Creates the VertexData of the Cylinder or Cone.
  29414. */
  29415. VertexData.CreateCylinder = function (options) {
  29416. var height = options.height || 2;
  29417. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29418. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29419. var tessellation = options.tessellation || 24;
  29420. var subdivisions = options.subdivisions || 1;
  29421. var hasRings = options.hasRings ? true : false;
  29422. var enclose = options.enclose ? true : false;
  29423. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29424. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29425. var faceUV = options.faceUV || new Array(3);
  29426. var faceColors = options.faceColors;
  29427. // default face colors and UV if undefined
  29428. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29429. var ringNb = (hasRings) ? subdivisions : 1;
  29430. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29431. var f;
  29432. for (f = 0; f < surfaceNb; f++) {
  29433. if (faceColors && faceColors[f] === undefined) {
  29434. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29435. }
  29436. }
  29437. for (f = 0; f < surfaceNb; f++) {
  29438. if (faceUV && faceUV[f] === undefined) {
  29439. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29440. }
  29441. }
  29442. var indices = new Array();
  29443. var positions = new Array();
  29444. var normals = new Array();
  29445. var uvs = new Array();
  29446. var colors = new Array();
  29447. var angle_step = Math.PI * 2 * arc / tessellation;
  29448. var angle;
  29449. var h;
  29450. var radius;
  29451. var tan = (diameterBottom - diameterTop) / 2 / height;
  29452. var ringVertex = BABYLON.Vector3.Zero();
  29453. var ringNormal = BABYLON.Vector3.Zero();
  29454. var ringFirstVertex = BABYLON.Vector3.Zero();
  29455. var ringFirstNormal = BABYLON.Vector3.Zero();
  29456. var quadNormal = BABYLON.Vector3.Zero();
  29457. var Y = BABYLON.Axis.Y;
  29458. // positions, normals, uvs
  29459. var i;
  29460. var j;
  29461. var r;
  29462. var ringIdx = 1;
  29463. var s = 1; // surface index
  29464. var cs = 0;
  29465. var v = 0;
  29466. for (i = 0; i <= subdivisions; i++) {
  29467. h = i / subdivisions;
  29468. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29469. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29470. for (r = 0; r < ringIdx; r++) {
  29471. if (hasRings) {
  29472. s += r;
  29473. }
  29474. if (enclose) {
  29475. s += 2 * r;
  29476. }
  29477. for (j = 0; j <= tessellation; j++) {
  29478. angle = j * angle_step;
  29479. // position
  29480. ringVertex.x = Math.cos(-angle) * radius;
  29481. ringVertex.y = -height / 2 + h * height;
  29482. ringVertex.z = Math.sin(-angle) * radius;
  29483. // normal
  29484. if (diameterTop === 0 && i === subdivisions) {
  29485. // if no top cap, reuse former normals
  29486. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29487. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29488. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29489. }
  29490. else {
  29491. ringNormal.x = ringVertex.x;
  29492. ringNormal.z = ringVertex.z;
  29493. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29494. ringNormal.normalize();
  29495. }
  29496. // keep first ring vertex values for enclose
  29497. if (j === 0) {
  29498. ringFirstVertex.copyFrom(ringVertex);
  29499. ringFirstNormal.copyFrom(ringNormal);
  29500. }
  29501. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29502. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29503. if (hasRings) {
  29504. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29505. }
  29506. else {
  29507. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29508. }
  29509. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29510. if (faceColors) {
  29511. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29512. }
  29513. }
  29514. // if enclose, add four vertices and their dedicated normals
  29515. if (arc !== 1 && enclose) {
  29516. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29517. positions.push(0, ringVertex.y, 0);
  29518. positions.push(0, ringVertex.y, 0);
  29519. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29520. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29521. quadNormal.normalize();
  29522. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29523. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29524. quadNormal.normalize();
  29525. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29526. if (hasRings) {
  29527. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29528. }
  29529. else {
  29530. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29531. }
  29532. uvs.push(faceUV[s + 1].x, v);
  29533. uvs.push(faceUV[s + 1].z, v);
  29534. if (hasRings) {
  29535. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29536. }
  29537. else {
  29538. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29539. }
  29540. uvs.push(faceUV[s + 2].x, v);
  29541. uvs.push(faceUV[s + 2].z, v);
  29542. if (faceColors) {
  29543. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29544. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29545. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29546. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29547. }
  29548. }
  29549. if (cs !== s) {
  29550. cs = s;
  29551. }
  29552. }
  29553. }
  29554. // indices
  29555. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29556. var s;
  29557. i = 0;
  29558. for (s = 0; s < subdivisions; s++) {
  29559. var i0 = 0;
  29560. var i1 = 0;
  29561. var i2 = 0;
  29562. var i3 = 0;
  29563. for (j = 0; j < tessellation; j++) {
  29564. i0 = i * (e + 1) + j;
  29565. i1 = (i + 1) * (e + 1) + j;
  29566. i2 = i * (e + 1) + (j + 1);
  29567. i3 = (i + 1) * (e + 1) + (j + 1);
  29568. indices.push(i0, i1, i2);
  29569. indices.push(i3, i2, i1);
  29570. }
  29571. if (arc !== 1 && enclose) {
  29572. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29573. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29574. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29575. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29576. }
  29577. i = (hasRings) ? (i + 2) : (i + 1);
  29578. }
  29579. // Caps
  29580. var createCylinderCap = function (isTop) {
  29581. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29582. if (radius === 0) {
  29583. return;
  29584. }
  29585. // Cap positions, normals & uvs
  29586. var angle;
  29587. var circleVector;
  29588. var i;
  29589. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29590. var c = null;
  29591. if (faceColors) {
  29592. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29593. }
  29594. // cap center
  29595. var vbase = positions.length / 3;
  29596. var offset = isTop ? height / 2 : -height / 2;
  29597. var center = new BABYLON.Vector3(0, offset, 0);
  29598. positions.push(center.x, center.y, center.z);
  29599. normals.push(0, isTop ? 1 : -1, 0);
  29600. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29601. if (c) {
  29602. colors.push(c.r, c.g, c.b, c.a);
  29603. }
  29604. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29605. for (i = 0; i <= tessellation; i++) {
  29606. angle = Math.PI * 2 * i * arc / tessellation;
  29607. var cos = Math.cos(-angle);
  29608. var sin = Math.sin(-angle);
  29609. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29610. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29611. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29612. normals.push(0, isTop ? 1 : -1, 0);
  29613. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29614. if (c) {
  29615. colors.push(c.r, c.g, c.b, c.a);
  29616. }
  29617. }
  29618. // Cap indices
  29619. for (i = 0; i < tessellation; i++) {
  29620. if (!isTop) {
  29621. indices.push(vbase);
  29622. indices.push(vbase + (i + 1));
  29623. indices.push(vbase + (i + 2));
  29624. }
  29625. else {
  29626. indices.push(vbase);
  29627. indices.push(vbase + (i + 2));
  29628. indices.push(vbase + (i + 1));
  29629. }
  29630. }
  29631. };
  29632. // add caps to geometry
  29633. createCylinderCap(false);
  29634. createCylinderCap(true);
  29635. // Sides
  29636. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29637. var vertexData = new VertexData();
  29638. vertexData.indices = indices;
  29639. vertexData.positions = positions;
  29640. vertexData.normals = normals;
  29641. vertexData.uvs = uvs;
  29642. if (faceColors) {
  29643. vertexData.colors = colors;
  29644. }
  29645. return vertexData;
  29646. };
  29647. /**
  29648. * Creates the VertexData of the Torus.
  29649. */
  29650. VertexData.CreateTorus = function (options) {
  29651. var indices = [];
  29652. var positions = [];
  29653. var normals = [];
  29654. var uvs = [];
  29655. var diameter = options.diameter || 1;
  29656. var thickness = options.thickness || 0.5;
  29657. var tessellation = options.tessellation || 16;
  29658. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29659. var stride = tessellation + 1;
  29660. for (var i = 0; i <= tessellation; i++) {
  29661. var u = i / tessellation;
  29662. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29663. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29664. for (var j = 0; j <= tessellation; j++) {
  29665. var v = 1 - j / tessellation;
  29666. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29667. var dx = Math.cos(innerAngle);
  29668. var dy = Math.sin(innerAngle);
  29669. // Create a vertex.
  29670. var normal = new BABYLON.Vector3(dx, dy, 0);
  29671. var position = normal.scale(thickness / 2);
  29672. var textureCoordinate = new BABYLON.Vector2(u, v);
  29673. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29674. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29675. positions.push(position.x, position.y, position.z);
  29676. normals.push(normal.x, normal.y, normal.z);
  29677. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29678. // And create indices for two triangles.
  29679. var nextI = (i + 1) % stride;
  29680. var nextJ = (j + 1) % stride;
  29681. indices.push(i * stride + j);
  29682. indices.push(i * stride + nextJ);
  29683. indices.push(nextI * stride + j);
  29684. indices.push(i * stride + nextJ);
  29685. indices.push(nextI * stride + nextJ);
  29686. indices.push(nextI * stride + j);
  29687. }
  29688. }
  29689. // Sides
  29690. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29691. // Result
  29692. var vertexData = new VertexData();
  29693. vertexData.indices = indices;
  29694. vertexData.positions = positions;
  29695. vertexData.normals = normals;
  29696. vertexData.uvs = uvs;
  29697. return vertexData;
  29698. };
  29699. /**
  29700. * Creates the VertexData of the LineSystem.
  29701. */
  29702. VertexData.CreateLineSystem = function (options) {
  29703. var indices = [];
  29704. var positions = [];
  29705. var lines = options.lines;
  29706. var colors = options.colors;
  29707. var vertexColors = [];
  29708. var idx = 0;
  29709. for (var l = 0; l < lines.length; l++) {
  29710. var points = lines[l];
  29711. for (var index = 0; index < points.length; index++) {
  29712. positions.push(points[index].x, points[index].y, points[index].z);
  29713. if (colors) {
  29714. var color = colors[l];
  29715. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  29716. }
  29717. if (index > 0) {
  29718. indices.push(idx - 1);
  29719. indices.push(idx);
  29720. }
  29721. idx++;
  29722. }
  29723. }
  29724. var vertexData = new VertexData();
  29725. vertexData.indices = indices;
  29726. vertexData.positions = positions;
  29727. if (colors) {
  29728. vertexData.colors = vertexColors;
  29729. }
  29730. return vertexData;
  29731. };
  29732. /**
  29733. * Create the VertexData of the DashedLines.
  29734. */
  29735. VertexData.CreateDashedLines = function (options) {
  29736. var dashSize = options.dashSize || 3;
  29737. var gapSize = options.gapSize || 1;
  29738. var dashNb = options.dashNb || 200;
  29739. var points = options.points;
  29740. var positions = new Array();
  29741. var indices = new Array();
  29742. var curvect = BABYLON.Vector3.Zero();
  29743. var lg = 0;
  29744. var nb = 0;
  29745. var shft = 0;
  29746. var dashshft = 0;
  29747. var curshft = 0;
  29748. var idx = 0;
  29749. var i = 0;
  29750. for (i = 0; i < points.length - 1; i++) {
  29751. points[i + 1].subtractToRef(points[i], curvect);
  29752. lg += curvect.length();
  29753. }
  29754. shft = lg / dashNb;
  29755. dashshft = dashSize * shft / (dashSize + gapSize);
  29756. for (i = 0; i < points.length - 1; i++) {
  29757. points[i + 1].subtractToRef(points[i], curvect);
  29758. nb = Math.floor(curvect.length() / shft);
  29759. curvect.normalize();
  29760. for (var j = 0; j < nb; j++) {
  29761. curshft = shft * j;
  29762. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29763. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29764. indices.push(idx, idx + 1);
  29765. idx += 2;
  29766. }
  29767. }
  29768. // Result
  29769. var vertexData = new VertexData();
  29770. vertexData.positions = positions;
  29771. vertexData.indices = indices;
  29772. return vertexData;
  29773. };
  29774. /**
  29775. * Creates the VertexData of the Ground.
  29776. */
  29777. VertexData.CreateGround = function (options) {
  29778. var indices = [];
  29779. var positions = [];
  29780. var normals = [];
  29781. var uvs = [];
  29782. var row, col;
  29783. var width = options.width || 1;
  29784. var height = options.height || 1;
  29785. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29786. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29787. for (row = 0; row <= subdivisionsY; row++) {
  29788. for (col = 0; col <= subdivisionsX; col++) {
  29789. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29790. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29791. positions.push(position.x, position.y, position.z);
  29792. normals.push(normal.x, normal.y, normal.z);
  29793. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29794. }
  29795. }
  29796. for (row = 0; row < subdivisionsY; row++) {
  29797. for (col = 0; col < subdivisionsX; col++) {
  29798. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29799. indices.push(col + 1 + row * (subdivisionsX + 1));
  29800. indices.push(col + row * (subdivisionsX + 1));
  29801. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29802. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29803. indices.push(col + row * (subdivisionsX + 1));
  29804. }
  29805. }
  29806. // Result
  29807. var vertexData = new VertexData();
  29808. vertexData.indices = indices;
  29809. vertexData.positions = positions;
  29810. vertexData.normals = normals;
  29811. vertexData.uvs = uvs;
  29812. return vertexData;
  29813. };
  29814. /**
  29815. * Creates the VertexData of the TiledGround.
  29816. */
  29817. VertexData.CreateTiledGround = function (options) {
  29818. var xmin = options.xmin || -1.0;
  29819. var zmin = options.zmin || -1.0;
  29820. var xmax = options.xmax || 1.0;
  29821. var zmax = options.zmax || 1.0;
  29822. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29823. var precision = options.precision || { w: 1, h: 1 };
  29824. var indices = new Array();
  29825. var positions = new Array();
  29826. var normals = new Array();
  29827. var uvs = new Array();
  29828. var row, col, tileRow, tileCol;
  29829. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29830. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29831. precision.w = (precision.w < 1) ? 1 : precision.w;
  29832. precision.h = (precision.h < 1) ? 1 : precision.h;
  29833. var tileSize = {
  29834. 'w': (xmax - xmin) / subdivisions.w,
  29835. 'h': (zmax - zmin) / subdivisions.h
  29836. };
  29837. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29838. // Indices
  29839. var base = positions.length / 3;
  29840. var rowLength = precision.w + 1;
  29841. for (row = 0; row < precision.h; row++) {
  29842. for (col = 0; col < precision.w; col++) {
  29843. var square = [
  29844. base + col + row * rowLength,
  29845. base + (col + 1) + row * rowLength,
  29846. base + (col + 1) + (row + 1) * rowLength,
  29847. base + col + (row + 1) * rowLength
  29848. ];
  29849. indices.push(square[1]);
  29850. indices.push(square[2]);
  29851. indices.push(square[3]);
  29852. indices.push(square[0]);
  29853. indices.push(square[1]);
  29854. indices.push(square[3]);
  29855. }
  29856. }
  29857. // Position, normals and uvs
  29858. var position = BABYLON.Vector3.Zero();
  29859. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29860. for (row = 0; row <= precision.h; row++) {
  29861. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29862. for (col = 0; col <= precision.w; col++) {
  29863. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29864. position.y = 0;
  29865. positions.push(position.x, position.y, position.z);
  29866. normals.push(normal.x, normal.y, normal.z);
  29867. uvs.push(col / precision.w, row / precision.h);
  29868. }
  29869. }
  29870. }
  29871. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29872. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29873. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29874. }
  29875. }
  29876. // Result
  29877. var vertexData = new VertexData();
  29878. vertexData.indices = indices;
  29879. vertexData.positions = positions;
  29880. vertexData.normals = normals;
  29881. vertexData.uvs = uvs;
  29882. return vertexData;
  29883. };
  29884. /**
  29885. * Creates the VertexData of the Ground designed from a heightmap.
  29886. */
  29887. VertexData.CreateGroundFromHeightMap = function (options) {
  29888. var indices = [];
  29889. var positions = [];
  29890. var normals = [];
  29891. var uvs = [];
  29892. var row, col;
  29893. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29894. // Vertices
  29895. for (row = 0; row <= options.subdivisions; row++) {
  29896. for (col = 0; col <= options.subdivisions; col++) {
  29897. 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));
  29898. // Compute height
  29899. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29900. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29901. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29902. var r = options.buffer[pos] / 255.0;
  29903. var g = options.buffer[pos + 1] / 255.0;
  29904. var b = options.buffer[pos + 2] / 255.0;
  29905. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29906. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29907. // Add vertex
  29908. positions.push(position.x, position.y, position.z);
  29909. normals.push(0, 0, 0);
  29910. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29911. }
  29912. }
  29913. // Indices
  29914. for (row = 0; row < options.subdivisions; row++) {
  29915. for (col = 0; col < options.subdivisions; col++) {
  29916. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29917. indices.push(col + 1 + row * (options.subdivisions + 1));
  29918. indices.push(col + row * (options.subdivisions + 1));
  29919. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29920. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29921. indices.push(col + row * (options.subdivisions + 1));
  29922. }
  29923. }
  29924. // Normals
  29925. VertexData.ComputeNormals(positions, indices, normals);
  29926. // Result
  29927. var vertexData = new VertexData();
  29928. vertexData.indices = indices;
  29929. vertexData.positions = positions;
  29930. vertexData.normals = normals;
  29931. vertexData.uvs = uvs;
  29932. return vertexData;
  29933. };
  29934. /**
  29935. * Creates the VertexData of the Plane.
  29936. */
  29937. VertexData.CreatePlane = function (options) {
  29938. var indices = [];
  29939. var positions = [];
  29940. var normals = [];
  29941. var uvs = [];
  29942. var width = options.width || options.size || 1;
  29943. var height = options.height || options.size || 1;
  29944. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29945. // Vertices
  29946. var halfWidth = width / 2.0;
  29947. var halfHeight = height / 2.0;
  29948. positions.push(-halfWidth, -halfHeight, 0);
  29949. normals.push(0, 0, -1.0);
  29950. uvs.push(0.0, 0.0);
  29951. positions.push(halfWidth, -halfHeight, 0);
  29952. normals.push(0, 0, -1.0);
  29953. uvs.push(1.0, 0.0);
  29954. positions.push(halfWidth, halfHeight, 0);
  29955. normals.push(0, 0, -1.0);
  29956. uvs.push(1.0, 1.0);
  29957. positions.push(-halfWidth, halfHeight, 0);
  29958. normals.push(0, 0, -1.0);
  29959. uvs.push(0.0, 1.0);
  29960. // Indices
  29961. indices.push(0);
  29962. indices.push(1);
  29963. indices.push(2);
  29964. indices.push(0);
  29965. indices.push(2);
  29966. indices.push(3);
  29967. // Sides
  29968. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29969. // Result
  29970. var vertexData = new VertexData();
  29971. vertexData.indices = indices;
  29972. vertexData.positions = positions;
  29973. vertexData.normals = normals;
  29974. vertexData.uvs = uvs;
  29975. return vertexData;
  29976. };
  29977. /**
  29978. * Creates the VertexData of the Disc or regular Polygon.
  29979. */
  29980. VertexData.CreateDisc = function (options) {
  29981. var positions = new Array();
  29982. var indices = new Array();
  29983. var normals = new Array();
  29984. var uvs = new Array();
  29985. var radius = options.radius || 0.5;
  29986. var tessellation = options.tessellation || 64;
  29987. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29988. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29989. // positions and uvs
  29990. positions.push(0, 0, 0); // disc center first
  29991. uvs.push(0.5, 0.5);
  29992. var theta = Math.PI * 2 * arc;
  29993. var step = theta / tessellation;
  29994. for (var a = 0; a < theta; a += step) {
  29995. var x = Math.cos(a);
  29996. var y = Math.sin(a);
  29997. var u = (x + 1) / 2;
  29998. var v = (1 - y) / 2;
  29999. positions.push(radius * x, radius * y, 0);
  30000. uvs.push(u, v);
  30001. }
  30002. if (arc === 1) {
  30003. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30004. uvs.push(uvs[2], uvs[3]);
  30005. }
  30006. //indices
  30007. var vertexNb = positions.length / 3;
  30008. for (var i = 1; i < vertexNb - 1; i++) {
  30009. indices.push(i + 1, 0, i);
  30010. }
  30011. // result
  30012. VertexData.ComputeNormals(positions, indices, normals);
  30013. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30014. var vertexData = new VertexData();
  30015. vertexData.indices = indices;
  30016. vertexData.positions = positions;
  30017. vertexData.normals = normals;
  30018. vertexData.uvs = uvs;
  30019. return vertexData;
  30020. };
  30021. /**
  30022. * Re-creates the VertexData of the Polygon for sideOrientation.
  30023. */
  30024. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30025. var faceUV = fUV || new Array(3);
  30026. var faceColors = fColors;
  30027. var colors = [];
  30028. // default face colors and UV if undefined
  30029. for (var f = 0; f < 3; f++) {
  30030. if (faceUV[f] === undefined) {
  30031. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30032. }
  30033. if (faceColors && faceColors[f] === undefined) {
  30034. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30035. }
  30036. }
  30037. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30038. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30039. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30040. var indices = polygon.getIndices();
  30041. // set face colours and textures
  30042. var idx = 0;
  30043. var face = 0;
  30044. for (var index = 0; index < normals.length; index += 3) {
  30045. //Edge Face no. 1
  30046. if (Math.abs(normals[index + 1]) < 0.001) {
  30047. face = 1;
  30048. }
  30049. //Top Face no. 0
  30050. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30051. face = 0;
  30052. }
  30053. //Bottom Face no. 2
  30054. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30055. face = 2;
  30056. }
  30057. idx = index / 3;
  30058. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30059. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30060. if (faceColors) {
  30061. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30062. }
  30063. }
  30064. // sides
  30065. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30066. // Result
  30067. var vertexData = new VertexData();
  30068. vertexData.indices = indices;
  30069. vertexData.positions = positions;
  30070. vertexData.normals = normals;
  30071. vertexData.uvs = uvs;
  30072. if (faceColors) {
  30073. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30074. vertexData.colors = totalColors;
  30075. }
  30076. return vertexData;
  30077. };
  30078. /**
  30079. * Creates the VertexData of the IcoSphere.
  30080. */
  30081. VertexData.CreateIcoSphere = function (options) {
  30082. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30083. var radius = options.radius || 1;
  30084. var flat = (options.flat === undefined) ? true : options.flat;
  30085. var subdivisions = options.subdivisions || 4;
  30086. var radiusX = options.radiusX || radius;
  30087. var radiusY = options.radiusY || radius;
  30088. var radiusZ = options.radiusZ || radius;
  30089. var t = (1 + Math.sqrt(5)) / 2;
  30090. // 12 vertex x,y,z
  30091. var ico_vertices = [
  30092. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30093. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30094. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30095. ];
  30096. // index of 3 vertex makes a face of icopshere
  30097. var ico_indices = [
  30098. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30099. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30100. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30101. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30102. ];
  30103. // vertex for uv have aliased position, not for UV
  30104. var vertices_unalias_id = [
  30105. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30106. // vertex alias
  30107. 0,
  30108. 2,
  30109. 3,
  30110. 3,
  30111. 3,
  30112. 4,
  30113. 7,
  30114. 8,
  30115. 9,
  30116. 9,
  30117. 10,
  30118. 11 // 23: B + 12
  30119. ];
  30120. // uv as integer step (not pixels !)
  30121. var ico_vertexuv = [
  30122. 5, 1, 3, 1, 6, 4, 0, 0,
  30123. 5, 3, 4, 2, 2, 2, 4, 0,
  30124. 2, 0, 1, 1, 6, 0, 6, 2,
  30125. // vertex alias (for same vertex on different faces)
  30126. 0, 4,
  30127. 3, 3,
  30128. 4, 4,
  30129. 3, 1,
  30130. 4, 2,
  30131. 4, 4,
  30132. 0, 2,
  30133. 1, 1,
  30134. 2, 2,
  30135. 3, 3,
  30136. 1, 3,
  30137. 2, 4 // 23: B + 12
  30138. ];
  30139. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30140. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30141. // First island of uv mapping
  30142. // v = 4h 3+ 2
  30143. // v = 3h 9+ 4
  30144. // v = 2h 9+ 5 B
  30145. // v = 1h 9 1 0
  30146. // v = 0h 3 8 7 A
  30147. // u = 0 1 2 3 4 5 6 *a
  30148. // Second island of uv mapping
  30149. // v = 4h 0+ B+ 4+
  30150. // v = 3h A+ 2+
  30151. // v = 2h 7+ 6 3+
  30152. // v = 1h 8+ 3+
  30153. // v = 0h
  30154. // u = 0 1 2 3 4 5 6 *a
  30155. // Face layout on texture UV mapping
  30156. // ============
  30157. // \ 4 /\ 16 / ======
  30158. // \ / \ / /\ 11 /
  30159. // \/ 7 \/ / \ /
  30160. // ======= / 10 \/
  30161. // /\ 17 /\ =======
  30162. // / \ / \ \ 15 /\
  30163. // / 8 \/ 12 \ \ / \
  30164. // ============ \/ 6 \
  30165. // \ 18 /\ ============
  30166. // \ / \ \ 5 /\ 0 /
  30167. // \/ 13 \ \ / \ /
  30168. // ======= \/ 1 \/
  30169. // =============
  30170. // /\ 19 /\ 2 /\
  30171. // / \ / \ / \
  30172. // / 14 \/ 9 \/ 3 \
  30173. // ===================
  30174. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30175. var ustep = 138 / 1024;
  30176. var vstep = 239 / 1024;
  30177. var uoffset = 60 / 1024;
  30178. var voffset = 26 / 1024;
  30179. // Second island should have margin, not to touch the first island
  30180. // avoid any borderline artefact in pixel rounding
  30181. var island_u_offset = -40 / 1024;
  30182. var island_v_offset = +20 / 1024;
  30183. // face is either island 0 or 1 :
  30184. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30185. var island = [
  30186. 0, 0, 0, 0, 1,
  30187. 0, 0, 1, 1, 0,
  30188. 0, 0, 1, 1, 0,
  30189. 0, 1, 1, 1, 0 // 15 - 19
  30190. ];
  30191. var indices = new Array();
  30192. var positions = new Array();
  30193. var normals = new Array();
  30194. var uvs = new Array();
  30195. var current_indice = 0;
  30196. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30197. var face_vertex_pos = new Array(3);
  30198. var face_vertex_uv = new Array(3);
  30199. var v012;
  30200. for (v012 = 0; v012 < 3; v012++) {
  30201. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30202. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30203. }
  30204. // create all with normals
  30205. for (var face = 0; face < 20; face++) {
  30206. // 3 vertex per face
  30207. for (v012 = 0; v012 < 3; v012++) {
  30208. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30209. var v_id = ico_indices[3 * face + v012];
  30210. // vertex have 3D position (x,y,z)
  30211. 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]);
  30212. // Normalize to get normal, then scale to radius
  30213. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30214. // uv Coordinates from vertex ID
  30215. 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);
  30216. }
  30217. // Subdivide the face (interpolate pos, norm, uv)
  30218. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30219. // - norm is linear interpolation of vertex corner normal
  30220. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30221. // - uv is linear interpolation
  30222. //
  30223. // Topology is as below for sub-divide by 2
  30224. // vertex shown as v0,v1,v2
  30225. // interp index is i1 to progress in range [v0,v1[
  30226. // interp index is i2 to progress in range [v0,v2[
  30227. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30228. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30229. //
  30230. //
  30231. // i2 v2
  30232. // ^ ^
  30233. // / / \
  30234. // / / \
  30235. // / / \
  30236. // / / (0,1) \
  30237. // / #---------\
  30238. // / / \ (0,0)'/ \
  30239. // / / \ / \
  30240. // / / \ / \
  30241. // / / (0,0) \ / (1,0) \
  30242. // / #---------#---------\
  30243. // v0 v1
  30244. //
  30245. // --------------------> i1
  30246. //
  30247. // interp of (i1,i2):
  30248. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30249. // along i1 : lerp(x0,x1, i1/(S-i2))
  30250. //
  30251. // centroid of triangle is needed to get help normal computation
  30252. // (c1,c2) are used for centroid location
  30253. var interp_vertex = function (i1, i2, c1, c2) {
  30254. // vertex is interpolated from
  30255. // - face_vertex_pos[0..2]
  30256. // - face_vertex_uv[0..2]
  30257. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30258. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30259. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30260. pos_interp.normalize();
  30261. var vertex_normal;
  30262. if (flat) {
  30263. // in flat mode, recalculate normal as face centroid normal
  30264. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30265. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30266. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30267. }
  30268. else {
  30269. // in smooth mode, recalculate normal from each single vertex position
  30270. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30271. }
  30272. // Vertex normal need correction due to X,Y,Z radius scaling
  30273. vertex_normal.x /= radiusX;
  30274. vertex_normal.y /= radiusY;
  30275. vertex_normal.z /= radiusZ;
  30276. vertex_normal.normalize();
  30277. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30278. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30279. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30280. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30281. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30282. uvs.push(uv_interp.x, uv_interp.y);
  30283. // push each vertex has member of a face
  30284. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30285. indices.push(current_indice);
  30286. current_indice++;
  30287. };
  30288. for (var i2 = 0; i2 < subdivisions; i2++) {
  30289. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30290. // face : (i1,i2) for /\ :
  30291. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30292. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30293. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30294. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30295. if (i1 + i2 + 1 < subdivisions) {
  30296. // face : (i1,i2)' for \/ :
  30297. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30298. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30299. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30300. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30301. }
  30302. }
  30303. }
  30304. }
  30305. // Sides
  30306. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30307. // Result
  30308. var vertexData = new VertexData();
  30309. vertexData.indices = indices;
  30310. vertexData.positions = positions;
  30311. vertexData.normals = normals;
  30312. vertexData.uvs = uvs;
  30313. return vertexData;
  30314. };
  30315. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30316. /**
  30317. * Creates the VertexData of the Polyhedron.
  30318. */
  30319. VertexData.CreatePolyhedron = function (options) {
  30320. // provided polyhedron types :
  30321. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30322. // 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)
  30323. var polyhedra = [];
  30324. 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]] };
  30325. 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]] };
  30326. polyhedra[2] = {
  30327. 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]],
  30328. 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]]
  30329. };
  30330. polyhedra[3] = {
  30331. 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]],
  30332. 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]]
  30333. };
  30334. polyhedra[4] = {
  30335. 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]],
  30336. 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]]
  30337. };
  30338. 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]] };
  30339. 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]] };
  30340. 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]] };
  30341. 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]] };
  30342. 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]] };
  30343. 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]] };
  30344. 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]] };
  30345. 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]] };
  30346. 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]] };
  30347. polyhedra[14] = {
  30348. 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]],
  30349. 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]]
  30350. };
  30351. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30352. var size = options.size;
  30353. var sizeX = options.sizeX || size || 1;
  30354. var sizeY = options.sizeY || size || 1;
  30355. var sizeZ = options.sizeZ || size || 1;
  30356. var data = options.custom || polyhedra[type];
  30357. var nbfaces = data.face.length;
  30358. var faceUV = options.faceUV || new Array(nbfaces);
  30359. var faceColors = options.faceColors;
  30360. var flat = (options.flat === undefined) ? true : options.flat;
  30361. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30362. var positions = new Array();
  30363. var indices = new Array();
  30364. var normals = new Array();
  30365. var uvs = new Array();
  30366. var colors = new Array();
  30367. var index = 0;
  30368. var faceIdx = 0; // face cursor in the array "indexes"
  30369. var indexes = new Array();
  30370. var i = 0;
  30371. var f = 0;
  30372. var u, v, ang, x, y, tmp;
  30373. // default face colors and UV if undefined
  30374. if (flat) {
  30375. for (f = 0; f < nbfaces; f++) {
  30376. if (faceColors && faceColors[f] === undefined) {
  30377. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30378. }
  30379. if (faceUV && faceUV[f] === undefined) {
  30380. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30381. }
  30382. }
  30383. }
  30384. if (!flat) {
  30385. for (i = 0; i < data.vertex.length; i++) {
  30386. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30387. uvs.push(0, 0);
  30388. }
  30389. for (f = 0; f < nbfaces; f++) {
  30390. for (i = 0; i < data.face[f].length - 2; i++) {
  30391. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30392. }
  30393. }
  30394. }
  30395. else {
  30396. for (f = 0; f < nbfaces; f++) {
  30397. var fl = data.face[f].length; // number of vertices of the current face
  30398. ang = 2 * Math.PI / fl;
  30399. x = 0.5 * Math.tan(ang / 2);
  30400. y = 0.5;
  30401. // positions, uvs, colors
  30402. for (i = 0; i < fl; i++) {
  30403. // positions
  30404. 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);
  30405. indexes.push(index);
  30406. index++;
  30407. // uvs
  30408. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30409. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30410. uvs.push(u, v);
  30411. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30412. y = x * Math.sin(ang) + y * Math.cos(ang);
  30413. x = tmp;
  30414. // colors
  30415. if (faceColors) {
  30416. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30417. }
  30418. }
  30419. // indices from indexes
  30420. for (i = 0; i < fl - 2; i++) {
  30421. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30422. }
  30423. faceIdx += fl;
  30424. }
  30425. }
  30426. VertexData.ComputeNormals(positions, indices, normals);
  30427. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30428. var vertexData = new VertexData();
  30429. vertexData.positions = positions;
  30430. vertexData.indices = indices;
  30431. vertexData.normals = normals;
  30432. vertexData.uvs = uvs;
  30433. if (faceColors && flat) {
  30434. vertexData.colors = colors;
  30435. }
  30436. return vertexData;
  30437. };
  30438. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30439. /**
  30440. * Creates the VertexData of the Torus Knot.
  30441. */
  30442. VertexData.CreateTorusKnot = function (options) {
  30443. var indices = new Array();
  30444. var positions = new Array();
  30445. var normals = new Array();
  30446. var uvs = new Array();
  30447. var radius = options.radius || 2;
  30448. var tube = options.tube || 0.5;
  30449. var radialSegments = options.radialSegments || 32;
  30450. var tubularSegments = options.tubularSegments || 32;
  30451. var p = options.p || 2;
  30452. var q = options.q || 3;
  30453. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30454. // Helper
  30455. var getPos = function (angle) {
  30456. var cu = Math.cos(angle);
  30457. var su = Math.sin(angle);
  30458. var quOverP = q / p * angle;
  30459. var cs = Math.cos(quOverP);
  30460. var tx = radius * (2 + cs) * 0.5 * cu;
  30461. var ty = radius * (2 + cs) * su * 0.5;
  30462. var tz = radius * Math.sin(quOverP) * 0.5;
  30463. return new BABYLON.Vector3(tx, ty, tz);
  30464. };
  30465. // Vertices
  30466. var i;
  30467. var j;
  30468. for (i = 0; i <= radialSegments; i++) {
  30469. var modI = i % radialSegments;
  30470. var u = modI / radialSegments * 2 * p * Math.PI;
  30471. var p1 = getPos(u);
  30472. var p2 = getPos(u + 0.01);
  30473. var tang = p2.subtract(p1);
  30474. var n = p2.add(p1);
  30475. var bitan = BABYLON.Vector3.Cross(tang, n);
  30476. n = BABYLON.Vector3.Cross(bitan, tang);
  30477. bitan.normalize();
  30478. n.normalize();
  30479. for (j = 0; j < tubularSegments; j++) {
  30480. var modJ = j % tubularSegments;
  30481. var v = modJ / tubularSegments * 2 * Math.PI;
  30482. var cx = -tube * Math.cos(v);
  30483. var cy = tube * Math.sin(v);
  30484. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30485. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30486. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30487. uvs.push(i / radialSegments);
  30488. uvs.push(j / tubularSegments);
  30489. }
  30490. }
  30491. for (i = 0; i < radialSegments; i++) {
  30492. for (j = 0; j < tubularSegments; j++) {
  30493. var jNext = (j + 1) % tubularSegments;
  30494. var a = i * tubularSegments + j;
  30495. var b = (i + 1) * tubularSegments + j;
  30496. var c = (i + 1) * tubularSegments + jNext;
  30497. var d = i * tubularSegments + jNext;
  30498. indices.push(d);
  30499. indices.push(b);
  30500. indices.push(a);
  30501. indices.push(d);
  30502. indices.push(c);
  30503. indices.push(b);
  30504. }
  30505. }
  30506. // Normals
  30507. VertexData.ComputeNormals(positions, indices, normals);
  30508. // Sides
  30509. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30510. // Result
  30511. var vertexData = new VertexData();
  30512. vertexData.indices = indices;
  30513. vertexData.positions = positions;
  30514. vertexData.normals = normals;
  30515. vertexData.uvs = uvs;
  30516. return vertexData;
  30517. };
  30518. // Tools
  30519. /**
  30520. * @param {any} - positions (number[] or Float32Array)
  30521. * @param {any} - indices (number[] or Uint16Array)
  30522. * @param {any} - normals (number[] or Float32Array)
  30523. * options (optional) :
  30524. * facetPositions : optional array of facet positions (vector3)
  30525. * facetNormals : optional array of facet normals (vector3)
  30526. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30527. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30528. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30529. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30530. * bInfo : optional bounding info, required for facetPartitioning computation
  30531. * useRightHandedSystem: optional boolean to for right handed system computation
  30532. * depthSort : optional boolean to enable the facet depth sort computation
  30533. * distanceTo : optional Vector3 to compute the facet depth from this location
  30534. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  30535. */
  30536. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30537. // temporary scalar variables
  30538. var index = 0; // facet index
  30539. var p1p2x = 0.0; // p1p2 vector x coordinate
  30540. var p1p2y = 0.0; // p1p2 vector y coordinate
  30541. var p1p2z = 0.0; // p1p2 vector z coordinate
  30542. var p3p2x = 0.0; // p3p2 vector x coordinate
  30543. var p3p2y = 0.0; // p3p2 vector y coordinate
  30544. var p3p2z = 0.0; // p3p2 vector z coordinate
  30545. var faceNormalx = 0.0; // facet normal x coordinate
  30546. var faceNormaly = 0.0; // facet normal y coordinate
  30547. var faceNormalz = 0.0; // facet normal z coordinate
  30548. var length = 0.0; // facet normal length before normalization
  30549. var v1x = 0; // vector1 x index in the positions array
  30550. var v1y = 0; // vector1 y index in the positions array
  30551. var v1z = 0; // vector1 z index in the positions array
  30552. var v2x = 0; // vector2 x index in the positions array
  30553. var v2y = 0; // vector2 y index in the positions array
  30554. var v2z = 0; // vector2 z index in the positions array
  30555. var v3x = 0; // vector3 x index in the positions array
  30556. var v3y = 0; // vector3 y index in the positions array
  30557. var v3z = 0; // vector3 z index in the positions array
  30558. var computeFacetNormals = false;
  30559. var computeFacetPositions = false;
  30560. var computeFacetPartitioning = false;
  30561. var computeDepthSort = false;
  30562. var faceNormalSign = 1;
  30563. var ratio = 0;
  30564. var distanceTo = null;
  30565. if (options) {
  30566. computeFacetNormals = (options.facetNormals) ? true : false;
  30567. computeFacetPositions = (options.facetPositions) ? true : false;
  30568. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30569. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30570. ratio = options.ratio || 0;
  30571. computeDepthSort = (options.depthSort) ? true : false;
  30572. distanceTo = (options.distanceTo);
  30573. if (computeDepthSort) {
  30574. if (distanceTo === undefined) {
  30575. distanceTo = BABYLON.Vector3.Zero();
  30576. }
  30577. var depthSortedFacets = options.depthSortedFacets;
  30578. }
  30579. }
  30580. // facetPartitioning reinit if needed
  30581. var xSubRatio = 0;
  30582. var ySubRatio = 0;
  30583. var zSubRatio = 0;
  30584. var subSq = 0;
  30585. if (computeFacetPartitioning && options && options.bbSize) {
  30586. var ox = 0; // X partitioning index for facet position
  30587. var oy = 0; // Y partinioning index for facet position
  30588. var oz = 0; // Z partinioning index for facet position
  30589. var b1x = 0; // X partitioning index for facet v1 vertex
  30590. var b1y = 0; // Y partitioning index for facet v1 vertex
  30591. var b1z = 0; // z partitioning index for facet v1 vertex
  30592. var b2x = 0; // X partitioning index for facet v2 vertex
  30593. var b2y = 0; // Y partitioning index for facet v2 vertex
  30594. var b2z = 0; // Z partitioning index for facet v2 vertex
  30595. var b3x = 0; // X partitioning index for facet v3 vertex
  30596. var b3y = 0; // Y partitioning index for facet v3 vertex
  30597. var b3z = 0; // Z partitioning index for facet v3 vertex
  30598. var block_idx_o = 0; // facet barycenter block index
  30599. var block_idx_v1 = 0; // v1 vertex block index
  30600. var block_idx_v2 = 0; // v2 vertex block index
  30601. var block_idx_v3 = 0; // v3 vertex block index
  30602. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30603. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30604. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30605. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30606. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30607. subSq = options.subDiv.max * options.subDiv.max;
  30608. options.facetPartitioning.length = 0;
  30609. }
  30610. // reset the normals
  30611. for (index = 0; index < positions.length; index++) {
  30612. normals[index] = 0.0;
  30613. }
  30614. // Loop : 1 indice triplet = 1 facet
  30615. var nbFaces = (indices.length / 3) | 0;
  30616. for (index = 0; index < nbFaces; index++) {
  30617. // get the indexes of the coordinates of each vertex of the facet
  30618. v1x = indices[index * 3] * 3;
  30619. v1y = v1x + 1;
  30620. v1z = v1x + 2;
  30621. v2x = indices[index * 3 + 1] * 3;
  30622. v2y = v2x + 1;
  30623. v2z = v2x + 2;
  30624. v3x = indices[index * 3 + 2] * 3;
  30625. v3y = v3x + 1;
  30626. v3z = v3x + 2;
  30627. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30628. p1p2y = positions[v1y] - positions[v2y];
  30629. p1p2z = positions[v1z] - positions[v2z];
  30630. p3p2x = positions[v3x] - positions[v2x];
  30631. p3p2y = positions[v3y] - positions[v2y];
  30632. p3p2z = positions[v3z] - positions[v2z];
  30633. // compute the face normal with the cross product
  30634. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30635. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30636. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30637. // normalize this normal and store it in the array facetData
  30638. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30639. length = (length === 0) ? 1.0 : length;
  30640. faceNormalx /= length;
  30641. faceNormaly /= length;
  30642. faceNormalz /= length;
  30643. if (computeFacetNormals && options) {
  30644. options.facetNormals[index].x = faceNormalx;
  30645. options.facetNormals[index].y = faceNormaly;
  30646. options.facetNormals[index].z = faceNormalz;
  30647. }
  30648. if (computeFacetPositions && options) {
  30649. // compute and the facet barycenter coordinates in the array facetPositions
  30650. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30651. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30652. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30653. }
  30654. if (computeFacetPartitioning && options) {
  30655. // store the facet indexes in arrays in the main facetPartitioning array :
  30656. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30657. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30658. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30659. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30660. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30661. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30662. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30663. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30664. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30665. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30666. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30667. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30668. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30669. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30670. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30671. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30672. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30673. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30674. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30675. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30676. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30677. // push each facet index in each block containing the vertex
  30678. options.facetPartitioning[block_idx_v1].push(index);
  30679. if (block_idx_v2 != block_idx_v1) {
  30680. options.facetPartitioning[block_idx_v2].push(index);
  30681. }
  30682. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30683. options.facetPartitioning[block_idx_v3].push(index);
  30684. }
  30685. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30686. options.facetPartitioning[block_idx_o].push(index);
  30687. }
  30688. }
  30689. if (computeDepthSort && options && options.facetPositions) {
  30690. var dsf = depthSortedFacets[index];
  30691. dsf.ind = index * 3;
  30692. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  30693. }
  30694. // compute the normals anyway
  30695. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30696. normals[v1y] += faceNormaly;
  30697. normals[v1z] += faceNormalz;
  30698. normals[v2x] += faceNormalx;
  30699. normals[v2y] += faceNormaly;
  30700. normals[v2z] += faceNormalz;
  30701. normals[v3x] += faceNormalx;
  30702. normals[v3y] += faceNormaly;
  30703. normals[v3z] += faceNormalz;
  30704. }
  30705. // last normalization of each normal
  30706. for (index = 0; index < normals.length / 3; index++) {
  30707. faceNormalx = normals[index * 3];
  30708. faceNormaly = normals[index * 3 + 1];
  30709. faceNormalz = normals[index * 3 + 2];
  30710. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30711. length = (length === 0) ? 1.0 : length;
  30712. faceNormalx /= length;
  30713. faceNormaly /= length;
  30714. faceNormalz /= length;
  30715. normals[index * 3] = faceNormalx;
  30716. normals[index * 3 + 1] = faceNormaly;
  30717. normals[index * 3 + 2] = faceNormalz;
  30718. }
  30719. };
  30720. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30721. var li = indices.length;
  30722. var ln = normals.length;
  30723. var i;
  30724. var n;
  30725. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30726. switch (sideOrientation) {
  30727. case BABYLON.Mesh.FRONTSIDE:
  30728. // nothing changed
  30729. break;
  30730. case BABYLON.Mesh.BACKSIDE:
  30731. var tmp;
  30732. // indices
  30733. for (i = 0; i < li; i += 3) {
  30734. tmp = indices[i];
  30735. indices[i] = indices[i + 2];
  30736. indices[i + 2] = tmp;
  30737. }
  30738. // normals
  30739. for (n = 0; n < ln; n++) {
  30740. normals[n] = -normals[n];
  30741. }
  30742. break;
  30743. case BABYLON.Mesh.DOUBLESIDE:
  30744. // positions
  30745. var lp = positions.length;
  30746. var l = lp / 3;
  30747. for (var p = 0; p < lp; p++) {
  30748. positions[lp + p] = positions[p];
  30749. }
  30750. // indices
  30751. for (i = 0; i < li; i += 3) {
  30752. indices[i + li] = indices[i + 2] + l;
  30753. indices[i + 1 + li] = indices[i + 1] + l;
  30754. indices[i + 2 + li] = indices[i] + l;
  30755. }
  30756. // normals
  30757. for (n = 0; n < ln; n++) {
  30758. normals[ln + n] = -normals[n];
  30759. }
  30760. // uvs
  30761. var lu = uvs.length;
  30762. var u = 0;
  30763. for (u = 0; u < lu; u++) {
  30764. uvs[u + lu] = uvs[u];
  30765. }
  30766. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30767. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30768. u = 0;
  30769. for (i = 0; i < lu / 2; i++) {
  30770. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30771. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30772. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30773. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30774. u += 2;
  30775. }
  30776. break;
  30777. }
  30778. };
  30779. /**
  30780. * Creates a new VertexData from the imported parameters.
  30781. */
  30782. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30783. var vertexData = new VertexData();
  30784. // positions
  30785. var positions = parsedVertexData.positions;
  30786. if (positions) {
  30787. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30788. }
  30789. // normals
  30790. var normals = parsedVertexData.normals;
  30791. if (normals) {
  30792. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30793. }
  30794. // tangents
  30795. var tangents = parsedVertexData.tangents;
  30796. if (tangents) {
  30797. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30798. }
  30799. // uvs
  30800. var uvs = parsedVertexData.uvs;
  30801. if (uvs) {
  30802. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30803. }
  30804. // uv2s
  30805. var uv2s = parsedVertexData.uv2s;
  30806. if (uv2s) {
  30807. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30808. }
  30809. // uv3s
  30810. var uv3s = parsedVertexData.uv3s;
  30811. if (uv3s) {
  30812. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30813. }
  30814. // uv4s
  30815. var uv4s = parsedVertexData.uv4s;
  30816. if (uv4s) {
  30817. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30818. }
  30819. // uv5s
  30820. var uv5s = parsedVertexData.uv5s;
  30821. if (uv5s) {
  30822. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30823. }
  30824. // uv6s
  30825. var uv6s = parsedVertexData.uv6s;
  30826. if (uv6s) {
  30827. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30828. }
  30829. // colors
  30830. var colors = parsedVertexData.colors;
  30831. if (colors) {
  30832. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30833. }
  30834. // matricesIndices
  30835. var matricesIndices = parsedVertexData.matricesIndices;
  30836. if (matricesIndices) {
  30837. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30838. }
  30839. // matricesWeights
  30840. var matricesWeights = parsedVertexData.matricesWeights;
  30841. if (matricesWeights) {
  30842. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30843. }
  30844. // indices
  30845. var indices = parsedVertexData.indices;
  30846. if (indices) {
  30847. vertexData.indices = indices;
  30848. }
  30849. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30850. };
  30851. return VertexData;
  30852. }());
  30853. BABYLON.VertexData = VertexData;
  30854. })(BABYLON || (BABYLON = {}));
  30855. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30856. var BABYLON;
  30857. (function (BABYLON) {
  30858. var Geometry = /** @class */ (function () {
  30859. function Geometry(id, scene, vertexData, updatable, mesh) {
  30860. if (updatable === void 0) { updatable = false; }
  30861. if (mesh === void 0) { mesh = null; }
  30862. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30863. this._totalVertices = 0;
  30864. this._isDisposed = false;
  30865. this._indexBufferIsUpdatable = false;
  30866. this.id = id;
  30867. this._engine = scene.getEngine();
  30868. this._meshes = [];
  30869. this._scene = scene;
  30870. //Init vertex buffer cache
  30871. this._vertexBuffers = {};
  30872. this._indices = [];
  30873. this._updatable = updatable;
  30874. // vertexData
  30875. if (vertexData) {
  30876. this.setAllVerticesData(vertexData, updatable);
  30877. }
  30878. else {
  30879. this._totalVertices = 0;
  30880. this._indices = [];
  30881. }
  30882. if (this._engine.getCaps().vertexArrayObject) {
  30883. this._vertexArrayObjects = {};
  30884. }
  30885. // applyToMesh
  30886. if (mesh) {
  30887. if (mesh.getClassName() === "LinesMesh") {
  30888. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30889. this.updateExtend();
  30890. }
  30891. this.applyToMesh(mesh);
  30892. mesh.computeWorldMatrix(true);
  30893. }
  30894. }
  30895. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30896. /**
  30897. * 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
  30898. * @returns The Bias Vector
  30899. */
  30900. get: function () {
  30901. return this._boundingBias;
  30902. },
  30903. set: function (value) {
  30904. if (this._boundingBias && this._boundingBias.equals(value)) {
  30905. return;
  30906. }
  30907. this._boundingBias = value.clone();
  30908. this.updateBoundingInfo(true, null);
  30909. },
  30910. enumerable: true,
  30911. configurable: true
  30912. });
  30913. Geometry.CreateGeometryForMesh = function (mesh) {
  30914. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30915. geometry.applyToMesh(mesh);
  30916. return geometry;
  30917. };
  30918. Object.defineProperty(Geometry.prototype, "extend", {
  30919. get: function () {
  30920. return this._extend;
  30921. },
  30922. enumerable: true,
  30923. configurable: true
  30924. });
  30925. Geometry.prototype.getScene = function () {
  30926. return this._scene;
  30927. };
  30928. Geometry.prototype.getEngine = function () {
  30929. return this._engine;
  30930. };
  30931. Geometry.prototype.isReady = function () {
  30932. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30933. };
  30934. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30935. get: function () {
  30936. for (var index = 0; index < this._meshes.length; index++) {
  30937. if (!this._meshes[index].doNotSerialize) {
  30938. return false;
  30939. }
  30940. }
  30941. return true;
  30942. },
  30943. enumerable: true,
  30944. configurable: true
  30945. });
  30946. Geometry.prototype._rebuild = function () {
  30947. if (this._vertexArrayObjects) {
  30948. this._vertexArrayObjects = {};
  30949. }
  30950. // Index buffer
  30951. if (this._meshes.length !== 0 && this._indices) {
  30952. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30953. }
  30954. // Vertex buffers
  30955. for (var key in this._vertexBuffers) {
  30956. var vertexBuffer = this._vertexBuffers[key];
  30957. vertexBuffer._rebuild();
  30958. }
  30959. };
  30960. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30961. vertexData.applyToGeometry(this, updatable);
  30962. this.notifyUpdate();
  30963. };
  30964. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30965. if (updatable === void 0) { updatable = false; }
  30966. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30967. this.setVerticesBuffer(buffer);
  30968. };
  30969. Geometry.prototype.removeVerticesData = function (kind) {
  30970. if (this._vertexBuffers[kind]) {
  30971. this._vertexBuffers[kind].dispose();
  30972. delete this._vertexBuffers[kind];
  30973. }
  30974. };
  30975. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30976. var kind = buffer.getKind();
  30977. if (this._vertexBuffers[kind]) {
  30978. this._vertexBuffers[kind].dispose();
  30979. }
  30980. this._vertexBuffers[kind] = buffer;
  30981. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30982. var data = buffer.getData();
  30983. var stride = buffer.getStrideSize();
  30984. this._totalVertices = data.length / stride;
  30985. this.updateExtend(data, stride);
  30986. this._resetPointsArrayCache();
  30987. var meshes = this._meshes;
  30988. var numOfMeshes = meshes.length;
  30989. for (var index = 0; index < numOfMeshes; index++) {
  30990. var mesh = meshes[index];
  30991. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30992. mesh._createGlobalSubMesh(false);
  30993. mesh.computeWorldMatrix(true);
  30994. }
  30995. }
  30996. this.notifyUpdate(kind);
  30997. if (this._vertexArrayObjects) {
  30998. this._disposeVertexArrayObjects();
  30999. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31000. }
  31001. };
  31002. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31003. var vertexBuffer = this.getVertexBuffer(kind);
  31004. if (!vertexBuffer) {
  31005. return;
  31006. }
  31007. vertexBuffer.updateDirectly(data, offset);
  31008. this.notifyUpdate(kind);
  31009. };
  31010. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31011. if (updateExtends === void 0) { updateExtends = false; }
  31012. var vertexBuffer = this.getVertexBuffer(kind);
  31013. if (!vertexBuffer) {
  31014. return;
  31015. }
  31016. vertexBuffer.update(data);
  31017. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31018. var stride = vertexBuffer.getStrideSize();
  31019. this._totalVertices = data.length / stride;
  31020. this.updateBoundingInfo(updateExtends, data);
  31021. }
  31022. this.notifyUpdate(kind);
  31023. };
  31024. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31025. if (updateExtends) {
  31026. this.updateExtend(data);
  31027. }
  31028. var meshes = this._meshes;
  31029. var numOfMeshes = meshes.length;
  31030. this._resetPointsArrayCache();
  31031. for (var index = 0; index < numOfMeshes; index++) {
  31032. var mesh = meshes[index];
  31033. if (updateExtends) {
  31034. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31035. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31036. var subMesh = mesh.subMeshes[subIndex];
  31037. subMesh.refreshBoundingInfo();
  31038. }
  31039. }
  31040. }
  31041. };
  31042. Geometry.prototype._bind = function (effect, indexToBind) {
  31043. if (!effect) {
  31044. return;
  31045. }
  31046. if (indexToBind === undefined) {
  31047. indexToBind = this._indexBuffer;
  31048. }
  31049. var vbs = this.getVertexBuffers();
  31050. if (!vbs) {
  31051. return;
  31052. }
  31053. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31054. this._engine.bindBuffers(vbs, indexToBind, effect);
  31055. return;
  31056. }
  31057. // Using VAO
  31058. if (!this._vertexArrayObjects[effect.key]) {
  31059. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31060. }
  31061. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31062. };
  31063. Geometry.prototype.getTotalVertices = function () {
  31064. if (!this.isReady()) {
  31065. return 0;
  31066. }
  31067. return this._totalVertices;
  31068. };
  31069. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31070. var vertexBuffer = this.getVertexBuffer(kind);
  31071. if (!vertexBuffer) {
  31072. return null;
  31073. }
  31074. var orig = vertexBuffer.getData();
  31075. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31076. return orig;
  31077. }
  31078. else {
  31079. var len = orig.length;
  31080. var copy = [];
  31081. for (var i = 0; i < len; i++) {
  31082. copy.push(orig[i]);
  31083. }
  31084. return copy;
  31085. }
  31086. };
  31087. /**
  31088. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31089. * Possible `kind` values :
  31090. * - BABYLON.VertexBuffer.PositionKind
  31091. * - BABYLON.VertexBuffer.UVKind
  31092. * - BABYLON.VertexBuffer.UV2Kind
  31093. * - BABYLON.VertexBuffer.UV3Kind
  31094. * - BABYLON.VertexBuffer.UV4Kind
  31095. * - BABYLON.VertexBuffer.UV5Kind
  31096. * - BABYLON.VertexBuffer.UV6Kind
  31097. * - BABYLON.VertexBuffer.ColorKind
  31098. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31099. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31100. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31101. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31102. */
  31103. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31104. var vb = this._vertexBuffers[kind];
  31105. if (!vb) {
  31106. return false;
  31107. }
  31108. return vb.isUpdatable();
  31109. };
  31110. Geometry.prototype.getVertexBuffer = function (kind) {
  31111. if (!this.isReady()) {
  31112. return null;
  31113. }
  31114. return this._vertexBuffers[kind];
  31115. };
  31116. Geometry.prototype.getVertexBuffers = function () {
  31117. if (!this.isReady()) {
  31118. return null;
  31119. }
  31120. return this._vertexBuffers;
  31121. };
  31122. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31123. if (!this._vertexBuffers) {
  31124. if (this._delayInfo) {
  31125. return this._delayInfo.indexOf(kind) !== -1;
  31126. }
  31127. return false;
  31128. }
  31129. return this._vertexBuffers[kind] !== undefined;
  31130. };
  31131. Geometry.prototype.getVerticesDataKinds = function () {
  31132. var result = [];
  31133. var kind;
  31134. if (!this._vertexBuffers && this._delayInfo) {
  31135. for (kind in this._delayInfo) {
  31136. result.push(kind);
  31137. }
  31138. }
  31139. else {
  31140. for (kind in this._vertexBuffers) {
  31141. result.push(kind);
  31142. }
  31143. }
  31144. return result;
  31145. };
  31146. Geometry.prototype.updateIndices = function (indices, offset) {
  31147. if (!this._indexBuffer) {
  31148. return;
  31149. }
  31150. if (!this._indexBufferIsUpdatable) {
  31151. this.setIndices(indices, null, true);
  31152. }
  31153. else {
  31154. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31155. }
  31156. };
  31157. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31158. if (totalVertices === void 0) { totalVertices = null; }
  31159. if (updatable === void 0) { updatable = false; }
  31160. if (this._indexBuffer) {
  31161. this._engine._releaseBuffer(this._indexBuffer);
  31162. }
  31163. this._disposeVertexArrayObjects();
  31164. this._indices = indices;
  31165. this._indexBufferIsUpdatable = updatable;
  31166. if (this._meshes.length !== 0 && this._indices) {
  31167. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31168. }
  31169. if (totalVertices != undefined) {
  31170. this._totalVertices = totalVertices;
  31171. }
  31172. var meshes = this._meshes;
  31173. var numOfMeshes = meshes.length;
  31174. for (var index = 0; index < numOfMeshes; index++) {
  31175. meshes[index]._createGlobalSubMesh(true);
  31176. }
  31177. this.notifyUpdate();
  31178. };
  31179. Geometry.prototype.getTotalIndices = function () {
  31180. if (!this.isReady()) {
  31181. return 0;
  31182. }
  31183. return this._indices.length;
  31184. };
  31185. Geometry.prototype.getIndices = function (copyWhenShared) {
  31186. if (!this.isReady()) {
  31187. return null;
  31188. }
  31189. var orig = this._indices;
  31190. if (!copyWhenShared || this._meshes.length === 1) {
  31191. return orig;
  31192. }
  31193. else {
  31194. var len = orig.length;
  31195. var copy = [];
  31196. for (var i = 0; i < len; i++) {
  31197. copy.push(orig[i]);
  31198. }
  31199. return copy;
  31200. }
  31201. };
  31202. Geometry.prototype.getIndexBuffer = function () {
  31203. if (!this.isReady()) {
  31204. return null;
  31205. }
  31206. return this._indexBuffer;
  31207. };
  31208. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31209. if (effect === void 0) { effect = null; }
  31210. if (!effect || !this._vertexArrayObjects) {
  31211. return;
  31212. }
  31213. if (this._vertexArrayObjects[effect.key]) {
  31214. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31215. delete this._vertexArrayObjects[effect.key];
  31216. }
  31217. };
  31218. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31219. var meshes = this._meshes;
  31220. var index = meshes.indexOf(mesh);
  31221. if (index === -1) {
  31222. return;
  31223. }
  31224. meshes.splice(index, 1);
  31225. mesh._geometry = null;
  31226. if (meshes.length === 0 && shouldDispose) {
  31227. this.dispose();
  31228. }
  31229. };
  31230. Geometry.prototype.applyToMesh = function (mesh) {
  31231. if (mesh._geometry === this) {
  31232. return;
  31233. }
  31234. var previousGeometry = mesh._geometry;
  31235. if (previousGeometry) {
  31236. previousGeometry.releaseForMesh(mesh);
  31237. }
  31238. var meshes = this._meshes;
  31239. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31240. mesh._geometry = this;
  31241. this._scene.pushGeometry(this);
  31242. meshes.push(mesh);
  31243. if (this.isReady()) {
  31244. this._applyToMesh(mesh);
  31245. }
  31246. else {
  31247. mesh._boundingInfo = this._boundingInfo;
  31248. }
  31249. };
  31250. Geometry.prototype.updateExtend = function (data, stride) {
  31251. if (data === void 0) { data = null; }
  31252. if (!data) {
  31253. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31254. }
  31255. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31256. };
  31257. Geometry.prototype._applyToMesh = function (mesh) {
  31258. var numOfMeshes = this._meshes.length;
  31259. // vertexBuffers
  31260. for (var kind in this._vertexBuffers) {
  31261. if (numOfMeshes === 1) {
  31262. this._vertexBuffers[kind].create();
  31263. }
  31264. var buffer = this._vertexBuffers[kind].getBuffer();
  31265. if (buffer)
  31266. buffer.references = numOfMeshes;
  31267. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31268. if (!this._extend) {
  31269. this.updateExtend(this._vertexBuffers[kind].getData());
  31270. }
  31271. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31272. mesh._createGlobalSubMesh(false);
  31273. //bounding info was just created again, world matrix should be applied again.
  31274. mesh._updateBoundingInfo();
  31275. }
  31276. }
  31277. // indexBuffer
  31278. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31279. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31280. }
  31281. if (this._indexBuffer) {
  31282. this._indexBuffer.references = numOfMeshes;
  31283. }
  31284. };
  31285. Geometry.prototype.notifyUpdate = function (kind) {
  31286. if (this.onGeometryUpdated) {
  31287. this.onGeometryUpdated(this, kind);
  31288. }
  31289. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31290. var mesh = _a[_i];
  31291. mesh._markSubMeshesAsAttributesDirty();
  31292. }
  31293. };
  31294. Geometry.prototype.load = function (scene, onLoaded) {
  31295. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31296. return;
  31297. }
  31298. if (this.isReady()) {
  31299. if (onLoaded) {
  31300. onLoaded();
  31301. }
  31302. return;
  31303. }
  31304. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31305. this._queueLoad(scene, onLoaded);
  31306. };
  31307. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31308. var _this = this;
  31309. if (!this.delayLoadingFile) {
  31310. return;
  31311. }
  31312. scene._addPendingData(this);
  31313. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31314. if (!_this._delayLoadingFunction) {
  31315. return;
  31316. }
  31317. _this._delayLoadingFunction(JSON.parse(data), _this);
  31318. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31319. _this._delayInfo = [];
  31320. scene._removePendingData(_this);
  31321. var meshes = _this._meshes;
  31322. var numOfMeshes = meshes.length;
  31323. for (var index = 0; index < numOfMeshes; index++) {
  31324. _this._applyToMesh(meshes[index]);
  31325. }
  31326. if (onLoaded) {
  31327. onLoaded();
  31328. }
  31329. }, function () { }, scene.database);
  31330. };
  31331. /**
  31332. * Invert the geometry to move from a right handed system to a left handed one.
  31333. */
  31334. Geometry.prototype.toLeftHanded = function () {
  31335. // Flip faces
  31336. var tIndices = this.getIndices(false);
  31337. if (tIndices != null && tIndices.length > 0) {
  31338. for (var i = 0; i < tIndices.length; i += 3) {
  31339. var tTemp = tIndices[i + 0];
  31340. tIndices[i + 0] = tIndices[i + 2];
  31341. tIndices[i + 2] = tTemp;
  31342. }
  31343. this.setIndices(tIndices);
  31344. }
  31345. // Negate position.z
  31346. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  31347. if (tPositions != null && tPositions.length > 0) {
  31348. for (var i = 0; i < tPositions.length; i += 3) {
  31349. tPositions[i + 2] = -tPositions[i + 2];
  31350. }
  31351. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  31352. }
  31353. // Negate normal.z
  31354. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  31355. if (tNormals != null && tNormals.length > 0) {
  31356. for (var i = 0; i < tNormals.length; i += 3) {
  31357. tNormals[i + 2] = -tNormals[i + 2];
  31358. }
  31359. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  31360. }
  31361. };
  31362. // Cache
  31363. Geometry.prototype._resetPointsArrayCache = function () {
  31364. this._positions = null;
  31365. };
  31366. Geometry.prototype._generatePointsArray = function () {
  31367. if (this._positions)
  31368. return true;
  31369. this._positions = [];
  31370. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31371. if (!data) {
  31372. return false;
  31373. }
  31374. for (var index = 0; index < data.length; index += 3) {
  31375. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  31376. }
  31377. return true;
  31378. };
  31379. Geometry.prototype.isDisposed = function () {
  31380. return this._isDisposed;
  31381. };
  31382. Geometry.prototype._disposeVertexArrayObjects = function () {
  31383. if (this._vertexArrayObjects) {
  31384. for (var kind in this._vertexArrayObjects) {
  31385. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  31386. }
  31387. this._vertexArrayObjects = {};
  31388. }
  31389. };
  31390. Geometry.prototype.dispose = function () {
  31391. var meshes = this._meshes;
  31392. var numOfMeshes = meshes.length;
  31393. var index;
  31394. for (index = 0; index < numOfMeshes; index++) {
  31395. this.releaseForMesh(meshes[index]);
  31396. }
  31397. this._meshes = [];
  31398. this._disposeVertexArrayObjects();
  31399. for (var kind in this._vertexBuffers) {
  31400. this._vertexBuffers[kind].dispose();
  31401. }
  31402. this._vertexBuffers = {};
  31403. this._totalVertices = 0;
  31404. if (this._indexBuffer) {
  31405. this._engine._releaseBuffer(this._indexBuffer);
  31406. }
  31407. this._indexBuffer = null;
  31408. this._indices = [];
  31409. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31410. this.delayLoadingFile = null;
  31411. this._delayLoadingFunction = null;
  31412. this._delayInfo = [];
  31413. this._boundingInfo = null;
  31414. this._scene.removeGeometry(this);
  31415. this._isDisposed = true;
  31416. };
  31417. Geometry.prototype.copy = function (id) {
  31418. var vertexData = new BABYLON.VertexData();
  31419. vertexData.indices = [];
  31420. var indices = this.getIndices();
  31421. if (indices) {
  31422. for (var index = 0; index < indices.length; index++) {
  31423. vertexData.indices.push(indices[index]);
  31424. }
  31425. }
  31426. var updatable = false;
  31427. var stopChecking = false;
  31428. var kind;
  31429. for (kind in this._vertexBuffers) {
  31430. // using slice() to make a copy of the array and not just reference it
  31431. var data = this.getVerticesData(kind);
  31432. if (data instanceof Float32Array) {
  31433. vertexData.set(new Float32Array(data), kind);
  31434. }
  31435. else {
  31436. vertexData.set(data.slice(0), kind);
  31437. }
  31438. if (!stopChecking) {
  31439. var vb = this.getVertexBuffer(kind);
  31440. if (vb) {
  31441. updatable = vb.isUpdatable();
  31442. stopChecking = !updatable;
  31443. }
  31444. }
  31445. }
  31446. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31447. geometry.delayLoadState = this.delayLoadState;
  31448. geometry.delayLoadingFile = this.delayLoadingFile;
  31449. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31450. for (kind in this._delayInfo) {
  31451. geometry._delayInfo = geometry._delayInfo || [];
  31452. geometry._delayInfo.push(kind);
  31453. }
  31454. // Bounding info
  31455. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31456. return geometry;
  31457. };
  31458. Geometry.prototype.serialize = function () {
  31459. var serializationObject = {};
  31460. serializationObject.id = this.id;
  31461. serializationObject.updatable = this._updatable;
  31462. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31463. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31464. }
  31465. return serializationObject;
  31466. };
  31467. Geometry.prototype.toNumberArray = function (origin) {
  31468. if (Array.isArray(origin)) {
  31469. return origin;
  31470. }
  31471. else {
  31472. return Array.prototype.slice.call(origin);
  31473. }
  31474. };
  31475. Geometry.prototype.serializeVerticeData = function () {
  31476. var serializationObject = this.serialize();
  31477. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31478. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31479. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31480. serializationObject.positions._updatable = true;
  31481. }
  31482. }
  31483. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31484. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31485. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31486. serializationObject.normals._updatable = true;
  31487. }
  31488. }
  31489. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31490. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31491. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31492. serializationObject.uvs._updatable = true;
  31493. }
  31494. }
  31495. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31496. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31497. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31498. serializationObject.uv2s._updatable = true;
  31499. }
  31500. }
  31501. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31502. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31503. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31504. serializationObject.uv3s._updatable = true;
  31505. }
  31506. }
  31507. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31508. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31509. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31510. serializationObject.uv4s._updatable = true;
  31511. }
  31512. }
  31513. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31514. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31515. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31516. serializationObject.uv5s._updatable = true;
  31517. }
  31518. }
  31519. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31520. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31521. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31522. serializationObject.uv6s._updatable = true;
  31523. }
  31524. }
  31525. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31526. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31527. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31528. serializationObject.colors._updatable = true;
  31529. }
  31530. }
  31531. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31532. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31533. serializationObject.matricesIndices._isExpanded = true;
  31534. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31535. serializationObject.matricesIndices._updatable = true;
  31536. }
  31537. }
  31538. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31539. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31540. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31541. serializationObject.matricesWeights._updatable = true;
  31542. }
  31543. }
  31544. serializationObject.indices = this.toNumberArray(this.getIndices());
  31545. return serializationObject;
  31546. };
  31547. // Statics
  31548. Geometry.ExtractFromMesh = function (mesh, id) {
  31549. var geometry = mesh._geometry;
  31550. if (!geometry) {
  31551. return null;
  31552. }
  31553. return geometry.copy(id);
  31554. };
  31555. /**
  31556. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31557. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31558. * Be aware Math.random() could cause collisions, but:
  31559. * "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"
  31560. */
  31561. Geometry.RandomId = function () {
  31562. return BABYLON.Tools.RandomId();
  31563. };
  31564. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31565. var scene = mesh.getScene();
  31566. // Geometry
  31567. var geometryId = parsedGeometry.geometryId;
  31568. if (geometryId) {
  31569. var geometry = scene.getGeometryByID(geometryId);
  31570. if (geometry) {
  31571. geometry.applyToMesh(mesh);
  31572. }
  31573. }
  31574. else if (parsedGeometry instanceof ArrayBuffer) {
  31575. var binaryInfo = mesh._binaryInfo;
  31576. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31577. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31578. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31579. }
  31580. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31581. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31582. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31583. }
  31584. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31585. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31586. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31587. }
  31588. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31589. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31590. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31591. }
  31592. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31593. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31594. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31595. }
  31596. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31597. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31598. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31599. }
  31600. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31601. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31602. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31603. }
  31604. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31605. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31606. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31607. }
  31608. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31609. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31610. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31611. }
  31612. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31613. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31614. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31615. }
  31616. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31617. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31618. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31619. }
  31620. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31621. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31622. mesh.setIndices(indicesData, null);
  31623. }
  31624. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31625. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31626. mesh.subMeshes = [];
  31627. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31628. var materialIndex = subMeshesData[(i * 5) + 0];
  31629. var verticesStart = subMeshesData[(i * 5) + 1];
  31630. var verticesCount = subMeshesData[(i * 5) + 2];
  31631. var indexStart = subMeshesData[(i * 5) + 3];
  31632. var indexCount = subMeshesData[(i * 5) + 4];
  31633. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31634. }
  31635. }
  31636. }
  31637. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31638. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31639. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31640. if (parsedGeometry.uvs) {
  31641. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31642. }
  31643. if (parsedGeometry.uvs2) {
  31644. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31645. }
  31646. if (parsedGeometry.uvs3) {
  31647. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31648. }
  31649. if (parsedGeometry.uvs4) {
  31650. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31651. }
  31652. if (parsedGeometry.uvs5) {
  31653. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31654. }
  31655. if (parsedGeometry.uvs6) {
  31656. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31657. }
  31658. if (parsedGeometry.colors) {
  31659. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31660. }
  31661. if (parsedGeometry.matricesIndices) {
  31662. if (!parsedGeometry.matricesIndices._isExpanded) {
  31663. var floatIndices = [];
  31664. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31665. var matricesIndex = parsedGeometry.matricesIndices[i];
  31666. floatIndices.push(matricesIndex & 0x000000FF);
  31667. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31668. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31669. floatIndices.push(matricesIndex >> 24);
  31670. }
  31671. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31672. }
  31673. else {
  31674. delete parsedGeometry.matricesIndices._isExpanded;
  31675. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31676. }
  31677. }
  31678. if (parsedGeometry.matricesIndicesExtra) {
  31679. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31680. var floatIndices = [];
  31681. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31682. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31683. floatIndices.push(matricesIndex & 0x000000FF);
  31684. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31685. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31686. floatIndices.push(matricesIndex >> 24);
  31687. }
  31688. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31689. }
  31690. else {
  31691. delete parsedGeometry.matricesIndices._isExpanded;
  31692. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31693. }
  31694. }
  31695. if (parsedGeometry.matricesWeights) {
  31696. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31697. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31698. }
  31699. if (parsedGeometry.matricesWeightsExtra) {
  31700. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31701. }
  31702. mesh.setIndices(parsedGeometry.indices, null);
  31703. }
  31704. // SubMeshes
  31705. if (parsedGeometry.subMeshes) {
  31706. mesh.subMeshes = [];
  31707. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31708. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31709. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31710. }
  31711. }
  31712. // Flat shading
  31713. if (mesh._shouldGenerateFlatShading) {
  31714. mesh.convertToFlatShadedMesh();
  31715. delete mesh._shouldGenerateFlatShading;
  31716. }
  31717. // Update
  31718. mesh.computeWorldMatrix(true);
  31719. // Octree
  31720. if (scene['_selectionOctree']) {
  31721. scene['_selectionOctree'].addMesh(mesh);
  31722. }
  31723. };
  31724. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31725. var epsilon = 1e-3;
  31726. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31727. return;
  31728. }
  31729. var noInfluenceBoneIndex = 0.0;
  31730. if (parsedGeometry.skeletonId > -1) {
  31731. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31732. if (!skeleton) {
  31733. return;
  31734. }
  31735. noInfluenceBoneIndex = skeleton.bones.length;
  31736. }
  31737. else {
  31738. return;
  31739. }
  31740. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31741. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31742. var matricesWeights = parsedGeometry.matricesWeights;
  31743. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31744. var influencers = parsedGeometry.numBoneInfluencer;
  31745. var size = matricesWeights.length;
  31746. for (var i = 0; i < size; i += 4) {
  31747. var weight = 0.0;
  31748. var firstZeroWeight = -1;
  31749. for (var j = 0; j < 4; j++) {
  31750. var w = matricesWeights[i + j];
  31751. weight += w;
  31752. if (w < epsilon && firstZeroWeight < 0) {
  31753. firstZeroWeight = j;
  31754. }
  31755. }
  31756. if (matricesWeightsExtra) {
  31757. for (var j = 0; j < 4; j++) {
  31758. var w = matricesWeightsExtra[i + j];
  31759. weight += w;
  31760. if (w < epsilon && firstZeroWeight < 0) {
  31761. firstZeroWeight = j + 4;
  31762. }
  31763. }
  31764. }
  31765. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31766. firstZeroWeight = influencers - 1;
  31767. }
  31768. if (weight > epsilon) {
  31769. var mweight = 1.0 / weight;
  31770. for (var j = 0; j < 4; j++) {
  31771. matricesWeights[i + j] *= mweight;
  31772. }
  31773. if (matricesWeightsExtra) {
  31774. for (var j = 0; j < 4; j++) {
  31775. matricesWeightsExtra[i + j] *= mweight;
  31776. }
  31777. }
  31778. }
  31779. else {
  31780. if (firstZeroWeight >= 4) {
  31781. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31782. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31783. }
  31784. else {
  31785. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31786. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31787. }
  31788. }
  31789. }
  31790. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31791. if (parsedGeometry.matricesWeightsExtra) {
  31792. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31793. }
  31794. };
  31795. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31796. if (scene.getGeometryByID(parsedVertexData.id)) {
  31797. return null; // null since geometry could be something else than a box...
  31798. }
  31799. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31800. if (BABYLON.Tags) {
  31801. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31802. }
  31803. if (parsedVertexData.delayLoadingFile) {
  31804. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31805. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31806. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31807. geometry._delayInfo = [];
  31808. if (parsedVertexData.hasUVs) {
  31809. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31810. }
  31811. if (parsedVertexData.hasUVs2) {
  31812. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31813. }
  31814. if (parsedVertexData.hasUVs3) {
  31815. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31816. }
  31817. if (parsedVertexData.hasUVs4) {
  31818. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31819. }
  31820. if (parsedVertexData.hasUVs5) {
  31821. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31822. }
  31823. if (parsedVertexData.hasUVs6) {
  31824. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31825. }
  31826. if (parsedVertexData.hasColors) {
  31827. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31828. }
  31829. if (parsedVertexData.hasMatricesIndices) {
  31830. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31831. }
  31832. if (parsedVertexData.hasMatricesWeights) {
  31833. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31834. }
  31835. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31836. }
  31837. else {
  31838. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31839. }
  31840. scene.pushGeometry(geometry, true);
  31841. return geometry;
  31842. };
  31843. return Geometry;
  31844. }());
  31845. BABYLON.Geometry = Geometry;
  31846. /////// Primitives //////////////////////////////////////////////
  31847. (function (Geometry) {
  31848. var Primitives;
  31849. (function (Primitives) {
  31850. /// Abstract class
  31851. var _Primitive = /** @class */ (function (_super) {
  31852. __extends(_Primitive, _super);
  31853. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31854. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31855. if (mesh === void 0) { mesh = null; }
  31856. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31857. _this._canBeRegenerated = _canBeRegenerated;
  31858. _this._beingRegenerated = true;
  31859. _this.regenerate();
  31860. _this._beingRegenerated = false;
  31861. return _this;
  31862. }
  31863. _Primitive.prototype.canBeRegenerated = function () {
  31864. return this._canBeRegenerated;
  31865. };
  31866. _Primitive.prototype.regenerate = function () {
  31867. if (!this._canBeRegenerated) {
  31868. return;
  31869. }
  31870. this._beingRegenerated = true;
  31871. this.setAllVerticesData(this._regenerateVertexData(), false);
  31872. this._beingRegenerated = false;
  31873. };
  31874. _Primitive.prototype.asNewGeometry = function (id) {
  31875. return _super.prototype.copy.call(this, id);
  31876. };
  31877. // overrides
  31878. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31879. if (!this._beingRegenerated) {
  31880. return;
  31881. }
  31882. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31883. };
  31884. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31885. if (!this._beingRegenerated) {
  31886. return;
  31887. }
  31888. _super.prototype.setVerticesData.call(this, kind, data, false);
  31889. };
  31890. // to override
  31891. // protected
  31892. _Primitive.prototype._regenerateVertexData = function () {
  31893. throw new Error("Abstract method");
  31894. };
  31895. _Primitive.prototype.copy = function (id) {
  31896. throw new Error("Must be overriden in sub-classes.");
  31897. };
  31898. _Primitive.prototype.serialize = function () {
  31899. var serializationObject = _super.prototype.serialize.call(this);
  31900. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31901. return serializationObject;
  31902. };
  31903. return _Primitive;
  31904. }(Geometry));
  31905. Primitives._Primitive = _Primitive;
  31906. var Ribbon = /** @class */ (function (_super) {
  31907. __extends(Ribbon, _super);
  31908. // Members
  31909. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31910. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31911. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31912. _this.pathArray = pathArray;
  31913. _this.closeArray = closeArray;
  31914. _this.closePath = closePath;
  31915. _this.offset = offset;
  31916. _this.side = side;
  31917. return _this;
  31918. }
  31919. Ribbon.prototype._regenerateVertexData = function () {
  31920. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31921. };
  31922. Ribbon.prototype.copy = function (id) {
  31923. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31924. };
  31925. return Ribbon;
  31926. }(_Primitive));
  31927. Primitives.Ribbon = Ribbon;
  31928. var Box = /** @class */ (function (_super) {
  31929. __extends(Box, _super);
  31930. // Members
  31931. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31932. if (mesh === void 0) { mesh = null; }
  31933. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31934. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31935. _this.size = size;
  31936. _this.side = side;
  31937. return _this;
  31938. }
  31939. Box.prototype._regenerateVertexData = function () {
  31940. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31941. };
  31942. Box.prototype.copy = function (id) {
  31943. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31944. };
  31945. Box.prototype.serialize = function () {
  31946. var serializationObject = _super.prototype.serialize.call(this);
  31947. serializationObject.size = this.size;
  31948. return serializationObject;
  31949. };
  31950. Box.Parse = function (parsedBox, scene) {
  31951. if (scene.getGeometryByID(parsedBox.id)) {
  31952. return null; // null since geometry could be something else than a box...
  31953. }
  31954. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31955. if (BABYLON.Tags) {
  31956. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31957. }
  31958. scene.pushGeometry(box, true);
  31959. return box;
  31960. };
  31961. return Box;
  31962. }(_Primitive));
  31963. Primitives.Box = Box;
  31964. var Sphere = /** @class */ (function (_super) {
  31965. __extends(Sphere, _super);
  31966. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31967. if (mesh === void 0) { mesh = null; }
  31968. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31969. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31970. _this.segments = segments;
  31971. _this.diameter = diameter;
  31972. _this.side = side;
  31973. return _this;
  31974. }
  31975. Sphere.prototype._regenerateVertexData = function () {
  31976. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31977. };
  31978. Sphere.prototype.copy = function (id) {
  31979. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31980. };
  31981. Sphere.prototype.serialize = function () {
  31982. var serializationObject = _super.prototype.serialize.call(this);
  31983. serializationObject.segments = this.segments;
  31984. serializationObject.diameter = this.diameter;
  31985. return serializationObject;
  31986. };
  31987. Sphere.Parse = function (parsedSphere, scene) {
  31988. if (scene.getGeometryByID(parsedSphere.id)) {
  31989. return null; // null since geometry could be something else than a sphere...
  31990. }
  31991. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31992. if (BABYLON.Tags) {
  31993. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31994. }
  31995. scene.pushGeometry(sphere, true);
  31996. return sphere;
  31997. };
  31998. return Sphere;
  31999. }(_Primitive));
  32000. Primitives.Sphere = Sphere;
  32001. var Disc = /** @class */ (function (_super) {
  32002. __extends(Disc, _super);
  32003. // Members
  32004. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32005. if (mesh === void 0) { mesh = null; }
  32006. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32007. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32008. _this.radius = radius;
  32009. _this.tessellation = tessellation;
  32010. _this.side = side;
  32011. return _this;
  32012. }
  32013. Disc.prototype._regenerateVertexData = function () {
  32014. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32015. };
  32016. Disc.prototype.copy = function (id) {
  32017. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32018. };
  32019. return Disc;
  32020. }(_Primitive));
  32021. Primitives.Disc = Disc;
  32022. var Cylinder = /** @class */ (function (_super) {
  32023. __extends(Cylinder, _super);
  32024. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32025. if (subdivisions === void 0) { subdivisions = 1; }
  32026. if (mesh === void 0) { mesh = null; }
  32027. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32028. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32029. _this.height = height;
  32030. _this.diameterTop = diameterTop;
  32031. _this.diameterBottom = diameterBottom;
  32032. _this.tessellation = tessellation;
  32033. _this.subdivisions = subdivisions;
  32034. _this.side = side;
  32035. return _this;
  32036. }
  32037. Cylinder.prototype._regenerateVertexData = function () {
  32038. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32039. };
  32040. Cylinder.prototype.copy = function (id) {
  32041. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32042. };
  32043. Cylinder.prototype.serialize = function () {
  32044. var serializationObject = _super.prototype.serialize.call(this);
  32045. serializationObject.height = this.height;
  32046. serializationObject.diameterTop = this.diameterTop;
  32047. serializationObject.diameterBottom = this.diameterBottom;
  32048. serializationObject.tessellation = this.tessellation;
  32049. return serializationObject;
  32050. };
  32051. Cylinder.Parse = function (parsedCylinder, scene) {
  32052. if (scene.getGeometryByID(parsedCylinder.id)) {
  32053. return null; // null since geometry could be something else than a cylinder...
  32054. }
  32055. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32056. if (BABYLON.Tags) {
  32057. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32058. }
  32059. scene.pushGeometry(cylinder, true);
  32060. return cylinder;
  32061. };
  32062. return Cylinder;
  32063. }(_Primitive));
  32064. Primitives.Cylinder = Cylinder;
  32065. var Torus = /** @class */ (function (_super) {
  32066. __extends(Torus, _super);
  32067. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32068. if (mesh === void 0) { mesh = null; }
  32069. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32070. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32071. _this.diameter = diameter;
  32072. _this.thickness = thickness;
  32073. _this.tessellation = tessellation;
  32074. _this.side = side;
  32075. return _this;
  32076. }
  32077. Torus.prototype._regenerateVertexData = function () {
  32078. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32079. };
  32080. Torus.prototype.copy = function (id) {
  32081. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32082. };
  32083. Torus.prototype.serialize = function () {
  32084. var serializationObject = _super.prototype.serialize.call(this);
  32085. serializationObject.diameter = this.diameter;
  32086. serializationObject.thickness = this.thickness;
  32087. serializationObject.tessellation = this.tessellation;
  32088. return serializationObject;
  32089. };
  32090. Torus.Parse = function (parsedTorus, scene) {
  32091. if (scene.getGeometryByID(parsedTorus.id)) {
  32092. return null; // null since geometry could be something else than a torus...
  32093. }
  32094. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32095. if (BABYLON.Tags) {
  32096. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32097. }
  32098. scene.pushGeometry(torus, true);
  32099. return torus;
  32100. };
  32101. return Torus;
  32102. }(_Primitive));
  32103. Primitives.Torus = Torus;
  32104. var Ground = /** @class */ (function (_super) {
  32105. __extends(Ground, _super);
  32106. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32107. if (mesh === void 0) { mesh = null; }
  32108. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32109. _this.width = width;
  32110. _this.height = height;
  32111. _this.subdivisions = subdivisions;
  32112. return _this;
  32113. }
  32114. Ground.prototype._regenerateVertexData = function () {
  32115. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32116. };
  32117. Ground.prototype.copy = function (id) {
  32118. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32119. };
  32120. Ground.prototype.serialize = function () {
  32121. var serializationObject = _super.prototype.serialize.call(this);
  32122. serializationObject.width = this.width;
  32123. serializationObject.height = this.height;
  32124. serializationObject.subdivisions = this.subdivisions;
  32125. return serializationObject;
  32126. };
  32127. Ground.Parse = function (parsedGround, scene) {
  32128. if (scene.getGeometryByID(parsedGround.id)) {
  32129. return null; // null since geometry could be something else than a ground...
  32130. }
  32131. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32132. if (BABYLON.Tags) {
  32133. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32134. }
  32135. scene.pushGeometry(ground, true);
  32136. return ground;
  32137. };
  32138. return Ground;
  32139. }(_Primitive));
  32140. Primitives.Ground = Ground;
  32141. var TiledGround = /** @class */ (function (_super) {
  32142. __extends(TiledGround, _super);
  32143. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32144. if (mesh === void 0) { mesh = null; }
  32145. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32146. _this.xmin = xmin;
  32147. _this.zmin = zmin;
  32148. _this.xmax = xmax;
  32149. _this.zmax = zmax;
  32150. _this.subdivisions = subdivisions;
  32151. _this.precision = precision;
  32152. return _this;
  32153. }
  32154. TiledGround.prototype._regenerateVertexData = function () {
  32155. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32156. };
  32157. TiledGround.prototype.copy = function (id) {
  32158. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32159. };
  32160. return TiledGround;
  32161. }(_Primitive));
  32162. Primitives.TiledGround = TiledGround;
  32163. var Plane = /** @class */ (function (_super) {
  32164. __extends(Plane, _super);
  32165. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  32166. if (mesh === void 0) { mesh = null; }
  32167. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32168. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32169. _this.size = size;
  32170. _this.side = side;
  32171. return _this;
  32172. }
  32173. Plane.prototype._regenerateVertexData = function () {
  32174. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32175. };
  32176. Plane.prototype.copy = function (id) {
  32177. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32178. };
  32179. Plane.prototype.serialize = function () {
  32180. var serializationObject = _super.prototype.serialize.call(this);
  32181. serializationObject.size = this.size;
  32182. return serializationObject;
  32183. };
  32184. Plane.Parse = function (parsedPlane, scene) {
  32185. if (scene.getGeometryByID(parsedPlane.id)) {
  32186. return null; // null since geometry could be something else than a ground...
  32187. }
  32188. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32189. if (BABYLON.Tags) {
  32190. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32191. }
  32192. scene.pushGeometry(plane, true);
  32193. return plane;
  32194. };
  32195. return Plane;
  32196. }(_Primitive));
  32197. Primitives.Plane = Plane;
  32198. var TorusKnot = /** @class */ (function (_super) {
  32199. __extends(TorusKnot, _super);
  32200. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32201. if (mesh === void 0) { mesh = null; }
  32202. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32203. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32204. _this.radius = radius;
  32205. _this.tube = tube;
  32206. _this.radialSegments = radialSegments;
  32207. _this.tubularSegments = tubularSegments;
  32208. _this.p = p;
  32209. _this.q = q;
  32210. _this.side = side;
  32211. return _this;
  32212. }
  32213. TorusKnot.prototype._regenerateVertexData = function () {
  32214. 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 });
  32215. };
  32216. TorusKnot.prototype.copy = function (id) {
  32217. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32218. };
  32219. TorusKnot.prototype.serialize = function () {
  32220. var serializationObject = _super.prototype.serialize.call(this);
  32221. serializationObject.radius = this.radius;
  32222. serializationObject.tube = this.tube;
  32223. serializationObject.radialSegments = this.radialSegments;
  32224. serializationObject.tubularSegments = this.tubularSegments;
  32225. serializationObject.p = this.p;
  32226. serializationObject.q = this.q;
  32227. return serializationObject;
  32228. };
  32229. ;
  32230. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  32231. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32232. return null; // null since geometry could be something else than a ground...
  32233. }
  32234. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32235. if (BABYLON.Tags) {
  32236. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32237. }
  32238. scene.pushGeometry(torusKnot, true);
  32239. return torusKnot;
  32240. };
  32241. return TorusKnot;
  32242. }(_Primitive));
  32243. Primitives.TorusKnot = TorusKnot;
  32244. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  32245. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  32246. })(BABYLON || (BABYLON = {}));
  32247. //# sourceMappingURL=babylon.geometry.js.map
  32248. var BABYLON;
  32249. (function (BABYLON) {
  32250. var PostProcessManager = /** @class */ (function () {
  32251. function PostProcessManager(scene) {
  32252. this._vertexBuffers = {};
  32253. this._scene = scene;
  32254. }
  32255. PostProcessManager.prototype._prepareBuffers = function () {
  32256. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32257. return;
  32258. }
  32259. // VBO
  32260. var vertices = [];
  32261. vertices.push(1, 1);
  32262. vertices.push(-1, 1);
  32263. vertices.push(-1, -1);
  32264. vertices.push(1, -1);
  32265. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32266. this._buildIndexBuffer();
  32267. };
  32268. PostProcessManager.prototype._buildIndexBuffer = function () {
  32269. // Indices
  32270. var indices = [];
  32271. indices.push(0);
  32272. indices.push(1);
  32273. indices.push(2);
  32274. indices.push(0);
  32275. indices.push(2);
  32276. indices.push(3);
  32277. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32278. };
  32279. PostProcessManager.prototype._rebuild = function () {
  32280. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32281. if (!vb) {
  32282. return;
  32283. }
  32284. vb._rebuild();
  32285. this._buildIndexBuffer();
  32286. };
  32287. // Methods
  32288. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32289. if (sourceTexture === void 0) { sourceTexture = null; }
  32290. if (postProcesses === void 0) { postProcesses = null; }
  32291. var camera = this._scene.activeCamera;
  32292. if (!camera) {
  32293. return false;
  32294. }
  32295. var postProcesses = postProcesses || camera._postProcesses;
  32296. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32297. return false;
  32298. }
  32299. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32300. return true;
  32301. };
  32302. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32303. if (targetTexture === void 0) { targetTexture = null; }
  32304. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32305. if (!this._scene.activeCamera) {
  32306. return;
  32307. }
  32308. var engine = this._scene.getEngine();
  32309. for (var index = 0; index < postProcesses.length; index++) {
  32310. if (index < postProcesses.length - 1) {
  32311. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32312. }
  32313. else {
  32314. if (targetTexture) {
  32315. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32316. }
  32317. else {
  32318. engine.restoreDefaultFramebuffer();
  32319. }
  32320. }
  32321. var pp = postProcesses[index];
  32322. var effect = pp.apply();
  32323. if (effect) {
  32324. pp.onBeforeRenderObservable.notifyObservers(effect);
  32325. // VBOs
  32326. this._prepareBuffers();
  32327. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32328. // Draw order
  32329. engine.draw(true, 0, 6);
  32330. pp.onAfterRenderObservable.notifyObservers(effect);
  32331. }
  32332. }
  32333. // Restore depth buffer
  32334. engine.setDepthBuffer(true);
  32335. engine.setDepthWrite(true);
  32336. };
  32337. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  32338. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32339. var camera = this._scene.activeCamera;
  32340. if (!camera) {
  32341. return;
  32342. }
  32343. postProcesses = postProcesses || camera._postProcesses;
  32344. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32345. return;
  32346. }
  32347. var engine = this._scene.getEngine();
  32348. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32349. if (index < len - 1) {
  32350. postProcesses[index + 1].activate(camera, targetTexture);
  32351. }
  32352. else {
  32353. if (targetTexture) {
  32354. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  32355. }
  32356. else {
  32357. engine.restoreDefaultFramebuffer();
  32358. }
  32359. }
  32360. if (doNotPresent) {
  32361. break;
  32362. }
  32363. var pp = postProcesses[index];
  32364. var effect = pp.apply();
  32365. if (effect) {
  32366. pp.onBeforeRenderObservable.notifyObservers(effect);
  32367. // VBOs
  32368. this._prepareBuffers();
  32369. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32370. // Draw order
  32371. engine.draw(true, 0, 6);
  32372. pp.onAfterRenderObservable.notifyObservers(effect);
  32373. }
  32374. }
  32375. // Restore states
  32376. engine.setDepthBuffer(true);
  32377. engine.setDepthWrite(true);
  32378. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32379. };
  32380. PostProcessManager.prototype.dispose = function () {
  32381. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32382. if (buffer) {
  32383. buffer.dispose();
  32384. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32385. }
  32386. if (this._indexBuffer) {
  32387. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32388. this._indexBuffer = null;
  32389. }
  32390. };
  32391. return PostProcessManager;
  32392. }());
  32393. BABYLON.PostProcessManager = PostProcessManager;
  32394. })(BABYLON || (BABYLON = {}));
  32395. //# sourceMappingURL=babylon.postProcessManager.js.map
  32396. var BABYLON;
  32397. (function (BABYLON) {
  32398. /**
  32399. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  32400. */
  32401. var PerformanceMonitor = /** @class */ (function () {
  32402. /**
  32403. * constructor
  32404. * @param frameSampleSize The number of samples required to saturate the sliding window
  32405. */
  32406. function PerformanceMonitor(frameSampleSize) {
  32407. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  32408. this._enabled = true;
  32409. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  32410. }
  32411. /**
  32412. * Samples current frame
  32413. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  32414. */
  32415. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  32416. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  32417. if (!this._enabled)
  32418. return;
  32419. if (this._lastFrameTimeMs != null) {
  32420. var dt = timeMs - this._lastFrameTimeMs;
  32421. this._rollingFrameTime.add(dt);
  32422. }
  32423. this._lastFrameTimeMs = timeMs;
  32424. };
  32425. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  32426. /**
  32427. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32428. * @return Average frame time in milliseconds
  32429. */
  32430. get: function () {
  32431. return this._rollingFrameTime.average;
  32432. },
  32433. enumerable: true,
  32434. configurable: true
  32435. });
  32436. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32437. /**
  32438. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32439. * @return Frame time variance in milliseconds squared
  32440. */
  32441. get: function () {
  32442. return this._rollingFrameTime.variance;
  32443. },
  32444. enumerable: true,
  32445. configurable: true
  32446. });
  32447. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32448. /**
  32449. * Returns the frame time of the most recent frame
  32450. * @return Frame time in milliseconds
  32451. */
  32452. get: function () {
  32453. return this._rollingFrameTime.history(0);
  32454. },
  32455. enumerable: true,
  32456. configurable: true
  32457. });
  32458. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32459. /**
  32460. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32461. * @return Framerate in frames per second
  32462. */
  32463. get: function () {
  32464. return 1000.0 / this._rollingFrameTime.average;
  32465. },
  32466. enumerable: true,
  32467. configurable: true
  32468. });
  32469. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32470. /**
  32471. * Returns the average framerate in frames per second using the most recent frame time
  32472. * @return Framerate in frames per second
  32473. */
  32474. get: function () {
  32475. var history = this._rollingFrameTime.history(0);
  32476. if (history === 0) {
  32477. return 0;
  32478. }
  32479. return 1000.0 / history;
  32480. },
  32481. enumerable: true,
  32482. configurable: true
  32483. });
  32484. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32485. /**
  32486. * Returns true if enough samples have been taken to completely fill the sliding window
  32487. * @return true if saturated
  32488. */
  32489. get: function () {
  32490. return this._rollingFrameTime.isSaturated();
  32491. },
  32492. enumerable: true,
  32493. configurable: true
  32494. });
  32495. /**
  32496. * Enables contributions to the sliding window sample set
  32497. */
  32498. PerformanceMonitor.prototype.enable = function () {
  32499. this._enabled = true;
  32500. };
  32501. /**
  32502. * Disables contributions to the sliding window sample set
  32503. * Samples will not be interpolated over the disabled period
  32504. */
  32505. PerformanceMonitor.prototype.disable = function () {
  32506. this._enabled = false;
  32507. //clear last sample to avoid interpolating over the disabled period when next enabled
  32508. this._lastFrameTimeMs = null;
  32509. };
  32510. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32511. /**
  32512. * Returns true if sampling is enabled
  32513. * @return true if enabled
  32514. */
  32515. get: function () {
  32516. return this._enabled;
  32517. },
  32518. enumerable: true,
  32519. configurable: true
  32520. });
  32521. /**
  32522. * Resets performance monitor
  32523. */
  32524. PerformanceMonitor.prototype.reset = function () {
  32525. //clear last sample to avoid interpolating over the disabled period when next enabled
  32526. this._lastFrameTimeMs = null;
  32527. //wipe record
  32528. this._rollingFrameTime.reset();
  32529. };
  32530. return PerformanceMonitor;
  32531. }());
  32532. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32533. /**
  32534. * RollingAverage
  32535. *
  32536. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32537. */
  32538. var RollingAverage = /** @class */ (function () {
  32539. /**
  32540. * constructor
  32541. * @param length The number of samples required to saturate the sliding window
  32542. */
  32543. function RollingAverage(length) {
  32544. this._samples = new Array(length);
  32545. this.reset();
  32546. }
  32547. /**
  32548. * Adds a sample to the sample set
  32549. * @param v The sample value
  32550. */
  32551. RollingAverage.prototype.add = function (v) {
  32552. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  32553. var delta;
  32554. //we need to check if we've already wrapped round
  32555. if (this.isSaturated()) {
  32556. //remove bottom of stack from mean
  32557. var bottomValue = this._samples[this._pos];
  32558. delta = bottomValue - this.average;
  32559. this.average -= delta / (this._sampleCount - 1);
  32560. this._m2 -= delta * (bottomValue - this.average);
  32561. }
  32562. else {
  32563. this._sampleCount++;
  32564. }
  32565. //add new value to mean
  32566. delta = v - this.average;
  32567. this.average += delta / (this._sampleCount);
  32568. this._m2 += delta * (v - this.average);
  32569. //set the new variance
  32570. this.variance = this._m2 / (this._sampleCount - 1);
  32571. this._samples[this._pos] = v;
  32572. this._pos++;
  32573. this._pos %= this._samples.length; //positive wrap around
  32574. };
  32575. /**
  32576. * Returns previously added values or null if outside of history or outside the sliding window domain
  32577. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32578. * @return Value previously recorded with add() or null if outside of range
  32579. */
  32580. RollingAverage.prototype.history = function (i) {
  32581. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32582. return 0;
  32583. }
  32584. var i0 = this._wrapPosition(this._pos - 1.0);
  32585. return this._samples[this._wrapPosition(i0 - i)];
  32586. };
  32587. /**
  32588. * Returns true if enough samples have been taken to completely fill the sliding window
  32589. * @return true if sample-set saturated
  32590. */
  32591. RollingAverage.prototype.isSaturated = function () {
  32592. return this._sampleCount >= this._samples.length;
  32593. };
  32594. /**
  32595. * Resets the rolling average (equivalent to 0 samples taken so far)
  32596. */
  32597. RollingAverage.prototype.reset = function () {
  32598. this.average = 0;
  32599. this.variance = 0;
  32600. this._sampleCount = 0;
  32601. this._pos = 0;
  32602. this._m2 = 0;
  32603. };
  32604. /**
  32605. * Wraps a value around the sample range boundaries
  32606. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32607. * @return Wrapped position in sample range
  32608. */
  32609. RollingAverage.prototype._wrapPosition = function (i) {
  32610. var max = this._samples.length;
  32611. return ((i % max) + max) % max;
  32612. };
  32613. return RollingAverage;
  32614. }());
  32615. BABYLON.RollingAverage = RollingAverage;
  32616. })(BABYLON || (BABYLON = {}));
  32617. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32618. var BABYLON;
  32619. (function (BABYLON) {
  32620. /**
  32621. * This groups together the common properties used for image processing either in direct forward pass
  32622. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32623. * or not.
  32624. */
  32625. var ImageProcessingConfiguration = /** @class */ (function () {
  32626. function ImageProcessingConfiguration() {
  32627. /**
  32628. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32629. */
  32630. this.colorCurves = new BABYLON.ColorCurves();
  32631. this._colorCurvesEnabled = false;
  32632. this._colorGradingEnabled = false;
  32633. this._colorGradingWithGreenDepth = true;
  32634. this._colorGradingBGR = true;
  32635. this._exposure = 1.0;
  32636. this._toneMappingEnabled = false;
  32637. this._contrast = 1.0;
  32638. /**
  32639. * Vignette stretch size.
  32640. */
  32641. this.vignetteStretch = 0;
  32642. /**
  32643. * Vignette centre X Offset.
  32644. */
  32645. this.vignetteCentreX = 0;
  32646. /**
  32647. * Vignette centre Y Offset.
  32648. */
  32649. this.vignetteCentreY = 0;
  32650. /**
  32651. * Vignette weight or intensity of the vignette effect.
  32652. */
  32653. this.vignetteWeight = 1.5;
  32654. /**
  32655. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32656. * if vignetteEnabled is set to true.
  32657. */
  32658. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32659. /**
  32660. * Camera field of view used by the Vignette effect.
  32661. */
  32662. this.vignetteCameraFov = 0.5;
  32663. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32664. this._vignetteEnabled = false;
  32665. this._applyByPostProcess = false;
  32666. this._isEnabled = true;
  32667. /**
  32668. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32669. * @type {BABYLON.Observable}
  32670. */
  32671. this.onUpdateParameters = new BABYLON.Observable();
  32672. }
  32673. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32674. /**
  32675. * Gets wether the color curves effect is enabled.
  32676. */
  32677. get: function () {
  32678. return this._colorCurvesEnabled;
  32679. },
  32680. /**
  32681. * Sets wether the color curves effect is enabled.
  32682. */
  32683. set: function (value) {
  32684. if (this._colorCurvesEnabled === value) {
  32685. return;
  32686. }
  32687. this._colorCurvesEnabled = value;
  32688. this._updateParameters();
  32689. },
  32690. enumerable: true,
  32691. configurable: true
  32692. });
  32693. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32694. /**
  32695. * Gets wether the color grading effect is enabled.
  32696. */
  32697. get: function () {
  32698. return this._colorGradingEnabled;
  32699. },
  32700. /**
  32701. * Sets wether the color grading effect is enabled.
  32702. */
  32703. set: function (value) {
  32704. if (this._colorGradingEnabled === value) {
  32705. return;
  32706. }
  32707. this._colorGradingEnabled = value;
  32708. this._updateParameters();
  32709. },
  32710. enumerable: true,
  32711. configurable: true
  32712. });
  32713. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32714. /**
  32715. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32716. */
  32717. get: function () {
  32718. return this._colorGradingWithGreenDepth;
  32719. },
  32720. /**
  32721. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32722. */
  32723. set: function (value) {
  32724. if (this._colorGradingWithGreenDepth === value) {
  32725. return;
  32726. }
  32727. this._colorGradingWithGreenDepth = value;
  32728. this._updateParameters();
  32729. },
  32730. enumerable: true,
  32731. configurable: true
  32732. });
  32733. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32734. /**
  32735. * Gets wether the color grading texture contains BGR values.
  32736. */
  32737. get: function () {
  32738. return this._colorGradingBGR;
  32739. },
  32740. /**
  32741. * Sets wether the color grading texture contains BGR values.
  32742. */
  32743. set: function (value) {
  32744. if (this._colorGradingBGR === value) {
  32745. return;
  32746. }
  32747. this._colorGradingBGR = value;
  32748. this._updateParameters();
  32749. },
  32750. enumerable: true,
  32751. configurable: true
  32752. });
  32753. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32754. /**
  32755. * Gets the Exposure used in the effect.
  32756. */
  32757. get: function () {
  32758. return this._exposure;
  32759. },
  32760. /**
  32761. * Sets the Exposure used in the effect.
  32762. */
  32763. set: function (value) {
  32764. if (this._exposure === value) {
  32765. return;
  32766. }
  32767. this._exposure = value;
  32768. this._updateParameters();
  32769. },
  32770. enumerable: true,
  32771. configurable: true
  32772. });
  32773. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32774. /**
  32775. * Gets wether the tone mapping effect is enabled.
  32776. */
  32777. get: function () {
  32778. return this._toneMappingEnabled;
  32779. },
  32780. /**
  32781. * Sets wether the tone mapping effect is enabled.
  32782. */
  32783. set: function (value) {
  32784. if (this._toneMappingEnabled === value) {
  32785. return;
  32786. }
  32787. this._toneMappingEnabled = value;
  32788. this._updateParameters();
  32789. },
  32790. enumerable: true,
  32791. configurable: true
  32792. });
  32793. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32794. /**
  32795. * Gets the contrast used in the effect.
  32796. */
  32797. get: function () {
  32798. return this._contrast;
  32799. },
  32800. /**
  32801. * Sets the contrast used in the effect.
  32802. */
  32803. set: function (value) {
  32804. if (this._contrast === value) {
  32805. return;
  32806. }
  32807. this._contrast = value;
  32808. this._updateParameters();
  32809. },
  32810. enumerable: true,
  32811. configurable: true
  32812. });
  32813. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32814. /**
  32815. * Gets the vignette blend mode allowing different kind of effect.
  32816. */
  32817. get: function () {
  32818. return this._vignetteBlendMode;
  32819. },
  32820. /**
  32821. * Sets the vignette blend mode allowing different kind of effect.
  32822. */
  32823. set: function (value) {
  32824. if (this._vignetteBlendMode === value) {
  32825. return;
  32826. }
  32827. this._vignetteBlendMode = value;
  32828. this._updateParameters();
  32829. },
  32830. enumerable: true,
  32831. configurable: true
  32832. });
  32833. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32834. /**
  32835. * Gets wether the vignette effect is enabled.
  32836. */
  32837. get: function () {
  32838. return this._vignetteEnabled;
  32839. },
  32840. /**
  32841. * Sets wether the vignette effect is enabled.
  32842. */
  32843. set: function (value) {
  32844. if (this._vignetteEnabled === value) {
  32845. return;
  32846. }
  32847. this._vignetteEnabled = value;
  32848. this._updateParameters();
  32849. },
  32850. enumerable: true,
  32851. configurable: true
  32852. });
  32853. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32854. /**
  32855. * Gets wether the image processing is applied through a post process or not.
  32856. */
  32857. get: function () {
  32858. return this._applyByPostProcess;
  32859. },
  32860. /**
  32861. * Sets wether the image processing is applied through a post process or not.
  32862. */
  32863. set: function (value) {
  32864. if (this._applyByPostProcess === value) {
  32865. return;
  32866. }
  32867. this._applyByPostProcess = value;
  32868. this._updateParameters();
  32869. },
  32870. enumerable: true,
  32871. configurable: true
  32872. });
  32873. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  32874. /**
  32875. * Gets wether the image processing is enabled or not.
  32876. */
  32877. get: function () {
  32878. return this._isEnabled;
  32879. },
  32880. /**
  32881. * Sets wether the image processing is enabled or not.
  32882. */
  32883. set: function (value) {
  32884. if (this._isEnabled === value) {
  32885. return;
  32886. }
  32887. this._isEnabled = value;
  32888. this._updateParameters();
  32889. },
  32890. enumerable: true,
  32891. configurable: true
  32892. });
  32893. /**
  32894. * Method called each time the image processing information changes requires to recompile the effect.
  32895. */
  32896. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32897. this.onUpdateParameters.notifyObservers(this);
  32898. };
  32899. ImageProcessingConfiguration.prototype.getClassName = function () {
  32900. return "ImageProcessingConfiguration";
  32901. };
  32902. /**
  32903. * Prepare the list of uniforms associated with the Image Processing effects.
  32904. * @param uniformsList The list of uniforms used in the effect
  32905. * @param defines the list of defines currently in use
  32906. */
  32907. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32908. if (defines.EXPOSURE) {
  32909. uniforms.push("exposureLinear");
  32910. }
  32911. if (defines.CONTRAST) {
  32912. uniforms.push("contrast");
  32913. }
  32914. if (defines.COLORGRADING) {
  32915. uniforms.push("colorTransformSettings");
  32916. }
  32917. if (defines.VIGNETTE) {
  32918. uniforms.push("vInverseScreenSize");
  32919. uniforms.push("vignetteSettings1");
  32920. uniforms.push("vignetteSettings2");
  32921. }
  32922. if (defines.COLORCURVES) {
  32923. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32924. }
  32925. };
  32926. /**
  32927. * Prepare the list of samplers associated with the Image Processing effects.
  32928. * @param uniformsList The list of uniforms used in the effect
  32929. * @param defines the list of defines currently in use
  32930. */
  32931. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32932. if (defines.COLORGRADING) {
  32933. samplersList.push("txColorTransform");
  32934. }
  32935. };
  32936. /**
  32937. * Prepare the list of defines associated to the shader.
  32938. * @param defines the list of defines to complete
  32939. */
  32940. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32941. if (forPostProcess === void 0) { forPostProcess = false; }
  32942. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  32943. defines.VIGNETTE = false;
  32944. defines.TONEMAPPING = false;
  32945. defines.CONTRAST = false;
  32946. defines.EXPOSURE = false;
  32947. defines.COLORCURVES = false;
  32948. defines.COLORGRADING = false;
  32949. defines.COLORGRADING3D = false;
  32950. defines.IMAGEPROCESSING = false;
  32951. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  32952. return;
  32953. }
  32954. defines.VIGNETTE = this.vignetteEnabled;
  32955. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32956. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32957. defines.TONEMAPPING = this.toneMappingEnabled;
  32958. defines.CONTRAST = (this.contrast !== 1.0);
  32959. defines.EXPOSURE = (this.exposure !== 1.0);
  32960. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32961. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32962. if (defines.COLORGRADING) {
  32963. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  32964. }
  32965. else {
  32966. defines.COLORGRADING3D = false;
  32967. }
  32968. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32969. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32970. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32971. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32972. };
  32973. /**
  32974. * Returns true if all the image processing information are ready.
  32975. */
  32976. ImageProcessingConfiguration.prototype.isReady = function () {
  32977. // Color Grading texure can not be none blocking.
  32978. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32979. };
  32980. /**
  32981. * Binds the image processing to the shader.
  32982. * @param effect The effect to bind to
  32983. */
  32984. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32985. if (aspectRatio === void 0) { aspectRatio = 1; }
  32986. // Color Curves
  32987. if (this._colorCurvesEnabled && this.colorCurves) {
  32988. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  32989. }
  32990. // Vignette
  32991. if (this._vignetteEnabled) {
  32992. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  32993. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  32994. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  32995. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  32996. var vignetteScaleX = vignetteScaleY * aspectRatio;
  32997. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  32998. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  32999. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33000. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33001. var vignettePower = -2.0 * this.vignetteWeight;
  33002. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33003. }
  33004. // Exposure
  33005. effect.setFloat("exposureLinear", this.exposure);
  33006. // Contrast
  33007. effect.setFloat("contrast", this.contrast);
  33008. // Color transform settings
  33009. if (this.colorGradingTexture) {
  33010. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33011. var textureSize = this.colorGradingTexture.getSize().height;
  33012. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33013. 0.5 / textureSize, // textureOffset
  33014. textureSize, // textureSize
  33015. this.colorGradingTexture.level // weight
  33016. );
  33017. }
  33018. };
  33019. /**
  33020. * Clones the current image processing instance.
  33021. * @return The cloned image processing
  33022. */
  33023. ImageProcessingConfiguration.prototype.clone = function () {
  33024. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33025. };
  33026. /**
  33027. * Serializes the current image processing instance to a json representation.
  33028. * @return a JSON representation
  33029. */
  33030. ImageProcessingConfiguration.prototype.serialize = function () {
  33031. return BABYLON.SerializationHelper.Serialize(this);
  33032. };
  33033. /**
  33034. * Parses the image processing from a json representation.
  33035. * @param source the JSON source to parse
  33036. * @return The parsed image processing
  33037. */
  33038. ImageProcessingConfiguration.Parse = function (source) {
  33039. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33040. };
  33041. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33042. /**
  33043. * Used to apply the vignette as a mix with the pixel color.
  33044. */
  33045. get: function () {
  33046. return this._VIGNETTEMODE_MULTIPLY;
  33047. },
  33048. enumerable: true,
  33049. configurable: true
  33050. });
  33051. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33052. /**
  33053. * Used to apply the vignette as a replacement of the pixel color.
  33054. */
  33055. get: function () {
  33056. return this._VIGNETTEMODE_OPAQUE;
  33057. },
  33058. enumerable: true,
  33059. configurable: true
  33060. });
  33061. // Static constants associated to the image processing.
  33062. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33063. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33064. __decorate([
  33065. BABYLON.serializeAsColorCurves()
  33066. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33067. __decorate([
  33068. BABYLON.serialize()
  33069. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33070. __decorate([
  33071. BABYLON.serializeAsTexture()
  33072. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33073. __decorate([
  33074. BABYLON.serialize()
  33075. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33076. __decorate([
  33077. BABYLON.serialize()
  33078. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33079. __decorate([
  33080. BABYLON.serialize()
  33081. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33082. __decorate([
  33083. BABYLON.serialize()
  33084. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33085. __decorate([
  33086. BABYLON.serialize()
  33087. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33088. __decorate([
  33089. BABYLON.serialize()
  33090. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33091. __decorate([
  33092. BABYLON.serialize()
  33093. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33094. __decorate([
  33095. BABYLON.serialize()
  33096. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33097. __decorate([
  33098. BABYLON.serialize()
  33099. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33100. __decorate([
  33101. BABYLON.serialize()
  33102. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33103. __decorate([
  33104. BABYLON.serializeAsColor4()
  33105. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33106. __decorate([
  33107. BABYLON.serialize()
  33108. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33109. __decorate([
  33110. BABYLON.serialize()
  33111. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33112. __decorate([
  33113. BABYLON.serialize()
  33114. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33115. __decorate([
  33116. BABYLON.serialize()
  33117. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33118. __decorate([
  33119. BABYLON.serialize()
  33120. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33121. return ImageProcessingConfiguration;
  33122. }());
  33123. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33124. })(BABYLON || (BABYLON = {}));
  33125. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33126. var BABYLON;
  33127. (function (BABYLON) {
  33128. /**
  33129. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33130. * It can help converting any input color in a desired output one. This can then be used to create effects
  33131. * from sepia, black and white to sixties or futuristic rendering...
  33132. *
  33133. * The only supported format is currently 3dl.
  33134. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33135. */
  33136. var ColorGradingTexture = /** @class */ (function (_super) {
  33137. __extends(ColorGradingTexture, _super);
  33138. /**
  33139. * Instantiates a ColorGradingTexture from the following parameters.
  33140. *
  33141. * @param url The location of the color gradind data (currently only supporting 3dl)
  33142. * @param scene The scene the texture will be used in
  33143. */
  33144. function ColorGradingTexture(url, scene) {
  33145. var _this = _super.call(this, scene) || this;
  33146. if (!url) {
  33147. return _this;
  33148. }
  33149. _this._engine = scene.getEngine();
  33150. _this._textureMatrix = BABYLON.Matrix.Identity();
  33151. _this.name = url;
  33152. _this.url = url;
  33153. _this.hasAlpha = false;
  33154. _this.isCube = false;
  33155. _this.is3D = _this._engine.webGLVersion > 1;
  33156. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33157. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33158. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33159. _this.anisotropicFilteringLevel = 1;
  33160. _this._texture = _this._getFromCache(url, true);
  33161. if (!_this._texture) {
  33162. if (!scene.useDelayedTextureLoading) {
  33163. _this.loadTexture();
  33164. }
  33165. else {
  33166. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33167. }
  33168. }
  33169. return _this;
  33170. }
  33171. /**
  33172. * Returns the texture matrix used in most of the material.
  33173. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33174. */
  33175. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33176. return this._textureMatrix;
  33177. };
  33178. /**
  33179. * Occurs when the file being loaded is a .3dl LUT file.
  33180. */
  33181. ColorGradingTexture.prototype.load3dlTexture = function () {
  33182. var engine = this._engine;
  33183. var texture;
  33184. if (engine.webGLVersion === 1) {
  33185. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33186. }
  33187. else {
  33188. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33189. }
  33190. this._texture = texture;
  33191. var callback = function (text) {
  33192. if (typeof text !== "string") {
  33193. return;
  33194. }
  33195. var data = null;
  33196. var tempData = null;
  33197. var line;
  33198. var lines = text.split('\n');
  33199. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33200. var maxColor = 0;
  33201. for (var i = 0; i < lines.length; i++) {
  33202. line = lines[i];
  33203. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33204. continue;
  33205. if (line.indexOf('#') === 0)
  33206. continue;
  33207. var words = line.split(" ");
  33208. if (size === 0) {
  33209. // Number of space + one
  33210. size = words.length;
  33211. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33212. tempData = new Float32Array(size * size * size * 4);
  33213. continue;
  33214. }
  33215. if (size != 0) {
  33216. var r = Math.max(parseInt(words[0]), 0);
  33217. var g = Math.max(parseInt(words[1]), 0);
  33218. var b = Math.max(parseInt(words[2]), 0);
  33219. maxColor = Math.max(r, maxColor);
  33220. maxColor = Math.max(g, maxColor);
  33221. maxColor = Math.max(b, maxColor);
  33222. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33223. if (tempData) {
  33224. tempData[pixelStorageIndex + 0] = r;
  33225. tempData[pixelStorageIndex + 1] = g;
  33226. tempData[pixelStorageIndex + 2] = b;
  33227. }
  33228. pixelIndexSlice++;
  33229. if (pixelIndexSlice % size == 0) {
  33230. pixelIndexH++;
  33231. pixelIndexSlice = 0;
  33232. if (pixelIndexH % size == 0) {
  33233. pixelIndexW++;
  33234. pixelIndexH = 0;
  33235. }
  33236. }
  33237. }
  33238. }
  33239. if (tempData && data) {
  33240. for (var i = 0; i < tempData.length; i++) {
  33241. if (i > 0 && (i + 1) % 4 === 0) {
  33242. data[i] = 255;
  33243. }
  33244. else {
  33245. var value = tempData[i];
  33246. data[i] = (value / maxColor * 255);
  33247. }
  33248. }
  33249. }
  33250. if (texture.is3D) {
  33251. texture.updateSize(size, size, size);
  33252. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33253. }
  33254. else {
  33255. texture.updateSize(size * size, size);
  33256. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33257. }
  33258. };
  33259. BABYLON.Tools.LoadFile(this.url, callback);
  33260. return this._texture;
  33261. };
  33262. /**
  33263. * Starts the loading process of the texture.
  33264. */
  33265. ColorGradingTexture.prototype.loadTexture = function () {
  33266. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33267. this.load3dlTexture();
  33268. }
  33269. };
  33270. /**
  33271. * Clones the color gradind texture.
  33272. */
  33273. ColorGradingTexture.prototype.clone = function () {
  33274. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33275. // Base texture
  33276. newTexture.level = this.level;
  33277. return newTexture;
  33278. };
  33279. /**
  33280. * Called during delayed load for textures.
  33281. */
  33282. ColorGradingTexture.prototype.delayLoad = function () {
  33283. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33284. return;
  33285. }
  33286. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33287. this._texture = this._getFromCache(this.url, true);
  33288. if (!this._texture) {
  33289. this.loadTexture();
  33290. }
  33291. };
  33292. /**
  33293. * Parses a color grading texture serialized by Babylon.
  33294. * @param parsedTexture The texture information being parsedTexture
  33295. * @param scene The scene to load the texture in
  33296. * @param rootUrl The root url of the data assets to load
  33297. * @return A color gradind texture
  33298. */
  33299. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33300. var texture = null;
  33301. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33302. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  33303. texture.name = parsedTexture.name;
  33304. texture.level = parsedTexture.level;
  33305. }
  33306. return texture;
  33307. };
  33308. /**
  33309. * Serializes the LUT texture to json format.
  33310. */
  33311. ColorGradingTexture.prototype.serialize = function () {
  33312. if (!this.name) {
  33313. return null;
  33314. }
  33315. var serializationObject = {};
  33316. serializationObject.name = this.name;
  33317. serializationObject.level = this.level;
  33318. serializationObject.customType = "BABYLON.ColorGradingTexture";
  33319. return serializationObject;
  33320. };
  33321. /**
  33322. * Empty line regex stored for GC.
  33323. */
  33324. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  33325. return ColorGradingTexture;
  33326. }(BABYLON.BaseTexture));
  33327. BABYLON.ColorGradingTexture = ColorGradingTexture;
  33328. })(BABYLON || (BABYLON = {}));
  33329. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  33330. var BABYLON;
  33331. (function (BABYLON) {
  33332. /**
  33333. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33334. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33335. * 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;
  33336. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33337. */
  33338. var ColorCurves = /** @class */ (function () {
  33339. function ColorCurves() {
  33340. this._dirty = true;
  33341. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  33342. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  33343. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33344. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  33345. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33346. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  33347. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  33348. this._globalHue = 30;
  33349. this._globalDensity = 0;
  33350. this._globalSaturation = 0;
  33351. this._globalExposure = 0;
  33352. this._highlightsHue = 30;
  33353. this._highlightsDensity = 0;
  33354. this._highlightsSaturation = 0;
  33355. this._highlightsExposure = 0;
  33356. this._midtonesHue = 30;
  33357. this._midtonesDensity = 0;
  33358. this._midtonesSaturation = 0;
  33359. this._midtonesExposure = 0;
  33360. this._shadowsHue = 30;
  33361. this._shadowsDensity = 0;
  33362. this._shadowsSaturation = 0;
  33363. this._shadowsExposure = 0;
  33364. }
  33365. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  33366. /**
  33367. * Gets the global Hue value.
  33368. * 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).
  33369. */
  33370. get: function () {
  33371. return this._globalHue;
  33372. },
  33373. /**
  33374. * Sets the global Hue value.
  33375. * 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).
  33376. */
  33377. set: function (value) {
  33378. this._globalHue = value;
  33379. this._dirty = true;
  33380. },
  33381. enumerable: true,
  33382. configurable: true
  33383. });
  33384. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  33385. /**
  33386. * Gets the global Density value.
  33387. * 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.
  33388. * Values less than zero provide a filter of opposite hue.
  33389. */
  33390. get: function () {
  33391. return this._globalDensity;
  33392. },
  33393. /**
  33394. * Sets the global Density value.
  33395. * 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.
  33396. * Values less than zero provide a filter of opposite hue.
  33397. */
  33398. set: function (value) {
  33399. this._globalDensity = value;
  33400. this._dirty = true;
  33401. },
  33402. enumerable: true,
  33403. configurable: true
  33404. });
  33405. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  33406. /**
  33407. * Gets the global Saturation value.
  33408. * 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.
  33409. */
  33410. get: function () {
  33411. return this._globalSaturation;
  33412. },
  33413. /**
  33414. * Sets the global Saturation value.
  33415. * 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.
  33416. */
  33417. set: function (value) {
  33418. this._globalSaturation = value;
  33419. this._dirty = true;
  33420. },
  33421. enumerable: true,
  33422. configurable: true
  33423. });
  33424. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  33425. /**
  33426. * Gets the highlights Hue value.
  33427. * 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).
  33428. */
  33429. get: function () {
  33430. return this._highlightsHue;
  33431. },
  33432. /**
  33433. * Sets the highlights Hue value.
  33434. * 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).
  33435. */
  33436. set: function (value) {
  33437. this._highlightsHue = value;
  33438. this._dirty = true;
  33439. },
  33440. enumerable: true,
  33441. configurable: true
  33442. });
  33443. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  33444. /**
  33445. * Gets the highlights Density value.
  33446. * 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.
  33447. * Values less than zero provide a filter of opposite hue.
  33448. */
  33449. get: function () {
  33450. return this._highlightsDensity;
  33451. },
  33452. /**
  33453. * Sets the highlights Density value.
  33454. * 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.
  33455. * Values less than zero provide a filter of opposite hue.
  33456. */
  33457. set: function (value) {
  33458. this._highlightsDensity = value;
  33459. this._dirty = true;
  33460. },
  33461. enumerable: true,
  33462. configurable: true
  33463. });
  33464. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33465. /**
  33466. * Gets the highlights Saturation value.
  33467. * 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.
  33468. */
  33469. get: function () {
  33470. return this._highlightsSaturation;
  33471. },
  33472. /**
  33473. * Sets the highlights Saturation value.
  33474. * 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.
  33475. */
  33476. set: function (value) {
  33477. this._highlightsSaturation = value;
  33478. this._dirty = true;
  33479. },
  33480. enumerable: true,
  33481. configurable: true
  33482. });
  33483. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33484. /**
  33485. * Gets the highlights Exposure value.
  33486. * 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.
  33487. */
  33488. get: function () {
  33489. return this._highlightsExposure;
  33490. },
  33491. /**
  33492. * Sets the highlights Exposure value.
  33493. * 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.
  33494. */
  33495. set: function (value) {
  33496. this._highlightsExposure = value;
  33497. this._dirty = true;
  33498. },
  33499. enumerable: true,
  33500. configurable: true
  33501. });
  33502. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33503. /**
  33504. * Gets the midtones Hue value.
  33505. * 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).
  33506. */
  33507. get: function () {
  33508. return this._midtonesHue;
  33509. },
  33510. /**
  33511. * Sets the midtones Hue value.
  33512. * 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).
  33513. */
  33514. set: function (value) {
  33515. this._midtonesHue = value;
  33516. this._dirty = true;
  33517. },
  33518. enumerable: true,
  33519. configurable: true
  33520. });
  33521. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33522. /**
  33523. * Gets the midtones Density value.
  33524. * 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.
  33525. * Values less than zero provide a filter of opposite hue.
  33526. */
  33527. get: function () {
  33528. return this._midtonesDensity;
  33529. },
  33530. /**
  33531. * Sets the midtones Density value.
  33532. * 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.
  33533. * Values less than zero provide a filter of opposite hue.
  33534. */
  33535. set: function (value) {
  33536. this._midtonesDensity = value;
  33537. this._dirty = true;
  33538. },
  33539. enumerable: true,
  33540. configurable: true
  33541. });
  33542. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  33543. /**
  33544. * Gets the midtones Saturation value.
  33545. * 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.
  33546. */
  33547. get: function () {
  33548. return this._midtonesSaturation;
  33549. },
  33550. /**
  33551. * Sets the midtones Saturation value.
  33552. * 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.
  33553. */
  33554. set: function (value) {
  33555. this._midtonesSaturation = value;
  33556. this._dirty = true;
  33557. },
  33558. enumerable: true,
  33559. configurable: true
  33560. });
  33561. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  33562. /**
  33563. * Gets the midtones Exposure value.
  33564. * 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.
  33565. */
  33566. get: function () {
  33567. return this._midtonesExposure;
  33568. },
  33569. /**
  33570. * Sets the midtones Exposure value.
  33571. * 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.
  33572. */
  33573. set: function (value) {
  33574. this._midtonesExposure = value;
  33575. this._dirty = true;
  33576. },
  33577. enumerable: true,
  33578. configurable: true
  33579. });
  33580. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  33581. /**
  33582. * Gets the shadows Hue value.
  33583. * 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).
  33584. */
  33585. get: function () {
  33586. return this._shadowsHue;
  33587. },
  33588. /**
  33589. * Sets the shadows Hue value.
  33590. * 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).
  33591. */
  33592. set: function (value) {
  33593. this._shadowsHue = value;
  33594. this._dirty = true;
  33595. },
  33596. enumerable: true,
  33597. configurable: true
  33598. });
  33599. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33600. /**
  33601. * Gets the shadows Density value.
  33602. * 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.
  33603. * Values less than zero provide a filter of opposite hue.
  33604. */
  33605. get: function () {
  33606. return this._shadowsDensity;
  33607. },
  33608. /**
  33609. * Sets the shadows Density value.
  33610. * 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.
  33611. * Values less than zero provide a filter of opposite hue.
  33612. */
  33613. set: function (value) {
  33614. this._shadowsDensity = value;
  33615. this._dirty = true;
  33616. },
  33617. enumerable: true,
  33618. configurable: true
  33619. });
  33620. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  33621. /**
  33622. * Gets the shadows Saturation value.
  33623. * 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.
  33624. */
  33625. get: function () {
  33626. return this._shadowsSaturation;
  33627. },
  33628. /**
  33629. * Sets the shadows Saturation value.
  33630. * 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.
  33631. */
  33632. set: function (value) {
  33633. this._shadowsSaturation = value;
  33634. this._dirty = true;
  33635. },
  33636. enumerable: true,
  33637. configurable: true
  33638. });
  33639. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  33640. /**
  33641. * Gets the shadows Exposure value.
  33642. * 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.
  33643. */
  33644. get: function () {
  33645. return this._shadowsExposure;
  33646. },
  33647. /**
  33648. * Sets the shadows Exposure value.
  33649. * 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.
  33650. */
  33651. set: function (value) {
  33652. this._shadowsExposure = value;
  33653. this._dirty = true;
  33654. },
  33655. enumerable: true,
  33656. configurable: true
  33657. });
  33658. ColorCurves.prototype.getClassName = function () {
  33659. return "ColorCurves";
  33660. };
  33661. /**
  33662. * Binds the color curves to the shader.
  33663. * @param colorCurves The color curve to bind
  33664. * @param effect The effect to bind to
  33665. */
  33666. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33667. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33668. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33669. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33670. if (colorCurves._dirty) {
  33671. colorCurves._dirty = false;
  33672. // Fill in global info.
  33673. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33674. // Compute highlights info.
  33675. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33676. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33677. // Compute midtones info.
  33678. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33679. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33680. // Compute shadows info.
  33681. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33682. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33683. // Compute deltas (neutral is midtones).
  33684. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33685. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33686. }
  33687. if (effect) {
  33688. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33689. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33690. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33691. }
  33692. };
  33693. /**
  33694. * Prepare the list of uniforms associated with the ColorCurves effects.
  33695. * @param uniformsList The list of uniforms used in the effect
  33696. */
  33697. ColorCurves.PrepareUniforms = function (uniformsList) {
  33698. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33699. };
  33700. /**
  33701. * Returns color grading data based on a hue, density, saturation and exposure value.
  33702. * @param filterHue The hue of the color filter.
  33703. * @param filterDensity The density of the color filter.
  33704. * @param saturation The saturation.
  33705. * @param exposure The exposure.
  33706. * @param result The result data container.
  33707. */
  33708. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33709. if (hue == null) {
  33710. return;
  33711. }
  33712. hue = ColorCurves.clamp(hue, 0, 360);
  33713. density = ColorCurves.clamp(density, -100, 100);
  33714. saturation = ColorCurves.clamp(saturation, -100, 100);
  33715. exposure = ColorCurves.clamp(exposure, -100, 100);
  33716. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33717. // so that the maximum filter density is only 50% control. This provides fine control
  33718. // for small values and reasonable range.
  33719. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33720. density *= 0.5;
  33721. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33722. if (density < 0) {
  33723. density *= -1;
  33724. hue = (hue + 180) % 360;
  33725. }
  33726. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33727. result.scaleToRef(2, result);
  33728. result.a = 1 + 0.01 * saturation;
  33729. };
  33730. /**
  33731. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33732. * @param value The input slider value in range [-100,100].
  33733. * @returns Adjusted value.
  33734. */
  33735. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33736. value /= 100;
  33737. var x = Math.abs(value);
  33738. x = Math.pow(x, 2);
  33739. if (value < 0) {
  33740. x *= -1;
  33741. }
  33742. x *= 100;
  33743. return x;
  33744. };
  33745. /**
  33746. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33747. * @param hue The hue (H) input.
  33748. * @param saturation The saturation (S) input.
  33749. * @param brightness The brightness (B) input.
  33750. * @result An RGBA color represented as Vector4.
  33751. */
  33752. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33753. var h = ColorCurves.clamp(hue, 0, 360);
  33754. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33755. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33756. if (s === 0) {
  33757. result.r = v;
  33758. result.g = v;
  33759. result.b = v;
  33760. }
  33761. else {
  33762. // sector 0 to 5
  33763. h /= 60;
  33764. var i = Math.floor(h);
  33765. // fractional part of h
  33766. var f = h - i;
  33767. var p = v * (1 - s);
  33768. var q = v * (1 - s * f);
  33769. var t = v * (1 - s * (1 - f));
  33770. switch (i) {
  33771. case 0:
  33772. result.r = v;
  33773. result.g = t;
  33774. result.b = p;
  33775. break;
  33776. case 1:
  33777. result.r = q;
  33778. result.g = v;
  33779. result.b = p;
  33780. break;
  33781. case 2:
  33782. result.r = p;
  33783. result.g = v;
  33784. result.b = t;
  33785. break;
  33786. case 3:
  33787. result.r = p;
  33788. result.g = q;
  33789. result.b = v;
  33790. break;
  33791. case 4:
  33792. result.r = t;
  33793. result.g = p;
  33794. result.b = v;
  33795. break;
  33796. default:// case 5:
  33797. result.r = v;
  33798. result.g = p;
  33799. result.b = q;
  33800. break;
  33801. }
  33802. }
  33803. result.a = 1;
  33804. };
  33805. /**
  33806. * Returns a value clamped between min and max
  33807. * @param value The value to clamp
  33808. * @param min The minimum of value
  33809. * @param max The maximum of value
  33810. * @returns The clamped value.
  33811. */
  33812. ColorCurves.clamp = function (value, min, max) {
  33813. return Math.min(Math.max(value, min), max);
  33814. };
  33815. /**
  33816. * Clones the current color curve instance.
  33817. * @return The cloned curves
  33818. */
  33819. ColorCurves.prototype.clone = function () {
  33820. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33821. };
  33822. /**
  33823. * Serializes the current color curve instance to a json representation.
  33824. * @return a JSON representation
  33825. */
  33826. ColorCurves.prototype.serialize = function () {
  33827. return BABYLON.SerializationHelper.Serialize(this);
  33828. };
  33829. /**
  33830. * Parses the color curve from a json representation.
  33831. * @param source the JSON source to parse
  33832. * @return The parsed curves
  33833. */
  33834. ColorCurves.Parse = function (source) {
  33835. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33836. };
  33837. __decorate([
  33838. BABYLON.serialize()
  33839. ], ColorCurves.prototype, "_globalHue", void 0);
  33840. __decorate([
  33841. BABYLON.serialize()
  33842. ], ColorCurves.prototype, "_globalDensity", void 0);
  33843. __decorate([
  33844. BABYLON.serialize()
  33845. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33846. __decorate([
  33847. BABYLON.serialize()
  33848. ], ColorCurves.prototype, "_globalExposure", void 0);
  33849. __decorate([
  33850. BABYLON.serialize()
  33851. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33852. __decorate([
  33853. BABYLON.serialize()
  33854. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33855. __decorate([
  33856. BABYLON.serialize()
  33857. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33858. __decorate([
  33859. BABYLON.serialize()
  33860. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33861. __decorate([
  33862. BABYLON.serialize()
  33863. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33864. __decorate([
  33865. BABYLON.serialize()
  33866. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33867. __decorate([
  33868. BABYLON.serialize()
  33869. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33870. __decorate([
  33871. BABYLON.serialize()
  33872. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33873. return ColorCurves;
  33874. }());
  33875. BABYLON.ColorCurves = ColorCurves;
  33876. })(BABYLON || (BABYLON = {}));
  33877. //# sourceMappingURL=babylon.colorCurves.js.map
  33878. var BABYLON;
  33879. (function (BABYLON) {
  33880. var StandardMaterialDefines = /** @class */ (function (_super) {
  33881. __extends(StandardMaterialDefines, _super);
  33882. function StandardMaterialDefines() {
  33883. var _this = _super.call(this) || this;
  33884. _this.MAINUV1 = false;
  33885. _this.MAINUV2 = false;
  33886. _this.DIFFUSE = false;
  33887. _this.DIFFUSEDIRECTUV = 0;
  33888. _this.AMBIENT = false;
  33889. _this.AMBIENTDIRECTUV = 0;
  33890. _this.OPACITY = false;
  33891. _this.OPACITYDIRECTUV = 0;
  33892. _this.OPACITYRGB = false;
  33893. _this.REFLECTION = false;
  33894. _this.EMISSIVE = false;
  33895. _this.EMISSIVEDIRECTUV = 0;
  33896. _this.SPECULAR = false;
  33897. _this.SPECULARDIRECTUV = 0;
  33898. _this.BUMP = false;
  33899. _this.BUMPDIRECTUV = 0;
  33900. _this.PARALLAX = false;
  33901. _this.PARALLAXOCCLUSION = false;
  33902. _this.SPECULAROVERALPHA = false;
  33903. _this.CLIPPLANE = false;
  33904. _this.ALPHATEST = false;
  33905. _this.DEPTHPREPASS = false;
  33906. _this.ALPHAFROMDIFFUSE = false;
  33907. _this.POINTSIZE = false;
  33908. _this.FOG = false;
  33909. _this.SPECULARTERM = false;
  33910. _this.DIFFUSEFRESNEL = false;
  33911. _this.OPACITYFRESNEL = false;
  33912. _this.REFLECTIONFRESNEL = false;
  33913. _this.REFRACTIONFRESNEL = false;
  33914. _this.EMISSIVEFRESNEL = false;
  33915. _this.FRESNEL = false;
  33916. _this.NORMAL = false;
  33917. _this.UV1 = false;
  33918. _this.UV2 = false;
  33919. _this.VERTEXCOLOR = false;
  33920. _this.VERTEXALPHA = false;
  33921. _this.NUM_BONE_INFLUENCERS = 0;
  33922. _this.BonesPerMesh = 0;
  33923. _this.INSTANCES = false;
  33924. _this.GLOSSINESS = false;
  33925. _this.ROUGHNESS = false;
  33926. _this.EMISSIVEASILLUMINATION = false;
  33927. _this.LINKEMISSIVEWITHDIFFUSE = false;
  33928. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  33929. _this.LIGHTMAP = false;
  33930. _this.LIGHTMAPDIRECTUV = 0;
  33931. _this.USELIGHTMAPASSHADOWMAP = false;
  33932. _this.REFLECTIONMAP_3D = false;
  33933. _this.REFLECTIONMAP_SPHERICAL = false;
  33934. _this.REFLECTIONMAP_PLANAR = false;
  33935. _this.REFLECTIONMAP_CUBIC = false;
  33936. _this.REFLECTIONMAP_PROJECTION = false;
  33937. _this.REFLECTIONMAP_SKYBOX = false;
  33938. _this.REFLECTIONMAP_EXPLICIT = false;
  33939. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33940. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33941. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33942. _this.INVERTCUBICMAP = false;
  33943. _this.LOGARITHMICDEPTH = false;
  33944. _this.REFRACTION = false;
  33945. _this.REFRACTIONMAP_3D = false;
  33946. _this.REFLECTIONOVERALPHA = false;
  33947. _this.TWOSIDEDLIGHTING = false;
  33948. _this.SHADOWFLOAT = false;
  33949. _this.MORPHTARGETS = false;
  33950. _this.MORPHTARGETS_NORMAL = false;
  33951. _this.MORPHTARGETS_TANGENT = false;
  33952. _this.NUM_MORPH_INFLUENCERS = 0;
  33953. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  33954. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  33955. _this.IMAGEPROCESSING = false;
  33956. _this.VIGNETTE = false;
  33957. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  33958. _this.VIGNETTEBLENDMODEOPAQUE = false;
  33959. _this.TONEMAPPING = false;
  33960. _this.CONTRAST = false;
  33961. _this.COLORCURVES = false;
  33962. _this.COLORGRADING = false;
  33963. _this.COLORGRADING3D = false;
  33964. _this.SAMPLER3DGREENDEPTH = false;
  33965. _this.SAMPLER3DBGRMAP = false;
  33966. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33967. _this.EXPOSURE = false;
  33968. _this.rebuild();
  33969. return _this;
  33970. }
  33971. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  33972. var modes = [
  33973. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  33974. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  33975. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  33976. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  33977. ];
  33978. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  33979. var mode = modes_1[_i];
  33980. this[mode] = (mode === modeToEnable);
  33981. }
  33982. };
  33983. return StandardMaterialDefines;
  33984. }(BABYLON.MaterialDefines));
  33985. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  33986. var StandardMaterial = /** @class */ (function (_super) {
  33987. __extends(StandardMaterial, _super);
  33988. function StandardMaterial(name, scene) {
  33989. var _this = _super.call(this, name, scene) || this;
  33990. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33991. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  33992. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  33993. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33994. _this.specularPower = 64;
  33995. _this._useAlphaFromDiffuseTexture = false;
  33996. _this._useEmissiveAsIllumination = false;
  33997. _this._linkEmissiveWithDiffuse = false;
  33998. _this._useSpecularOverAlpha = false;
  33999. _this._useReflectionOverAlpha = false;
  34000. _this._disableLighting = false;
  34001. _this._useParallax = false;
  34002. _this._useParallaxOcclusion = false;
  34003. _this.parallaxScaleBias = 0.05;
  34004. _this._roughness = 0;
  34005. _this.indexOfRefraction = 0.98;
  34006. _this.invertRefractionY = true;
  34007. _this._useLightmapAsShadowmap = false;
  34008. _this._useReflectionFresnelFromSpecular = false;
  34009. _this._useGlossinessFromSpecularMapAlpha = false;
  34010. _this._maxSimultaneousLights = 4;
  34011. /**
  34012. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34013. */
  34014. _this._invertNormalMapX = false;
  34015. /**
  34016. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34017. */
  34018. _this._invertNormalMapY = false;
  34019. /**
  34020. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34021. */
  34022. _this._twoSidedLighting = false;
  34023. _this._renderTargets = new BABYLON.SmartArray(16);
  34024. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34025. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34026. // Setup the default processing configuration to the scene.
  34027. _this._attachImageProcessingConfiguration(null);
  34028. _this.getRenderTargetTextures = function () {
  34029. _this._renderTargets.reset();
  34030. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34031. _this._renderTargets.push(_this._reflectionTexture);
  34032. }
  34033. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34034. _this._renderTargets.push(_this._refractionTexture);
  34035. }
  34036. return _this._renderTargets;
  34037. };
  34038. return _this;
  34039. }
  34040. ;
  34041. ;
  34042. ;
  34043. ;
  34044. ;
  34045. ;
  34046. ;
  34047. ;
  34048. ;
  34049. ;
  34050. ;
  34051. ;
  34052. ;
  34053. ;
  34054. ;
  34055. ;
  34056. ;
  34057. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  34058. /**
  34059. * Gets the image processing configuration used either in this material.
  34060. */
  34061. get: function () {
  34062. return this._imageProcessingConfiguration;
  34063. },
  34064. /**
  34065. * Sets the Default image processing configuration used either in the this material.
  34066. *
  34067. * If sets to null, the scene one is in use.
  34068. */
  34069. set: function (value) {
  34070. this._attachImageProcessingConfiguration(value);
  34071. // Ensure the effect will be rebuilt.
  34072. this._markAllSubMeshesAsTexturesDirty();
  34073. },
  34074. enumerable: true,
  34075. configurable: true
  34076. });
  34077. /**
  34078. * Attaches a new image processing configuration to the Standard Material.
  34079. * @param configuration
  34080. */
  34081. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34082. var _this = this;
  34083. if (configuration === this._imageProcessingConfiguration) {
  34084. return;
  34085. }
  34086. // Detaches observer.
  34087. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34088. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34089. }
  34090. // Pick the scene configuration if needed.
  34091. if (!configuration) {
  34092. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34093. }
  34094. else {
  34095. this._imageProcessingConfiguration = configuration;
  34096. }
  34097. // Attaches observer.
  34098. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34099. _this._markAllSubMeshesAsImageProcessingDirty();
  34100. });
  34101. };
  34102. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  34103. /**
  34104. * Gets wether the color curves effect is enabled.
  34105. */
  34106. get: function () {
  34107. return this.imageProcessingConfiguration.colorCurvesEnabled;
  34108. },
  34109. /**
  34110. * Sets wether the color curves effect is enabled.
  34111. */
  34112. set: function (value) {
  34113. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  34114. },
  34115. enumerable: true,
  34116. configurable: true
  34117. });
  34118. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  34119. /**
  34120. * Gets wether the color grading effect is enabled.
  34121. */
  34122. get: function () {
  34123. return this.imageProcessingConfiguration.colorGradingEnabled;
  34124. },
  34125. /**
  34126. * Gets wether the color grading effect is enabled.
  34127. */
  34128. set: function (value) {
  34129. this.imageProcessingConfiguration.colorGradingEnabled = value;
  34130. },
  34131. enumerable: true,
  34132. configurable: true
  34133. });
  34134. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  34135. /**
  34136. * Gets wether tonemapping is enabled or not.
  34137. */
  34138. get: function () {
  34139. return this._imageProcessingConfiguration.toneMappingEnabled;
  34140. },
  34141. /**
  34142. * Sets wether tonemapping is enabled or not
  34143. */
  34144. set: function (value) {
  34145. this._imageProcessingConfiguration.toneMappingEnabled = value;
  34146. },
  34147. enumerable: true,
  34148. configurable: true
  34149. });
  34150. ;
  34151. ;
  34152. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  34153. /**
  34154. * The camera exposure used on this material.
  34155. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34156. * This corresponds to a photographic exposure.
  34157. */
  34158. get: function () {
  34159. return this._imageProcessingConfiguration.exposure;
  34160. },
  34161. /**
  34162. * The camera exposure used on this material.
  34163. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34164. * This corresponds to a photographic exposure.
  34165. */
  34166. set: function (value) {
  34167. this._imageProcessingConfiguration.exposure = value;
  34168. },
  34169. enumerable: true,
  34170. configurable: true
  34171. });
  34172. ;
  34173. ;
  34174. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  34175. /**
  34176. * Gets The camera contrast used on this material.
  34177. */
  34178. get: function () {
  34179. return this._imageProcessingConfiguration.contrast;
  34180. },
  34181. /**
  34182. * Sets The camera contrast used on this material.
  34183. */
  34184. set: function (value) {
  34185. this._imageProcessingConfiguration.contrast = value;
  34186. },
  34187. enumerable: true,
  34188. configurable: true
  34189. });
  34190. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  34191. /**
  34192. * Gets the Color Grading 2D Lookup Texture.
  34193. */
  34194. get: function () {
  34195. return this._imageProcessingConfiguration.colorGradingTexture;
  34196. },
  34197. /**
  34198. * Sets the Color Grading 2D Lookup Texture.
  34199. */
  34200. set: function (value) {
  34201. this._imageProcessingConfiguration.colorGradingTexture = value;
  34202. },
  34203. enumerable: true,
  34204. configurable: true
  34205. });
  34206. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  34207. /**
  34208. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34209. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34210. * 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;
  34211. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34212. */
  34213. get: function () {
  34214. return this._imageProcessingConfiguration.colorCurves;
  34215. },
  34216. /**
  34217. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34218. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34219. * 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;
  34220. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34221. */
  34222. set: function (value) {
  34223. this._imageProcessingConfiguration.colorCurves = value;
  34224. },
  34225. enumerable: true,
  34226. configurable: true
  34227. });
  34228. StandardMaterial.prototype.getClassName = function () {
  34229. return "StandardMaterial";
  34230. };
  34231. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  34232. get: function () {
  34233. return this._useLogarithmicDepth;
  34234. },
  34235. set: function (value) {
  34236. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34237. this._markAllSubMeshesAsMiscDirty();
  34238. },
  34239. enumerable: true,
  34240. configurable: true
  34241. });
  34242. StandardMaterial.prototype.needAlphaBlending = function () {
  34243. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  34244. };
  34245. StandardMaterial.prototype.needAlphaTesting = function () {
  34246. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  34247. };
  34248. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  34249. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  34250. };
  34251. StandardMaterial.prototype.getAlphaTestTexture = function () {
  34252. return this._diffuseTexture;
  34253. };
  34254. /**
  34255. * Child classes can use it to update shaders
  34256. */
  34257. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34258. if (useInstances === void 0) { useInstances = false; }
  34259. if (subMesh.effect && this.isFrozen) {
  34260. if (this._wasPreviouslyReady && subMesh.effect) {
  34261. return true;
  34262. }
  34263. }
  34264. if (!subMesh._materialDefines) {
  34265. subMesh._materialDefines = new StandardMaterialDefines();
  34266. }
  34267. var scene = this.getScene();
  34268. var defines = subMesh._materialDefines;
  34269. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34270. if (defines._renderId === scene.getRenderId()) {
  34271. return true;
  34272. }
  34273. }
  34274. var engine = scene.getEngine();
  34275. // Lights
  34276. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34277. // Textures
  34278. if (defines._areTexturesDirty) {
  34279. defines._needUVs = false;
  34280. defines.MAINUV1 = false;
  34281. defines.MAINUV2 = false;
  34282. if (scene.texturesEnabled) {
  34283. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34284. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  34285. return false;
  34286. }
  34287. else {
  34288. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  34289. }
  34290. }
  34291. else {
  34292. defines.DIFFUSE = false;
  34293. }
  34294. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34295. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34296. return false;
  34297. }
  34298. else {
  34299. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  34300. }
  34301. }
  34302. else {
  34303. defines.AMBIENT = false;
  34304. }
  34305. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34306. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34307. return false;
  34308. }
  34309. else {
  34310. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  34311. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34312. }
  34313. }
  34314. else {
  34315. defines.OPACITY = false;
  34316. }
  34317. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34318. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  34319. return false;
  34320. }
  34321. else {
  34322. defines._needNormals = true;
  34323. defines.REFLECTION = true;
  34324. defines.ROUGHNESS = (this._roughness > 0);
  34325. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  34326. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  34327. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  34328. switch (this._reflectionTexture.coordinatesMode) {
  34329. case BABYLON.Texture.CUBIC_MODE:
  34330. case BABYLON.Texture.INVCUBIC_MODE:
  34331. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  34332. break;
  34333. case BABYLON.Texture.EXPLICIT_MODE:
  34334. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  34335. break;
  34336. case BABYLON.Texture.PLANAR_MODE:
  34337. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  34338. break;
  34339. case BABYLON.Texture.PROJECTION_MODE:
  34340. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  34341. break;
  34342. case BABYLON.Texture.SKYBOX_MODE:
  34343. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  34344. break;
  34345. case BABYLON.Texture.SPHERICAL_MODE:
  34346. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  34347. break;
  34348. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34349. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  34350. break;
  34351. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34352. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  34353. break;
  34354. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34355. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  34356. break;
  34357. }
  34358. }
  34359. }
  34360. else {
  34361. defines.REFLECTION = false;
  34362. }
  34363. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34364. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34365. return false;
  34366. }
  34367. else {
  34368. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  34369. }
  34370. }
  34371. else {
  34372. defines.EMISSIVE = false;
  34373. }
  34374. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34375. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34376. return false;
  34377. }
  34378. else {
  34379. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  34380. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  34381. }
  34382. }
  34383. else {
  34384. defines.LIGHTMAP = false;
  34385. }
  34386. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34387. if (!this._specularTexture.isReadyOrNotBlocking()) {
  34388. return false;
  34389. }
  34390. else {
  34391. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  34392. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  34393. }
  34394. }
  34395. else {
  34396. defines.SPECULAR = false;
  34397. }
  34398. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  34399. // Bump texure can not be not blocking.
  34400. if (!this._bumpTexture.isReady()) {
  34401. return false;
  34402. }
  34403. else {
  34404. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  34405. defines.PARALLAX = this._useParallax;
  34406. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  34407. }
  34408. }
  34409. else {
  34410. defines.BUMP = false;
  34411. }
  34412. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34413. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  34414. return false;
  34415. }
  34416. else {
  34417. defines._needUVs = true;
  34418. defines.REFRACTION = true;
  34419. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  34420. }
  34421. }
  34422. else {
  34423. defines.REFRACTION = false;
  34424. }
  34425. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  34426. }
  34427. else {
  34428. defines.DIFFUSE = false;
  34429. defines.AMBIENT = false;
  34430. defines.OPACITY = false;
  34431. defines.REFLECTION = false;
  34432. defines.EMISSIVE = false;
  34433. defines.LIGHTMAP = false;
  34434. defines.BUMP = false;
  34435. defines.REFRACTION = false;
  34436. }
  34437. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  34438. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  34439. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  34440. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  34441. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  34442. }
  34443. if (defines._areImageProcessingDirty) {
  34444. if (!this._imageProcessingConfiguration.isReady()) {
  34445. return false;
  34446. }
  34447. this._imageProcessingConfiguration.prepareDefines(defines);
  34448. }
  34449. if (defines._areFresnelDirty) {
  34450. if (StandardMaterial.FresnelEnabled) {
  34451. // Fresnel
  34452. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  34453. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  34454. this._reflectionFresnelParameters) {
  34455. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  34456. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  34457. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  34458. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  34459. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  34460. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  34461. defines._needNormals = true;
  34462. defines.FRESNEL = true;
  34463. }
  34464. }
  34465. else {
  34466. defines.FRESNEL = false;
  34467. }
  34468. }
  34469. // Misc.
  34470. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34471. // Attribs
  34472. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  34473. // Values that need to be evaluated on every frame
  34474. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  34475. // Get correct effect
  34476. if (defines.isDirty) {
  34477. defines.markAsProcessed();
  34478. scene.resetCachedMaterial();
  34479. // Fallbacks
  34480. var fallbacks = new BABYLON.EffectFallbacks();
  34481. if (defines.REFLECTION) {
  34482. fallbacks.addFallback(0, "REFLECTION");
  34483. }
  34484. if (defines.SPECULAR) {
  34485. fallbacks.addFallback(0, "SPECULAR");
  34486. }
  34487. if (defines.BUMP) {
  34488. fallbacks.addFallback(0, "BUMP");
  34489. }
  34490. if (defines.PARALLAX) {
  34491. fallbacks.addFallback(1, "PARALLAX");
  34492. }
  34493. if (defines.PARALLAXOCCLUSION) {
  34494. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  34495. }
  34496. if (defines.SPECULAROVERALPHA) {
  34497. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  34498. }
  34499. if (defines.FOG) {
  34500. fallbacks.addFallback(1, "FOG");
  34501. }
  34502. if (defines.POINTSIZE) {
  34503. fallbacks.addFallback(0, "POINTSIZE");
  34504. }
  34505. if (defines.LOGARITHMICDEPTH) {
  34506. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  34507. }
  34508. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  34509. if (defines.SPECULARTERM) {
  34510. fallbacks.addFallback(0, "SPECULARTERM");
  34511. }
  34512. if (defines.DIFFUSEFRESNEL) {
  34513. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  34514. }
  34515. if (defines.OPACITYFRESNEL) {
  34516. fallbacks.addFallback(2, "OPACITYFRESNEL");
  34517. }
  34518. if (defines.REFLECTIONFRESNEL) {
  34519. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  34520. }
  34521. if (defines.EMISSIVEFRESNEL) {
  34522. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  34523. }
  34524. if (defines.FRESNEL) {
  34525. fallbacks.addFallback(4, "FRESNEL");
  34526. }
  34527. //Attributes
  34528. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34529. if (defines.NORMAL) {
  34530. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34531. }
  34532. if (defines.UV1) {
  34533. attribs.push(BABYLON.VertexBuffer.UVKind);
  34534. }
  34535. if (defines.UV2) {
  34536. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34537. }
  34538. if (defines.VERTEXCOLOR) {
  34539. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34540. }
  34541. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  34542. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  34543. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  34544. var shaderName = "default";
  34545. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  34546. "vFogInfos", "vFogColor", "pointSize",
  34547. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  34548. "mBones",
  34549. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  34550. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  34551. "logarithmicDepthConstant", "vTangentSpaceParams"
  34552. ];
  34553. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  34554. var uniformBuffers = ["Material", "Scene"];
  34555. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  34556. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  34557. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  34558. uniformsNames: uniforms,
  34559. uniformBuffersNames: uniformBuffers,
  34560. samplers: samplers,
  34561. defines: defines,
  34562. maxSimultaneousLights: this._maxSimultaneousLights
  34563. });
  34564. if (this.customShaderNameResolve) {
  34565. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  34566. }
  34567. var join = defines.toString();
  34568. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  34569. attributes: attribs,
  34570. uniformsNames: uniforms,
  34571. uniformBuffersNames: uniformBuffers,
  34572. samplers: samplers,
  34573. defines: join,
  34574. fallbacks: fallbacks,
  34575. onCompiled: this.onCompiled,
  34576. onError: this.onError,
  34577. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  34578. }, engine), defines);
  34579. this.buildUniformLayout();
  34580. }
  34581. if (!subMesh.effect || !subMesh.effect.isReady()) {
  34582. return false;
  34583. }
  34584. defines._renderId = scene.getRenderId();
  34585. this._wasPreviouslyReady = true;
  34586. return true;
  34587. };
  34588. StandardMaterial.prototype.buildUniformLayout = function () {
  34589. // Order is important !
  34590. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  34591. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  34592. this._uniformBuffer.addUniform("opacityParts", 4);
  34593. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  34594. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  34595. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  34596. this._uniformBuffer.addUniform("refractionRightColor", 4);
  34597. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  34598. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  34599. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  34600. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  34601. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  34602. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  34603. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  34604. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  34605. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  34606. this._uniformBuffer.addUniform("vBumpInfos", 3);
  34607. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  34608. this._uniformBuffer.addUniform("ambientMatrix", 16);
  34609. this._uniformBuffer.addUniform("opacityMatrix", 16);
  34610. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  34611. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  34612. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  34613. this._uniformBuffer.addUniform("specularMatrix", 16);
  34614. this._uniformBuffer.addUniform("bumpMatrix", 16);
  34615. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  34616. this._uniformBuffer.addUniform("refractionMatrix", 16);
  34617. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  34618. this._uniformBuffer.addUniform("vSpecularColor", 4);
  34619. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  34620. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  34621. this._uniformBuffer.addUniform("pointSize", 1);
  34622. this._uniformBuffer.create();
  34623. };
  34624. StandardMaterial.prototype.unbind = function () {
  34625. if (this._activeEffect) {
  34626. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  34627. this._activeEffect.setTexture("reflection2DSampler", null);
  34628. }
  34629. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  34630. this._activeEffect.setTexture("refraction2DSampler", null);
  34631. }
  34632. }
  34633. _super.prototype.unbind.call(this);
  34634. };
  34635. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34636. var scene = this.getScene();
  34637. var defines = subMesh._materialDefines;
  34638. if (!defines) {
  34639. return;
  34640. }
  34641. var effect = subMesh.effect;
  34642. if (!effect) {
  34643. return;
  34644. }
  34645. this._activeEffect = effect;
  34646. // Matrices
  34647. this.bindOnlyWorldMatrix(world);
  34648. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  34649. // Bones
  34650. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  34651. if (mustRebind) {
  34652. this._uniformBuffer.bindToEffect(effect, "Material");
  34653. this.bindViewProjection(effect);
  34654. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  34655. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  34656. // Fresnel
  34657. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  34658. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  34659. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  34660. }
  34661. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  34662. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  34663. }
  34664. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  34665. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  34666. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  34667. }
  34668. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  34669. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  34670. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  34671. }
  34672. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  34673. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  34674. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  34675. }
  34676. }
  34677. // Textures
  34678. if (scene.texturesEnabled) {
  34679. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34680. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  34681. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  34682. }
  34683. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34684. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  34685. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  34686. }
  34687. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34688. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  34689. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  34690. }
  34691. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34692. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  34693. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  34694. }
  34695. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34696. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  34697. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  34698. }
  34699. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34700. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  34701. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  34702. }
  34703. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34704. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  34705. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  34706. }
  34707. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34708. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  34709. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  34710. if (scene._mirroredCameraPosition) {
  34711. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  34712. }
  34713. else {
  34714. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34715. }
  34716. }
  34717. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34718. var depth = 1.0;
  34719. if (!this._refractionTexture.isCube) {
  34720. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  34721. if (this._refractionTexture.depth) {
  34722. depth = this._refractionTexture.depth;
  34723. }
  34724. }
  34725. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  34726. }
  34727. }
  34728. // Point size
  34729. if (this.pointsCloud) {
  34730. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34731. }
  34732. if (defines.SPECULARTERM) {
  34733. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  34734. }
  34735. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  34736. // Diffuse
  34737. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  34738. }
  34739. // Textures
  34740. if (scene.texturesEnabled) {
  34741. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34742. effect.setTexture("diffuseSampler", this._diffuseTexture);
  34743. }
  34744. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34745. effect.setTexture("ambientSampler", this._ambientTexture);
  34746. }
  34747. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34748. effect.setTexture("opacitySampler", this._opacityTexture);
  34749. }
  34750. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34751. if (this._reflectionTexture.isCube) {
  34752. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  34753. }
  34754. else {
  34755. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  34756. }
  34757. }
  34758. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34759. effect.setTexture("emissiveSampler", this._emissiveTexture);
  34760. }
  34761. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34762. effect.setTexture("lightmapSampler", this._lightmapTexture);
  34763. }
  34764. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34765. effect.setTexture("specularSampler", this._specularTexture);
  34766. }
  34767. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34768. effect.setTexture("bumpSampler", this._bumpTexture);
  34769. }
  34770. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34771. var depth = 1.0;
  34772. if (this._refractionTexture.isCube) {
  34773. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  34774. }
  34775. else {
  34776. effect.setTexture("refraction2DSampler", this._refractionTexture);
  34777. }
  34778. }
  34779. }
  34780. // Clip plane
  34781. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  34782. // Colors
  34783. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  34784. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  34785. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34786. }
  34787. if (mustRebind || !this.isFrozen) {
  34788. // Lights
  34789. if (scene.lightsEnabled && !this._disableLighting) {
  34790. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  34791. }
  34792. // View
  34793. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  34794. this.bindView(effect);
  34795. }
  34796. // Fog
  34797. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  34798. // Morph targets
  34799. if (defines.NUM_MORPH_INFLUENCERS) {
  34800. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  34801. }
  34802. // Log. depth
  34803. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  34804. // image processing
  34805. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  34806. this._imageProcessingConfiguration.bind(this._activeEffect);
  34807. }
  34808. }
  34809. this._uniformBuffer.update();
  34810. this._afterBind(mesh, this._activeEffect);
  34811. };
  34812. StandardMaterial.prototype.getAnimatables = function () {
  34813. var results = [];
  34814. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  34815. results.push(this._diffuseTexture);
  34816. }
  34817. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34818. results.push(this._ambientTexture);
  34819. }
  34820. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34821. results.push(this._opacityTexture);
  34822. }
  34823. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34824. results.push(this._reflectionTexture);
  34825. }
  34826. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34827. results.push(this._emissiveTexture);
  34828. }
  34829. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  34830. results.push(this._specularTexture);
  34831. }
  34832. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34833. results.push(this._bumpTexture);
  34834. }
  34835. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34836. results.push(this._lightmapTexture);
  34837. }
  34838. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34839. results.push(this._refractionTexture);
  34840. }
  34841. return results;
  34842. };
  34843. StandardMaterial.prototype.getActiveTextures = function () {
  34844. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34845. if (this._diffuseTexture) {
  34846. activeTextures.push(this._diffuseTexture);
  34847. }
  34848. if (this._ambientTexture) {
  34849. activeTextures.push(this._ambientTexture);
  34850. }
  34851. if (this._opacityTexture) {
  34852. activeTextures.push(this._opacityTexture);
  34853. }
  34854. if (this._reflectionTexture) {
  34855. activeTextures.push(this._reflectionTexture);
  34856. }
  34857. if (this._emissiveTexture) {
  34858. activeTextures.push(this._emissiveTexture);
  34859. }
  34860. if (this._specularTexture) {
  34861. activeTextures.push(this._specularTexture);
  34862. }
  34863. if (this._bumpTexture) {
  34864. activeTextures.push(this._bumpTexture);
  34865. }
  34866. if (this._lightmapTexture) {
  34867. activeTextures.push(this._lightmapTexture);
  34868. }
  34869. if (this._refractionTexture) {
  34870. activeTextures.push(this._refractionTexture);
  34871. }
  34872. return activeTextures;
  34873. };
  34874. StandardMaterial.prototype.hasTexture = function (texture) {
  34875. if (_super.prototype.hasTexture.call(this, texture)) {
  34876. return true;
  34877. }
  34878. if (this._diffuseTexture === texture) {
  34879. return true;
  34880. }
  34881. if (this._ambientTexture === texture) {
  34882. return true;
  34883. }
  34884. if (this._opacityTexture === texture) {
  34885. return true;
  34886. }
  34887. if (this._reflectionTexture === texture) {
  34888. return true;
  34889. }
  34890. if (this._emissiveTexture === texture) {
  34891. return true;
  34892. }
  34893. if (this._specularTexture === texture) {
  34894. return true;
  34895. }
  34896. if (this._bumpTexture === texture) {
  34897. return true;
  34898. }
  34899. if (this._lightmapTexture === texture) {
  34900. return true;
  34901. }
  34902. if (this._refractionTexture === texture) {
  34903. return true;
  34904. }
  34905. return false;
  34906. };
  34907. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34908. if (forceDisposeTextures) {
  34909. if (this._diffuseTexture) {
  34910. this._diffuseTexture.dispose();
  34911. }
  34912. if (this._ambientTexture) {
  34913. this._ambientTexture.dispose();
  34914. }
  34915. if (this._opacityTexture) {
  34916. this._opacityTexture.dispose();
  34917. }
  34918. if (this._reflectionTexture) {
  34919. this._reflectionTexture.dispose();
  34920. }
  34921. if (this._emissiveTexture) {
  34922. this._emissiveTexture.dispose();
  34923. }
  34924. if (this._specularTexture) {
  34925. this._specularTexture.dispose();
  34926. }
  34927. if (this._bumpTexture) {
  34928. this._bumpTexture.dispose();
  34929. }
  34930. if (this._lightmapTexture) {
  34931. this._lightmapTexture.dispose();
  34932. }
  34933. if (this._refractionTexture) {
  34934. this._refractionTexture.dispose();
  34935. }
  34936. }
  34937. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34938. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34939. }
  34940. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34941. };
  34942. StandardMaterial.prototype.clone = function (name) {
  34943. var _this = this;
  34944. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  34945. result.name = name;
  34946. result.id = name;
  34947. return result;
  34948. };
  34949. StandardMaterial.prototype.serialize = function () {
  34950. return BABYLON.SerializationHelper.Serialize(this);
  34951. };
  34952. // Statics
  34953. StandardMaterial.Parse = function (source, scene, rootUrl) {
  34954. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  34955. };
  34956. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  34957. get: function () {
  34958. return StandardMaterial._DiffuseTextureEnabled;
  34959. },
  34960. set: function (value) {
  34961. if (StandardMaterial._DiffuseTextureEnabled === value) {
  34962. return;
  34963. }
  34964. StandardMaterial._DiffuseTextureEnabled = value;
  34965. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34966. },
  34967. enumerable: true,
  34968. configurable: true
  34969. });
  34970. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  34971. get: function () {
  34972. return StandardMaterial._AmbientTextureEnabled;
  34973. },
  34974. set: function (value) {
  34975. if (StandardMaterial._AmbientTextureEnabled === value) {
  34976. return;
  34977. }
  34978. StandardMaterial._AmbientTextureEnabled = value;
  34979. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34980. },
  34981. enumerable: true,
  34982. configurable: true
  34983. });
  34984. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  34985. get: function () {
  34986. return StandardMaterial._OpacityTextureEnabled;
  34987. },
  34988. set: function (value) {
  34989. if (StandardMaterial._OpacityTextureEnabled === value) {
  34990. return;
  34991. }
  34992. StandardMaterial._OpacityTextureEnabled = value;
  34993. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34994. },
  34995. enumerable: true,
  34996. configurable: true
  34997. });
  34998. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  34999. get: function () {
  35000. return StandardMaterial._ReflectionTextureEnabled;
  35001. },
  35002. set: function (value) {
  35003. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35004. return;
  35005. }
  35006. StandardMaterial._ReflectionTextureEnabled = value;
  35007. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35008. },
  35009. enumerable: true,
  35010. configurable: true
  35011. });
  35012. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35013. get: function () {
  35014. return StandardMaterial._EmissiveTextureEnabled;
  35015. },
  35016. set: function (value) {
  35017. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35018. return;
  35019. }
  35020. StandardMaterial._EmissiveTextureEnabled = value;
  35021. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35022. },
  35023. enumerable: true,
  35024. configurable: true
  35025. });
  35026. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35027. get: function () {
  35028. return StandardMaterial._SpecularTextureEnabled;
  35029. },
  35030. set: function (value) {
  35031. if (StandardMaterial._SpecularTextureEnabled === value) {
  35032. return;
  35033. }
  35034. StandardMaterial._SpecularTextureEnabled = value;
  35035. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35036. },
  35037. enumerable: true,
  35038. configurable: true
  35039. });
  35040. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35041. get: function () {
  35042. return StandardMaterial._BumpTextureEnabled;
  35043. },
  35044. set: function (value) {
  35045. if (StandardMaterial._BumpTextureEnabled === value) {
  35046. return;
  35047. }
  35048. StandardMaterial._BumpTextureEnabled = value;
  35049. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35050. },
  35051. enumerable: true,
  35052. configurable: true
  35053. });
  35054. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35055. get: function () {
  35056. return StandardMaterial._LightmapTextureEnabled;
  35057. },
  35058. set: function (value) {
  35059. if (StandardMaterial._LightmapTextureEnabled === value) {
  35060. return;
  35061. }
  35062. StandardMaterial._LightmapTextureEnabled = value;
  35063. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35064. },
  35065. enumerable: true,
  35066. configurable: true
  35067. });
  35068. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35069. get: function () {
  35070. return StandardMaterial._RefractionTextureEnabled;
  35071. },
  35072. set: function (value) {
  35073. if (StandardMaterial._RefractionTextureEnabled === value) {
  35074. return;
  35075. }
  35076. StandardMaterial._RefractionTextureEnabled = value;
  35077. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35078. },
  35079. enumerable: true,
  35080. configurable: true
  35081. });
  35082. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35083. get: function () {
  35084. return StandardMaterial._ColorGradingTextureEnabled;
  35085. },
  35086. set: function (value) {
  35087. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35088. return;
  35089. }
  35090. StandardMaterial._ColorGradingTextureEnabled = value;
  35091. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35092. },
  35093. enumerable: true,
  35094. configurable: true
  35095. });
  35096. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35097. get: function () {
  35098. return StandardMaterial._FresnelEnabled;
  35099. },
  35100. set: function (value) {
  35101. if (StandardMaterial._FresnelEnabled === value) {
  35102. return;
  35103. }
  35104. StandardMaterial._FresnelEnabled = value;
  35105. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35106. },
  35107. enumerable: true,
  35108. configurable: true
  35109. });
  35110. // Flags used to enable or disable a type of texture for all Standard Materials
  35111. StandardMaterial._DiffuseTextureEnabled = true;
  35112. StandardMaterial._AmbientTextureEnabled = true;
  35113. StandardMaterial._OpacityTextureEnabled = true;
  35114. StandardMaterial._ReflectionTextureEnabled = true;
  35115. StandardMaterial._EmissiveTextureEnabled = true;
  35116. StandardMaterial._SpecularTextureEnabled = true;
  35117. StandardMaterial._BumpTextureEnabled = true;
  35118. StandardMaterial._LightmapTextureEnabled = true;
  35119. StandardMaterial._RefractionTextureEnabled = true;
  35120. StandardMaterial._ColorGradingTextureEnabled = true;
  35121. StandardMaterial._FresnelEnabled = true;
  35122. __decorate([
  35123. BABYLON.serializeAsTexture("diffuseTexture")
  35124. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35125. __decorate([
  35126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35127. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35128. __decorate([
  35129. BABYLON.serializeAsTexture("ambientTexture")
  35130. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35131. __decorate([
  35132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35133. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35134. __decorate([
  35135. BABYLON.serializeAsTexture("opacityTexture")
  35136. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35137. __decorate([
  35138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35139. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35140. __decorate([
  35141. BABYLON.serializeAsTexture("reflectionTexture")
  35142. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35143. __decorate([
  35144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35145. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35146. __decorate([
  35147. BABYLON.serializeAsTexture("emissiveTexture")
  35148. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35149. __decorate([
  35150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35151. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35152. __decorate([
  35153. BABYLON.serializeAsTexture("specularTexture")
  35154. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35155. __decorate([
  35156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35157. ], StandardMaterial.prototype, "specularTexture", void 0);
  35158. __decorate([
  35159. BABYLON.serializeAsTexture("bumpTexture")
  35160. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35161. __decorate([
  35162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35163. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35164. __decorate([
  35165. BABYLON.serializeAsTexture("lightmapTexture")
  35166. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35167. __decorate([
  35168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35169. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35170. __decorate([
  35171. BABYLON.serializeAsTexture("refractionTexture")
  35172. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35173. __decorate([
  35174. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35175. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35176. __decorate([
  35177. BABYLON.serializeAsColor3("ambient")
  35178. ], StandardMaterial.prototype, "ambientColor", void 0);
  35179. __decorate([
  35180. BABYLON.serializeAsColor3("diffuse")
  35181. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35182. __decorate([
  35183. BABYLON.serializeAsColor3("specular")
  35184. ], StandardMaterial.prototype, "specularColor", void 0);
  35185. __decorate([
  35186. BABYLON.serializeAsColor3("emissive")
  35187. ], StandardMaterial.prototype, "emissiveColor", void 0);
  35188. __decorate([
  35189. BABYLON.serialize()
  35190. ], StandardMaterial.prototype, "specularPower", void 0);
  35191. __decorate([
  35192. BABYLON.serialize("useAlphaFromDiffuseTexture")
  35193. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  35194. __decorate([
  35195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35196. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  35197. __decorate([
  35198. BABYLON.serialize("useEmissiveAsIllumination")
  35199. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  35200. __decorate([
  35201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35202. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  35203. __decorate([
  35204. BABYLON.serialize("linkEmissiveWithDiffuse")
  35205. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  35206. __decorate([
  35207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35208. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  35209. __decorate([
  35210. BABYLON.serialize("useSpecularOverAlpha")
  35211. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  35212. __decorate([
  35213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35214. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  35215. __decorate([
  35216. BABYLON.serialize("useReflectionOverAlpha")
  35217. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  35218. __decorate([
  35219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35220. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  35221. __decorate([
  35222. BABYLON.serialize("disableLighting")
  35223. ], StandardMaterial.prototype, "_disableLighting", void 0);
  35224. __decorate([
  35225. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35226. ], StandardMaterial.prototype, "disableLighting", void 0);
  35227. __decorate([
  35228. BABYLON.serialize("useParallax")
  35229. ], StandardMaterial.prototype, "_useParallax", void 0);
  35230. __decorate([
  35231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35232. ], StandardMaterial.prototype, "useParallax", void 0);
  35233. __decorate([
  35234. BABYLON.serialize("useParallaxOcclusion")
  35235. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  35236. __decorate([
  35237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35238. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  35239. __decorate([
  35240. BABYLON.serialize()
  35241. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  35242. __decorate([
  35243. BABYLON.serialize("roughness")
  35244. ], StandardMaterial.prototype, "_roughness", void 0);
  35245. __decorate([
  35246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35247. ], StandardMaterial.prototype, "roughness", void 0);
  35248. __decorate([
  35249. BABYLON.serialize()
  35250. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  35251. __decorate([
  35252. BABYLON.serialize()
  35253. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  35254. __decorate([
  35255. BABYLON.serialize("useLightmapAsShadowmap")
  35256. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  35257. __decorate([
  35258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35259. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35260. __decorate([
  35261. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  35262. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  35263. __decorate([
  35264. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35265. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  35266. __decorate([
  35267. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  35268. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  35269. __decorate([
  35270. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35271. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  35272. __decorate([
  35273. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  35274. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  35275. __decorate([
  35276. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35277. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  35278. __decorate([
  35279. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  35280. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  35281. __decorate([
  35282. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35283. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  35284. __decorate([
  35285. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  35286. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  35287. __decorate([
  35288. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35289. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  35290. __decorate([
  35291. BABYLON.serialize("useReflectionFresnelFromSpecular")
  35292. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  35293. __decorate([
  35294. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35295. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  35296. __decorate([
  35297. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  35298. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  35299. __decorate([
  35300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35301. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  35302. __decorate([
  35303. BABYLON.serialize("maxSimultaneousLights")
  35304. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  35305. __decorate([
  35306. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35307. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  35308. __decorate([
  35309. BABYLON.serialize("invertNormalMapX")
  35310. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  35311. __decorate([
  35312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35313. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  35314. __decorate([
  35315. BABYLON.serialize("invertNormalMapY")
  35316. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  35317. __decorate([
  35318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35319. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  35320. __decorate([
  35321. BABYLON.serialize("twoSidedLighting")
  35322. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  35323. __decorate([
  35324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35325. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  35326. __decorate([
  35327. BABYLON.serialize()
  35328. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  35329. return StandardMaterial;
  35330. }(BABYLON.PushMaterial));
  35331. BABYLON.StandardMaterial = StandardMaterial;
  35332. })(BABYLON || (BABYLON = {}));
  35333. //# sourceMappingURL=babylon.standardMaterial.js.map
  35334. var BABYLON;
  35335. (function (BABYLON) {
  35336. var PBRMaterialDefines = /** @class */ (function (_super) {
  35337. __extends(PBRMaterialDefines, _super);
  35338. function PBRMaterialDefines() {
  35339. var _this = _super.call(this) || this;
  35340. _this.PBR = true;
  35341. _this.MAINUV1 = false;
  35342. _this.MAINUV2 = false;
  35343. _this.UV1 = false;
  35344. _this.UV2 = false;
  35345. _this.ALBEDO = false;
  35346. _this.ALBEDODIRECTUV = 0;
  35347. _this.VERTEXCOLOR = false;
  35348. _this.AMBIENT = false;
  35349. _this.AMBIENTDIRECTUV = 0;
  35350. _this.AMBIENTINGRAYSCALE = false;
  35351. _this.OPACITY = false;
  35352. _this.VERTEXALPHA = false;
  35353. _this.OPACITYDIRECTUV = 0;
  35354. _this.OPACITYRGB = false;
  35355. _this.ALPHATEST = false;
  35356. _this.DEPTHPREPASS = false;
  35357. _this.ALPHABLEND = false;
  35358. _this.ALPHAFROMALBEDO = false;
  35359. _this.ALPHATESTVALUE = 0.5;
  35360. _this.SPECULAROVERALPHA = false;
  35361. _this.RADIANCEOVERALPHA = false;
  35362. _this.ALPHAFRESNEL = false;
  35363. _this.PREMULTIPLYALPHA = false;
  35364. _this.EMISSIVE = false;
  35365. _this.EMISSIVEDIRECTUV = 0;
  35366. _this.REFLECTIVITY = false;
  35367. _this.REFLECTIVITYDIRECTUV = 0;
  35368. _this.SPECULARTERM = false;
  35369. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  35370. _this.MICROSURFACEAUTOMATIC = false;
  35371. _this.LODBASEDMICROSFURACE = false;
  35372. _this.MICROSURFACEMAP = false;
  35373. _this.MICROSURFACEMAPDIRECTUV = 0;
  35374. _this.METALLICWORKFLOW = false;
  35375. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  35376. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  35377. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  35378. _this.AOSTOREINMETALMAPRED = false;
  35379. _this.ENVIRONMENTBRDF = false;
  35380. _this.NORMAL = false;
  35381. _this.TANGENT = false;
  35382. _this.BUMP = false;
  35383. _this.BUMPDIRECTUV = 0;
  35384. _this.PARALLAX = false;
  35385. _this.PARALLAXOCCLUSION = false;
  35386. _this.NORMALXYSCALE = true;
  35387. _this.LIGHTMAP = false;
  35388. _this.LIGHTMAPDIRECTUV = 0;
  35389. _this.USELIGHTMAPASSHADOWMAP = false;
  35390. _this.REFLECTION = false;
  35391. _this.REFLECTIONMAP_3D = false;
  35392. _this.REFLECTIONMAP_SPHERICAL = false;
  35393. _this.REFLECTIONMAP_PLANAR = false;
  35394. _this.REFLECTIONMAP_CUBIC = false;
  35395. _this.REFLECTIONMAP_PROJECTION = false;
  35396. _this.REFLECTIONMAP_SKYBOX = false;
  35397. _this.REFLECTIONMAP_EXPLICIT = false;
  35398. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35399. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35400. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35401. _this.INVERTCUBICMAP = false;
  35402. _this.USESPHERICALFROMREFLECTIONMAP = false;
  35403. _this.USESPHERICALINVERTEX = false;
  35404. _this.REFLECTIONMAP_OPPOSITEZ = false;
  35405. _this.LODINREFLECTIONALPHA = false;
  35406. _this.GAMMAREFLECTION = false;
  35407. _this.RADIANCEOCCLUSION = false;
  35408. _this.HORIZONOCCLUSION = false;
  35409. _this.REFRACTION = false;
  35410. _this.REFRACTIONMAP_3D = false;
  35411. _this.REFRACTIONMAP_OPPOSITEZ = false;
  35412. _this.LODINREFRACTIONALPHA = false;
  35413. _this.GAMMAREFRACTION = false;
  35414. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  35415. _this.INSTANCES = false;
  35416. _this.NUM_BONE_INFLUENCERS = 0;
  35417. _this.BonesPerMesh = 0;
  35418. _this.NONUNIFORMSCALING = false;
  35419. _this.MORPHTARGETS = false;
  35420. _this.MORPHTARGETS_NORMAL = false;
  35421. _this.MORPHTARGETS_TANGENT = false;
  35422. _this.NUM_MORPH_INFLUENCERS = 0;
  35423. _this.IMAGEPROCESSING = false;
  35424. _this.VIGNETTE = false;
  35425. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35426. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35427. _this.TONEMAPPING = false;
  35428. _this.CONTRAST = false;
  35429. _this.COLORCURVES = false;
  35430. _this.COLORGRADING = false;
  35431. _this.COLORGRADING3D = false;
  35432. _this.SAMPLER3DGREENDEPTH = false;
  35433. _this.SAMPLER3DBGRMAP = false;
  35434. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35435. _this.EXPOSURE = false;
  35436. _this.USEPHYSICALLIGHTFALLOFF = false;
  35437. _this.TWOSIDEDLIGHTING = false;
  35438. _this.SHADOWFLOAT = false;
  35439. _this.CLIPPLANE = false;
  35440. _this.POINTSIZE = false;
  35441. _this.FOG = false;
  35442. _this.LOGARITHMICDEPTH = false;
  35443. _this.FORCENORMALFORWARD = false;
  35444. _this.rebuild();
  35445. return _this;
  35446. }
  35447. PBRMaterialDefines.prototype.reset = function () {
  35448. _super.prototype.reset.call(this);
  35449. this.ALPHATESTVALUE = 0.5;
  35450. this.PBR = true;
  35451. };
  35452. return PBRMaterialDefines;
  35453. }(BABYLON.MaterialDefines));
  35454. /**
  35455. * The Physically based material base class of BJS.
  35456. *
  35457. * This offers the main features of a standard PBR material.
  35458. * For more information, please refer to the documentation :
  35459. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35460. */
  35461. var PBRBaseMaterial = /** @class */ (function (_super) {
  35462. __extends(PBRBaseMaterial, _super);
  35463. /**
  35464. * Instantiates a new PBRMaterial instance.
  35465. *
  35466. * @param name The material name
  35467. * @param scene The scene the material will be use in.
  35468. */
  35469. function PBRBaseMaterial(name, scene) {
  35470. var _this = _super.call(this, name, scene) || this;
  35471. /**
  35472. * Intensity of the direct lights e.g. the four lights available in your scene.
  35473. * This impacts both the direct diffuse and specular highlights.
  35474. */
  35475. _this._directIntensity = 1.0;
  35476. /**
  35477. * Intensity of the emissive part of the material.
  35478. * This helps controlling the emissive effect without modifying the emissive color.
  35479. */
  35480. _this._emissiveIntensity = 1.0;
  35481. /**
  35482. * Intensity of the environment e.g. how much the environment will light the object
  35483. * either through harmonics for rough material or through the refelction for shiny ones.
  35484. */
  35485. _this._environmentIntensity = 1.0;
  35486. /**
  35487. * This is a special control allowing the reduction of the specular highlights coming from the
  35488. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35489. */
  35490. _this._specularIntensity = 1.0;
  35491. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  35492. /**
  35493. * Debug Control allowing disabling the bump map on this material.
  35494. */
  35495. _this._disableBumpMap = false;
  35496. /**
  35497. * AKA Occlusion Texture Intensity in other nomenclature.
  35498. */
  35499. _this._ambientTextureStrength = 1.0;
  35500. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  35501. /**
  35502. * AKA Diffuse Color in other nomenclature.
  35503. */
  35504. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  35505. /**
  35506. * AKA Specular Color in other nomenclature.
  35507. */
  35508. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35509. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  35510. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  35511. /**
  35512. * AKA Glossiness in other nomenclature.
  35513. */
  35514. _this._microSurface = 0.9;
  35515. /**
  35516. * source material index of refraction (IOR)' / 'destination material IOR.
  35517. */
  35518. _this._indexOfRefraction = 0.66;
  35519. /**
  35520. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35521. */
  35522. _this._invertRefractionY = false;
  35523. /**
  35524. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35525. * Materials half opaque for instance using refraction could benefit from this control.
  35526. */
  35527. _this._linkRefractionWithTransparency = false;
  35528. _this._useLightmapAsShadowmap = false;
  35529. /**
  35530. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  35531. * makes the reflect vector face the model (under horizon).
  35532. */
  35533. _this._useHorizonOcclusion = false; // USEHORIZONOCCLUSION
  35534. /**
  35535. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  35536. * too much the area relying on ambient texture to define their ambient occlusion.
  35537. */
  35538. _this._useRadianceOcclusion = false;
  35539. /**
  35540. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  35541. */
  35542. _this._useAlphaFromAlbedoTexture = false;
  35543. /**
  35544. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35545. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35546. */
  35547. _this._useSpecularOverAlpha = true;
  35548. /**
  35549. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35550. */
  35551. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  35552. /**
  35553. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35554. */
  35555. _this._useRoughnessFromMetallicTextureAlpha = true;
  35556. /**
  35557. * Specifies if the metallic texture contains the roughness information in its green channel.
  35558. */
  35559. _this._useRoughnessFromMetallicTextureGreen = false;
  35560. /**
  35561. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35562. */
  35563. _this._useMetallnessFromMetallicTextureBlue = false;
  35564. /**
  35565. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35566. */
  35567. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  35568. /**
  35569. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35570. */
  35571. _this._useAmbientInGrayScale = false;
  35572. /**
  35573. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35574. * The material will try to infer what glossiness each pixel should be.
  35575. */
  35576. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  35577. /**
  35578. * BJS is using an harcoded light falloff based on a manually sets up range.
  35579. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35580. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35581. */
  35582. _this._usePhysicalLightFalloff = true;
  35583. /**
  35584. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35585. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35586. */
  35587. _this._useRadianceOverAlpha = true;
  35588. /**
  35589. * Allows using the bump map in parallax mode.
  35590. */
  35591. _this._useParallax = false;
  35592. /**
  35593. * Allows using the bump map in parallax occlusion mode.
  35594. */
  35595. _this._useParallaxOcclusion = false;
  35596. /**
  35597. * Controls the scale bias of the parallax mode.
  35598. */
  35599. _this._parallaxScaleBias = 0.05;
  35600. /**
  35601. * If sets to true, disables all the lights affecting the material.
  35602. */
  35603. _this._disableLighting = false;
  35604. /**
  35605. * Number of Simultaneous lights allowed on the material.
  35606. */
  35607. _this._maxSimultaneousLights = 4;
  35608. /**
  35609. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  35610. */
  35611. _this._invertNormalMapX = false;
  35612. /**
  35613. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  35614. */
  35615. _this._invertNormalMapY = false;
  35616. /**
  35617. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35618. */
  35619. _this._twoSidedLighting = false;
  35620. /**
  35621. * Defines the alpha limits in alpha test mode.
  35622. */
  35623. _this._alphaCutOff = 0.4;
  35624. /**
  35625. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35626. */
  35627. _this._forceAlphaTest = false;
  35628. /**
  35629. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35630. * And/Or occlude the blended part.
  35631. */
  35632. _this._useAlphaFresnel = false;
  35633. /**
  35634. * The transparency mode of the material.
  35635. */
  35636. _this._transparencyMode = null;
  35637. /**
  35638. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  35639. * from cos thetav and roughness:
  35640. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  35641. */
  35642. _this._environmentBRDFTexture = null;
  35643. /**
  35644. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  35645. */
  35646. _this._forceIrradianceInFragment = false;
  35647. /**
  35648. * Force normal to face away from face.
  35649. * (Temporary internal fix to remove before 3.1)
  35650. */
  35651. _this._forceNormalForward = false;
  35652. _this._renderTargets = new BABYLON.SmartArray(16);
  35653. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35654. // Setup the default processing configuration to the scene.
  35655. _this._attachImageProcessingConfiguration(null);
  35656. _this.getRenderTargetTextures = function () {
  35657. _this._renderTargets.reset();
  35658. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35659. _this._renderTargets.push(_this._reflectionTexture);
  35660. }
  35661. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35662. _this._renderTargets.push(_this._refractionTexture);
  35663. }
  35664. return _this._renderTargets;
  35665. };
  35666. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  35667. return _this;
  35668. }
  35669. /**
  35670. * Attaches a new image processing configuration to the PBR Material.
  35671. * @param configuration
  35672. */
  35673. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35674. var _this = this;
  35675. if (configuration === this._imageProcessingConfiguration) {
  35676. return;
  35677. }
  35678. // Detaches observer.
  35679. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35680. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35681. }
  35682. // Pick the scene configuration if needed.
  35683. if (!configuration) {
  35684. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35685. }
  35686. else {
  35687. this._imageProcessingConfiguration = configuration;
  35688. }
  35689. // Attaches observer.
  35690. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35691. _this._markAllSubMeshesAsImageProcessingDirty();
  35692. });
  35693. };
  35694. PBRBaseMaterial.prototype.getClassName = function () {
  35695. return "PBRBaseMaterial";
  35696. };
  35697. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  35698. get: function () {
  35699. return this._useLogarithmicDepth;
  35700. },
  35701. set: function (value) {
  35702. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35703. },
  35704. enumerable: true,
  35705. configurable: true
  35706. });
  35707. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  35708. /**
  35709. * Gets the current transparency mode.
  35710. */
  35711. get: function () {
  35712. return this._transparencyMode;
  35713. },
  35714. /**
  35715. * Sets the transparency mode of the material.
  35716. */
  35717. set: function (value) {
  35718. if (this._transparencyMode === value) {
  35719. return;
  35720. }
  35721. this._transparencyMode = value;
  35722. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  35723. this._markAllSubMeshesAsTexturesDirty();
  35724. },
  35725. enumerable: true,
  35726. configurable: true
  35727. });
  35728. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  35729. /**
  35730. * Returns true if alpha blending should be disabled.
  35731. */
  35732. get: function () {
  35733. return (this._linkRefractionWithTransparency ||
  35734. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  35735. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  35736. },
  35737. enumerable: true,
  35738. configurable: true
  35739. });
  35740. /**
  35741. * Specifies whether or not this material should be rendered in alpha blend mode.
  35742. */
  35743. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  35744. if (this._disableAlphaBlending) {
  35745. return false;
  35746. }
  35747. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  35748. };
  35749. /**
  35750. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  35751. */
  35752. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  35753. if (this._disableAlphaBlending) {
  35754. return false;
  35755. }
  35756. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  35757. };
  35758. /**
  35759. * Specifies whether or not this material should be rendered in alpha test mode.
  35760. */
  35761. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  35762. if (this._forceAlphaTest) {
  35763. return true;
  35764. }
  35765. if (this._linkRefractionWithTransparency) {
  35766. return false;
  35767. }
  35768. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35769. };
  35770. /**
  35771. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  35772. */
  35773. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35774. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35775. };
  35776. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  35777. return this._albedoTexture;
  35778. };
  35779. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35780. var _this = this;
  35781. if (subMesh.effect && this.isFrozen) {
  35782. if (this._wasPreviouslyReady) {
  35783. return true;
  35784. }
  35785. }
  35786. if (!subMesh._materialDefines) {
  35787. subMesh._materialDefines = new PBRMaterialDefines();
  35788. }
  35789. var scene = this.getScene();
  35790. var defines = subMesh._materialDefines;
  35791. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35792. if (defines._renderId === scene.getRenderId()) {
  35793. return true;
  35794. }
  35795. }
  35796. var engine = scene.getEngine();
  35797. // Lights
  35798. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35799. defines._needNormals = true;
  35800. // Textures
  35801. if (defines._areTexturesDirty) {
  35802. defines._needUVs = false;
  35803. if (scene.texturesEnabled) {
  35804. if (scene.getEngine().getCaps().textureLOD) {
  35805. defines.LODBASEDMICROSFURACE = true;
  35806. }
  35807. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35808. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  35809. return false;
  35810. }
  35811. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  35812. }
  35813. else {
  35814. defines.ALBEDO = false;
  35815. }
  35816. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35817. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35818. return false;
  35819. }
  35820. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35821. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  35822. }
  35823. else {
  35824. defines.AMBIENT = false;
  35825. }
  35826. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35827. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35828. return false;
  35829. }
  35830. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35831. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35832. }
  35833. else {
  35834. defines.OPACITY = false;
  35835. }
  35836. var reflectionTexture = this._getReflectionTexture();
  35837. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35838. if (!reflectionTexture.isReadyOrNotBlocking()) {
  35839. return false;
  35840. }
  35841. defines.REFLECTION = true;
  35842. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  35843. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  35844. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35845. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  35846. defines.INVERTCUBICMAP = true;
  35847. }
  35848. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  35849. switch (reflectionTexture.coordinatesMode) {
  35850. case BABYLON.Texture.CUBIC_MODE:
  35851. case BABYLON.Texture.INVCUBIC_MODE:
  35852. defines.REFLECTIONMAP_CUBIC = true;
  35853. break;
  35854. case BABYLON.Texture.EXPLICIT_MODE:
  35855. defines.REFLECTIONMAP_EXPLICIT = true;
  35856. break;
  35857. case BABYLON.Texture.PLANAR_MODE:
  35858. defines.REFLECTIONMAP_PLANAR = true;
  35859. break;
  35860. case BABYLON.Texture.PROJECTION_MODE:
  35861. defines.REFLECTIONMAP_PROJECTION = true;
  35862. break;
  35863. case BABYLON.Texture.SKYBOX_MODE:
  35864. defines.REFLECTIONMAP_SKYBOX = true;
  35865. break;
  35866. case BABYLON.Texture.SPHERICAL_MODE:
  35867. defines.REFLECTIONMAP_SPHERICAL = true;
  35868. break;
  35869. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35870. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35871. break;
  35872. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35873. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35874. break;
  35875. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35876. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35877. break;
  35878. }
  35879. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35880. if (reflectionTexture.sphericalPolynomial) {
  35881. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35882. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35883. defines.USESPHERICALINVERTEX = false;
  35884. }
  35885. else {
  35886. defines.USESPHERICALINVERTEX = true;
  35887. }
  35888. }
  35889. }
  35890. }
  35891. else {
  35892. defines.REFLECTION = false;
  35893. defines.REFLECTIONMAP_3D = false;
  35894. defines.REFLECTIONMAP_SPHERICAL = false;
  35895. defines.REFLECTIONMAP_PLANAR = false;
  35896. defines.REFLECTIONMAP_CUBIC = false;
  35897. defines.REFLECTIONMAP_PROJECTION = false;
  35898. defines.REFLECTIONMAP_SKYBOX = false;
  35899. defines.REFLECTIONMAP_EXPLICIT = false;
  35900. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35901. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35902. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35903. defines.INVERTCUBICMAP = false;
  35904. defines.USESPHERICALFROMREFLECTIONMAP = false;
  35905. defines.USESPHERICALINVERTEX = false;
  35906. defines.REFLECTIONMAP_OPPOSITEZ = false;
  35907. defines.LODINREFLECTIONALPHA = false;
  35908. defines.GAMMAREFLECTION = false;
  35909. }
  35910. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35911. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35912. return false;
  35913. }
  35914. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35915. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35916. }
  35917. else {
  35918. defines.LIGHTMAP = false;
  35919. }
  35920. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35921. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35922. return false;
  35923. }
  35924. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35925. }
  35926. else {
  35927. defines.EMISSIVE = false;
  35928. }
  35929. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35930. if (this._metallicTexture) {
  35931. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35932. return false;
  35933. }
  35934. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  35935. defines.METALLICWORKFLOW = true;
  35936. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35937. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35938. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35939. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35940. }
  35941. else if (this._reflectivityTexture) {
  35942. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35943. return false;
  35944. }
  35945. defines.METALLICWORKFLOW = false;
  35946. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  35947. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35948. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35949. }
  35950. else {
  35951. defines.METALLICWORKFLOW = false;
  35952. defines.REFLECTIVITY = false;
  35953. }
  35954. if (this._microSurfaceTexture) {
  35955. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35956. return false;
  35957. }
  35958. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  35959. }
  35960. else {
  35961. defines.MICROSURFACEMAP = false;
  35962. }
  35963. }
  35964. else {
  35965. defines.REFLECTIVITY = false;
  35966. defines.MICROSURFACEMAP = false;
  35967. }
  35968. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35969. // Bump texure can not be none blocking.
  35970. if (!this._bumpTexture.isReady()) {
  35971. return false;
  35972. }
  35973. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35974. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35975. defines.PARALLAX = true;
  35976. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  35977. }
  35978. else {
  35979. defines.PARALLAX = false;
  35980. }
  35981. }
  35982. else {
  35983. defines.BUMP = false;
  35984. }
  35985. var refractionTexture = this._getRefractionTexture();
  35986. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35987. if (!refractionTexture.isReadyOrNotBlocking()) {
  35988. return false;
  35989. }
  35990. defines.REFRACTION = true;
  35991. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  35992. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  35993. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  35994. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35995. if (this._linkRefractionWithTransparency) {
  35996. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35997. }
  35998. }
  35999. else {
  36000. defines.REFRACTION = false;
  36001. }
  36002. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36003. // This is blocking.
  36004. if (!this._environmentBRDFTexture.isReady()) {
  36005. return false;
  36006. }
  36007. defines.ENVIRONMENTBRDF = true;
  36008. }
  36009. else {
  36010. defines.ENVIRONMENTBRDF = false;
  36011. }
  36012. if (this._shouldUseAlphaFromAlbedoTexture()) {
  36013. defines.ALPHAFROMALBEDO = true;
  36014. }
  36015. else {
  36016. defines.ALPHAFROMALBEDO = false;
  36017. }
  36018. }
  36019. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36020. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  36021. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  36022. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  36023. defines.METALLICWORKFLOW = true;
  36024. }
  36025. else {
  36026. defines.METALLICWORKFLOW = false;
  36027. }
  36028. if (!this.backFaceCulling && this._twoSidedLighting) {
  36029. defines.TWOSIDEDLIGHTING = true;
  36030. }
  36031. else {
  36032. defines.TWOSIDEDLIGHTING = false;
  36033. }
  36034. defines.ALPHATESTVALUE = this._alphaCutOff;
  36035. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36036. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  36037. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  36038. }
  36039. if (defines._areImageProcessingDirty) {
  36040. if (!this._imageProcessingConfiguration.isReady()) {
  36041. return false;
  36042. }
  36043. this._imageProcessingConfiguration.prepareDefines(defines);
  36044. }
  36045. defines.FORCENORMALFORWARD = this._forceNormalForward;
  36046. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  36047. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  36048. // Misc.
  36049. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  36050. // Values that need to be evaluated on every frame
  36051. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  36052. // Attribs
  36053. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE)) {
  36054. if (mesh) {
  36055. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36056. mesh.createNormals(true);
  36057. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  36058. }
  36059. }
  36060. }
  36061. // Get correct effect
  36062. if (defines.isDirty) {
  36063. defines.markAsProcessed();
  36064. scene.resetCachedMaterial();
  36065. // Fallbacks
  36066. var fallbacks = new BABYLON.EffectFallbacks();
  36067. var fallbackRank = 0;
  36068. if (defines.USESPHERICALINVERTEX) {
  36069. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  36070. }
  36071. if (defines.FOG) {
  36072. fallbacks.addFallback(fallbackRank, "FOG");
  36073. }
  36074. if (defines.POINTSIZE) {
  36075. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  36076. }
  36077. if (defines.LOGARITHMICDEPTH) {
  36078. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  36079. }
  36080. if (defines.PARALLAX) {
  36081. fallbacks.addFallback(fallbackRank, "PARALLAX");
  36082. }
  36083. if (defines.PARALLAXOCCLUSION) {
  36084. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  36085. }
  36086. if (defines.ENVIRONMENTBRDF) {
  36087. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  36088. }
  36089. if (defines.TANGENT) {
  36090. fallbacks.addFallback(fallbackRank++, "TANGENT");
  36091. }
  36092. if (defines.BUMP) {
  36093. fallbacks.addFallback(fallbackRank++, "BUMP");
  36094. }
  36095. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  36096. if (defines.SPECULARTERM) {
  36097. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  36098. }
  36099. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  36100. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  36101. }
  36102. if (defines.LIGHTMAP) {
  36103. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  36104. }
  36105. if (defines.NORMAL) {
  36106. fallbacks.addFallback(fallbackRank++, "NORMAL");
  36107. }
  36108. if (defines.AMBIENT) {
  36109. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  36110. }
  36111. if (defines.EMISSIVE) {
  36112. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  36113. }
  36114. if (defines.VERTEXCOLOR) {
  36115. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  36116. }
  36117. if (defines.NUM_BONE_INFLUENCERS > 0) {
  36118. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  36119. }
  36120. if (defines.MORPHTARGETS) {
  36121. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  36122. }
  36123. //Attributes
  36124. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36125. if (defines.NORMAL) {
  36126. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36127. }
  36128. if (defines.TANGENT) {
  36129. attribs.push(BABYLON.VertexBuffer.TangentKind);
  36130. }
  36131. if (defines.UV1) {
  36132. attribs.push(BABYLON.VertexBuffer.UVKind);
  36133. }
  36134. if (defines.UV2) {
  36135. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36136. }
  36137. if (defines.VERTEXCOLOR) {
  36138. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36139. }
  36140. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36141. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36142. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36143. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  36144. "vFogInfos", "vFogColor", "pointSize",
  36145. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36146. "mBones",
  36147. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36148. "vLightingIntensity",
  36149. "logarithmicDepthConstant",
  36150. "vSphericalX", "vSphericalY", "vSphericalZ",
  36151. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  36152. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  36153. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  36154. "vTangentSpaceParams"
  36155. ];
  36156. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  36157. "bumpSampler", "lightmapSampler", "opacitySampler",
  36158. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  36159. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  36160. "microSurfaceSampler", "environmentBrdfSampler"];
  36161. var uniformBuffers = ["Material", "Scene"];
  36162. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36163. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36164. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36165. uniformsNames: uniforms,
  36166. uniformBuffersNames: uniformBuffers,
  36167. samplers: samplers,
  36168. defines: defines,
  36169. maxSimultaneousLights: this._maxSimultaneousLights
  36170. });
  36171. var onCompiled = function (effect) {
  36172. if (_this.onCompiled) {
  36173. _this.onCompiled(effect);
  36174. }
  36175. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  36176. };
  36177. var join = defines.toString();
  36178. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  36179. attributes: attribs,
  36180. uniformsNames: uniforms,
  36181. uniformBuffersNames: uniformBuffers,
  36182. samplers: samplers,
  36183. defines: join,
  36184. fallbacks: fallbacks,
  36185. onCompiled: onCompiled,
  36186. onError: this.onError,
  36187. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36188. }, engine), defines);
  36189. this.buildUniformLayout();
  36190. }
  36191. if (!subMesh.effect || !subMesh.effect.isReady()) {
  36192. return false;
  36193. }
  36194. defines._renderId = scene.getRenderId();
  36195. this._wasPreviouslyReady = true;
  36196. return true;
  36197. };
  36198. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  36199. // Order is important !
  36200. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  36201. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  36202. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36203. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36204. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36205. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  36206. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  36207. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36208. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36209. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36210. this._uniformBuffer.addUniform("albedoMatrix", 16);
  36211. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36212. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36213. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36214. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36215. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  36216. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  36217. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36218. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  36219. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36220. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36221. this._uniformBuffer.addUniform("vReflectionColor", 3);
  36222. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  36223. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  36224. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  36225. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  36226. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  36227. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36228. this._uniformBuffer.addUniform("pointSize", 1);
  36229. this._uniformBuffer.create();
  36230. };
  36231. PBRBaseMaterial.prototype.unbind = function () {
  36232. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36233. this._uniformBuffer.setTexture("reflectionSampler", null);
  36234. }
  36235. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36236. this._uniformBuffer.setTexture("refractionSampler", null);
  36237. }
  36238. _super.prototype.unbind.call(this);
  36239. };
  36240. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36241. this._activeEffect.setMatrix("world", world);
  36242. };
  36243. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36244. var scene = this.getScene();
  36245. var defines = subMesh._materialDefines;
  36246. if (!defines) {
  36247. return;
  36248. }
  36249. var effect = subMesh.effect;
  36250. if (!effect) {
  36251. return;
  36252. }
  36253. this._activeEffect = effect;
  36254. // Matrices
  36255. this.bindOnlyWorldMatrix(world);
  36256. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  36257. // Bones
  36258. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  36259. var reflectionTexture = null;
  36260. if (mustRebind) {
  36261. this._uniformBuffer.bindToEffect(effect, "Material");
  36262. this.bindViewProjection(effect);
  36263. reflectionTexture = this._getReflectionTexture();
  36264. var refractionTexture = this._getRefractionTexture();
  36265. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  36266. // Texture uniforms
  36267. if (scene.texturesEnabled) {
  36268. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36269. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  36270. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  36271. }
  36272. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36273. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  36274. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  36275. }
  36276. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36277. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  36278. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  36279. }
  36280. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36281. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  36282. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  36283. var polynomials = reflectionTexture.sphericalPolynomial;
  36284. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  36285. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  36286. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  36287. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  36288. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  36289. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  36290. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  36291. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  36292. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  36293. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  36294. }
  36295. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  36296. }
  36297. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36298. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  36299. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  36300. }
  36301. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36302. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  36303. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  36304. }
  36305. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36306. if (this._metallicTexture) {
  36307. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  36308. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  36309. }
  36310. else if (this._reflectivityTexture) {
  36311. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  36312. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  36313. }
  36314. if (this._microSurfaceTexture) {
  36315. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  36316. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  36317. }
  36318. }
  36319. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36320. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  36321. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  36322. if (scene._mirroredCameraPosition) {
  36323. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  36324. }
  36325. else {
  36326. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  36327. }
  36328. }
  36329. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36330. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  36331. var depth = 1.0;
  36332. if (!refractionTexture.isCube) {
  36333. if (refractionTexture.depth) {
  36334. depth = refractionTexture.depth;
  36335. }
  36336. }
  36337. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  36338. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  36339. }
  36340. }
  36341. // Point size
  36342. if (this.pointsCloud) {
  36343. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  36344. }
  36345. // Colors
  36346. if (defines.METALLICWORKFLOW) {
  36347. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  36348. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  36349. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  36350. }
  36351. else {
  36352. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  36353. }
  36354. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  36355. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  36356. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  36357. // Misc
  36358. this._lightingInfos.x = this._directIntensity;
  36359. this._lightingInfos.y = this._emissiveIntensity;
  36360. this._lightingInfos.z = this._environmentIntensity;
  36361. this._lightingInfos.w = this._specularIntensity;
  36362. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  36363. }
  36364. // Textures
  36365. if (scene.texturesEnabled) {
  36366. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36367. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  36368. }
  36369. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36370. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  36371. }
  36372. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36373. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  36374. }
  36375. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36376. if (defines.LODBASEDMICROSFURACE) {
  36377. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  36378. }
  36379. else {
  36380. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  36381. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  36382. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  36383. }
  36384. }
  36385. if (defines.ENVIRONMENTBRDF) {
  36386. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  36387. }
  36388. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36389. if (defines.LODBASEDMICROSFURACE) {
  36390. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  36391. }
  36392. else {
  36393. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  36394. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  36395. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  36396. }
  36397. }
  36398. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36399. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  36400. }
  36401. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36402. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  36403. }
  36404. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36405. if (this._metallicTexture) {
  36406. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  36407. }
  36408. else if (this._reflectivityTexture) {
  36409. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  36410. }
  36411. if (this._microSurfaceTexture) {
  36412. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  36413. }
  36414. }
  36415. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36416. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  36417. }
  36418. }
  36419. // Clip plane
  36420. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  36421. // Colors
  36422. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  36423. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36424. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  36425. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  36426. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  36427. }
  36428. if (mustRebind || !this.isFrozen) {
  36429. // Lights
  36430. if (scene.lightsEnabled && !this._disableLighting) {
  36431. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  36432. }
  36433. // View
  36434. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  36435. this.bindView(effect);
  36436. }
  36437. // Fog
  36438. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  36439. // Morph targets
  36440. if (defines.NUM_MORPH_INFLUENCERS) {
  36441. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  36442. }
  36443. // image processing
  36444. this._imageProcessingConfiguration.bind(this._activeEffect);
  36445. // Log. depth
  36446. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  36447. }
  36448. this._uniformBuffer.update();
  36449. this._afterBind(mesh);
  36450. };
  36451. PBRBaseMaterial.prototype.getAnimatables = function () {
  36452. var results = [];
  36453. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  36454. results.push(this._albedoTexture);
  36455. }
  36456. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  36457. results.push(this._ambientTexture);
  36458. }
  36459. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  36460. results.push(this._opacityTexture);
  36461. }
  36462. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  36463. results.push(this._reflectionTexture);
  36464. }
  36465. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  36466. results.push(this._emissiveTexture);
  36467. }
  36468. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  36469. results.push(this._metallicTexture);
  36470. }
  36471. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  36472. results.push(this._reflectivityTexture);
  36473. }
  36474. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  36475. results.push(this._bumpTexture);
  36476. }
  36477. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  36478. results.push(this._lightmapTexture);
  36479. }
  36480. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  36481. results.push(this._refractionTexture);
  36482. }
  36483. return results;
  36484. };
  36485. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  36486. if (this._reflectionTexture) {
  36487. return this._reflectionTexture;
  36488. }
  36489. return this.getScene().environmentTexture;
  36490. };
  36491. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  36492. if (this._refractionTexture) {
  36493. return this._refractionTexture;
  36494. }
  36495. if (this._linkRefractionWithTransparency) {
  36496. return this.getScene().environmentTexture;
  36497. }
  36498. return null;
  36499. };
  36500. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36501. if (forceDisposeTextures) {
  36502. if (this._albedoTexture) {
  36503. this._albedoTexture.dispose();
  36504. }
  36505. if (this._ambientTexture) {
  36506. this._ambientTexture.dispose();
  36507. }
  36508. if (this._opacityTexture) {
  36509. this._opacityTexture.dispose();
  36510. }
  36511. if (this._reflectionTexture) {
  36512. this._reflectionTexture.dispose();
  36513. }
  36514. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  36515. this._environmentBRDFTexture.dispose();
  36516. }
  36517. if (this._emissiveTexture) {
  36518. this._emissiveTexture.dispose();
  36519. }
  36520. if (this._metallicTexture) {
  36521. this._metallicTexture.dispose();
  36522. }
  36523. if (this._reflectivityTexture) {
  36524. this._reflectivityTexture.dispose();
  36525. }
  36526. if (this._bumpTexture) {
  36527. this._bumpTexture.dispose();
  36528. }
  36529. if (this._lightmapTexture) {
  36530. this._lightmapTexture.dispose();
  36531. }
  36532. if (this._refractionTexture) {
  36533. this._refractionTexture.dispose();
  36534. }
  36535. }
  36536. this._renderTargets.dispose();
  36537. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36538. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36539. }
  36540. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36541. };
  36542. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  36543. __decorate([
  36544. BABYLON.serializeAsImageProcessingConfiguration()
  36545. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  36546. __decorate([
  36547. BABYLON.serialize()
  36548. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  36549. __decorate([
  36550. BABYLON.serialize()
  36551. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  36552. return PBRBaseMaterial;
  36553. }(BABYLON.PushMaterial));
  36554. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  36555. })(BABYLON || (BABYLON = {}));
  36556. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  36557. var BABYLON;
  36558. (function (BABYLON) {
  36559. var Internals;
  36560. (function (Internals) {
  36561. /**
  36562. * The Physically based simple base material of BJS.
  36563. *
  36564. * This enables better naming and convention enforcements on top of the pbrMaterial.
  36565. * It is used as the base class for both the specGloss and metalRough conventions.
  36566. */
  36567. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  36568. __extends(PBRBaseSimpleMaterial, _super);
  36569. /**
  36570. * Instantiates a new PBRMaterial instance.
  36571. *
  36572. * @param name The material name
  36573. * @param scene The scene the material will be use in.
  36574. */
  36575. function PBRBaseSimpleMaterial(name, scene) {
  36576. var _this = _super.call(this, name, scene) || this;
  36577. /**
  36578. * Number of Simultaneous lights allowed on the material.
  36579. */
  36580. _this.maxSimultaneousLights = 4;
  36581. /**
  36582. * If sets to true, disables all the lights affecting the material.
  36583. */
  36584. _this.disableLighting = false;
  36585. /**
  36586. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36587. */
  36588. _this.invertNormalMapX = false;
  36589. /**
  36590. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36591. */
  36592. _this.invertNormalMapY = false;
  36593. /**
  36594. * Emissivie color used to self-illuminate the model.
  36595. */
  36596. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36597. /**
  36598. * Occlusion Channel Strenght.
  36599. */
  36600. _this.occlusionStrength = 1.0;
  36601. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36602. _this._useAlphaFromAlbedoTexture = true;
  36603. _this._useAmbientInGrayScale = true;
  36604. return _this;
  36605. }
  36606. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  36607. /**
  36608. * Gets the current double sided mode.
  36609. */
  36610. get: function () {
  36611. return this._twoSidedLighting;
  36612. },
  36613. /**
  36614. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36615. */
  36616. set: function (value) {
  36617. if (this._twoSidedLighting === value) {
  36618. return;
  36619. }
  36620. this._twoSidedLighting = value;
  36621. this.backFaceCulling = !value;
  36622. this._markAllSubMeshesAsTexturesDirty();
  36623. },
  36624. enumerable: true,
  36625. configurable: true
  36626. });
  36627. /**
  36628. * Return the active textures of the material.
  36629. */
  36630. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  36631. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36632. if (this.environmentTexture) {
  36633. activeTextures.push(this.environmentTexture);
  36634. }
  36635. if (this.normalTexture) {
  36636. activeTextures.push(this.normalTexture);
  36637. }
  36638. if (this.emissiveTexture) {
  36639. activeTextures.push(this.emissiveTexture);
  36640. }
  36641. if (this.occlusionTexture) {
  36642. activeTextures.push(this.occlusionTexture);
  36643. }
  36644. return activeTextures;
  36645. };
  36646. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  36647. return "PBRBaseSimpleMaterial";
  36648. };
  36649. __decorate([
  36650. BABYLON.serialize(),
  36651. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36652. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  36653. __decorate([
  36654. BABYLON.serialize(),
  36655. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36656. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  36657. __decorate([
  36658. BABYLON.serializeAsTexture(),
  36659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  36660. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  36661. __decorate([
  36662. BABYLON.serialize(),
  36663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36664. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  36665. __decorate([
  36666. BABYLON.serialize(),
  36667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36668. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  36669. __decorate([
  36670. BABYLON.serializeAsTexture(),
  36671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  36672. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  36673. __decorate([
  36674. BABYLON.serializeAsColor3("emissive"),
  36675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36676. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  36677. __decorate([
  36678. BABYLON.serializeAsTexture(),
  36679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36680. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  36681. __decorate([
  36682. BABYLON.serialize(),
  36683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  36684. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  36685. __decorate([
  36686. BABYLON.serializeAsTexture(),
  36687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  36688. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  36689. __decorate([
  36690. BABYLON.serialize(),
  36691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  36692. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  36693. __decorate([
  36694. BABYLON.serialize()
  36695. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  36696. return PBRBaseSimpleMaterial;
  36697. }(BABYLON.PBRBaseMaterial));
  36698. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  36699. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36700. })(BABYLON || (BABYLON = {}));
  36701. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  36702. var BABYLON;
  36703. (function (BABYLON) {
  36704. /**
  36705. * The Physically based material of BJS.
  36706. *
  36707. * This offers the main features of a standard PBR material.
  36708. * For more information, please refer to the documentation :
  36709. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36710. */
  36711. var PBRMaterial = /** @class */ (function (_super) {
  36712. __extends(PBRMaterial, _super);
  36713. /**
  36714. * Instantiates a new PBRMaterial instance.
  36715. *
  36716. * @param name The material name
  36717. * @param scene The scene the material will be use in.
  36718. */
  36719. function PBRMaterial(name, scene) {
  36720. var _this = _super.call(this, name, scene) || this;
  36721. /**
  36722. * Intensity of the direct lights e.g. the four lights available in your scene.
  36723. * This impacts both the direct diffuse and specular highlights.
  36724. */
  36725. _this.directIntensity = 1.0;
  36726. /**
  36727. * Intensity of the emissive part of the material.
  36728. * This helps controlling the emissive effect without modifying the emissive color.
  36729. */
  36730. _this.emissiveIntensity = 1.0;
  36731. /**
  36732. * Intensity of the environment e.g. how much the environment will light the object
  36733. * either through harmonics for rough material or through the refelction for shiny ones.
  36734. */
  36735. _this.environmentIntensity = 1.0;
  36736. /**
  36737. * This is a special control allowing the reduction of the specular highlights coming from the
  36738. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36739. */
  36740. _this.specularIntensity = 1.0;
  36741. /**
  36742. * Debug Control allowing disabling the bump map on this material.
  36743. */
  36744. _this.disableBumpMap = false;
  36745. /**
  36746. * AKA Occlusion Texture Intensity in other nomenclature.
  36747. */
  36748. _this.ambientTextureStrength = 1.0;
  36749. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36750. /**
  36751. * AKA Diffuse Color in other nomenclature.
  36752. */
  36753. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  36754. /**
  36755. * AKA Specular Color in other nomenclature.
  36756. */
  36757. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36758. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  36759. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36760. /**
  36761. * AKA Glossiness in other nomenclature.
  36762. */
  36763. _this.microSurface = 1.0;
  36764. /**
  36765. * source material index of refraction (IOR)' / 'destination material IOR.
  36766. */
  36767. _this.indexOfRefraction = 0.66;
  36768. /**
  36769. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36770. */
  36771. _this.invertRefractionY = false;
  36772. /**
  36773. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36774. * Materials half opaque for instance using refraction could benefit from this control.
  36775. */
  36776. _this.linkRefractionWithTransparency = false;
  36777. _this.useLightmapAsShadowmap = false;
  36778. /**
  36779. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36780. */
  36781. _this.useAlphaFromAlbedoTexture = false;
  36782. /**
  36783. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36784. */
  36785. _this.forceAlphaTest = false;
  36786. /**
  36787. * Defines the alpha limits in alpha test mode.
  36788. */
  36789. _this.alphaCutOff = 0.4;
  36790. /**
  36791. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36792. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36793. */
  36794. _this.useSpecularOverAlpha = true;
  36795. /**
  36796. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36797. */
  36798. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  36799. /**
  36800. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36801. */
  36802. _this.useRoughnessFromMetallicTextureAlpha = true;
  36803. /**
  36804. * Specifies if the metallic texture contains the roughness information in its green channel.
  36805. */
  36806. _this.useRoughnessFromMetallicTextureGreen = false;
  36807. /**
  36808. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36809. */
  36810. _this.useMetallnessFromMetallicTextureBlue = false;
  36811. /**
  36812. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36813. */
  36814. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  36815. /**
  36816. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36817. */
  36818. _this.useAmbientInGrayScale = false;
  36819. /**
  36820. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36821. * The material will try to infer what glossiness each pixel should be.
  36822. */
  36823. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  36824. /**
  36825. * BJS is using an harcoded light falloff based on a manually sets up range.
  36826. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36827. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36828. */
  36829. _this.usePhysicalLightFalloff = true;
  36830. /**
  36831. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36832. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36833. */
  36834. _this.useRadianceOverAlpha = true;
  36835. /**
  36836. * Allows using the bump map in parallax mode.
  36837. */
  36838. _this.useParallax = false;
  36839. /**
  36840. * Allows using the bump map in parallax occlusion mode.
  36841. */
  36842. _this.useParallaxOcclusion = false;
  36843. /**
  36844. * Controls the scale bias of the parallax mode.
  36845. */
  36846. _this.parallaxScaleBias = 0.05;
  36847. /**
  36848. * If sets to true, disables all the lights affecting the material.
  36849. */
  36850. _this.disableLighting = false;
  36851. /**
  36852. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36853. */
  36854. _this.forceIrradianceInFragment = false;
  36855. /**
  36856. * Number of Simultaneous lights allowed on the material.
  36857. */
  36858. _this.maxSimultaneousLights = 4;
  36859. /**
  36860. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36861. */
  36862. _this.invertNormalMapX = false;
  36863. /**
  36864. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36865. */
  36866. _this.invertNormalMapY = false;
  36867. /**
  36868. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36869. */
  36870. _this.twoSidedLighting = false;
  36871. /**
  36872. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36873. * And/Or occlude the blended part.
  36874. */
  36875. _this.useAlphaFresnel = false;
  36876. /**
  36877. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36878. * And/Or occlude the blended part.
  36879. */
  36880. _this.environmentBRDFTexture = null;
  36881. /**
  36882. * Force normal to face away from face.
  36883. * (Temporary internal fix to remove before 3.1)
  36884. */
  36885. _this.forceNormalForward = false;
  36886. /**
  36887. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  36888. * makes the reflect vector face the model (under horizon).
  36889. */
  36890. _this.useHorizonOcclusion = false;
  36891. /**
  36892. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  36893. * too much the area relying on ambient texture to define their ambient occlusion.
  36894. */
  36895. _this.useRadianceOcclusion = false;
  36896. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36897. return _this;
  36898. }
  36899. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  36900. /**
  36901. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  36902. */
  36903. get: function () {
  36904. return this._PBRMATERIAL_OPAQUE;
  36905. },
  36906. enumerable: true,
  36907. configurable: true
  36908. });
  36909. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  36910. /**
  36911. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  36912. */
  36913. get: function () {
  36914. return this._PBRMATERIAL_ALPHATEST;
  36915. },
  36916. enumerable: true,
  36917. configurable: true
  36918. });
  36919. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  36920. /**
  36921. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36922. */
  36923. get: function () {
  36924. return this._PBRMATERIAL_ALPHABLEND;
  36925. },
  36926. enumerable: true,
  36927. configurable: true
  36928. });
  36929. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  36930. /**
  36931. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36932. * They are also discarded below the alpha cutoff threshold to improve performances.
  36933. */
  36934. get: function () {
  36935. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  36936. },
  36937. enumerable: true,
  36938. configurable: true
  36939. });
  36940. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  36941. /**
  36942. * Gets the image processing configuration used either in this material.
  36943. */
  36944. get: function () {
  36945. return this._imageProcessingConfiguration;
  36946. },
  36947. /**
  36948. * Sets the Default image processing configuration used either in the this material.
  36949. *
  36950. * If sets to null, the scene one is in use.
  36951. */
  36952. set: function (value) {
  36953. this._attachImageProcessingConfiguration(value);
  36954. // Ensure the effect will be rebuilt.
  36955. this._markAllSubMeshesAsTexturesDirty();
  36956. },
  36957. enumerable: true,
  36958. configurable: true
  36959. });
  36960. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  36961. /**
  36962. * Gets wether the color curves effect is enabled.
  36963. */
  36964. get: function () {
  36965. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36966. },
  36967. /**
  36968. * Sets wether the color curves effect is enabled.
  36969. */
  36970. set: function (value) {
  36971. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36972. },
  36973. enumerable: true,
  36974. configurable: true
  36975. });
  36976. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  36977. /**
  36978. * Gets wether the color grading effect is enabled.
  36979. */
  36980. get: function () {
  36981. return this.imageProcessingConfiguration.colorGradingEnabled;
  36982. },
  36983. /**
  36984. * Gets wether the color grading effect is enabled.
  36985. */
  36986. set: function (value) {
  36987. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36988. },
  36989. enumerable: true,
  36990. configurable: true
  36991. });
  36992. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36993. /**
  36994. * Gets wether tonemapping is enabled or not.
  36995. */
  36996. get: function () {
  36997. return this._imageProcessingConfiguration.toneMappingEnabled;
  36998. },
  36999. /**
  37000. * Sets wether tonemapping is enabled or not
  37001. */
  37002. set: function (value) {
  37003. this._imageProcessingConfiguration.toneMappingEnabled = value;
  37004. },
  37005. enumerable: true,
  37006. configurable: true
  37007. });
  37008. ;
  37009. ;
  37010. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  37011. /**
  37012. * The camera exposure used on this material.
  37013. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37014. * This corresponds to a photographic exposure.
  37015. */
  37016. get: function () {
  37017. return this._imageProcessingConfiguration.exposure;
  37018. },
  37019. /**
  37020. * The camera exposure used on this material.
  37021. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37022. * This corresponds to a photographic exposure.
  37023. */
  37024. set: function (value) {
  37025. this._imageProcessingConfiguration.exposure = value;
  37026. },
  37027. enumerable: true,
  37028. configurable: true
  37029. });
  37030. ;
  37031. ;
  37032. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  37033. /**
  37034. * Gets The camera contrast used on this material.
  37035. */
  37036. get: function () {
  37037. return this._imageProcessingConfiguration.contrast;
  37038. },
  37039. /**
  37040. * Sets The camera contrast used on this material.
  37041. */
  37042. set: function (value) {
  37043. this._imageProcessingConfiguration.contrast = value;
  37044. },
  37045. enumerable: true,
  37046. configurable: true
  37047. });
  37048. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  37049. /**
  37050. * Gets the Color Grading 2D Lookup Texture.
  37051. */
  37052. get: function () {
  37053. return this._imageProcessingConfiguration.colorGradingTexture;
  37054. },
  37055. /**
  37056. * Sets the Color Grading 2D Lookup Texture.
  37057. */
  37058. set: function (value) {
  37059. this._imageProcessingConfiguration.colorGradingTexture = value;
  37060. },
  37061. enumerable: true,
  37062. configurable: true
  37063. });
  37064. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  37065. /**
  37066. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37067. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37068. * 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;
  37069. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37070. */
  37071. get: function () {
  37072. return this._imageProcessingConfiguration.colorCurves;
  37073. },
  37074. /**
  37075. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37076. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37077. * 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;
  37078. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37079. */
  37080. set: function (value) {
  37081. this._imageProcessingConfiguration.colorCurves = value;
  37082. },
  37083. enumerable: true,
  37084. configurable: true
  37085. });
  37086. PBRMaterial.prototype.getClassName = function () {
  37087. return "PBRMaterial";
  37088. };
  37089. PBRMaterial.prototype.getActiveTextures = function () {
  37090. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37091. if (this._albedoTexture) {
  37092. activeTextures.push(this._albedoTexture);
  37093. }
  37094. if (this._ambientTexture) {
  37095. activeTextures.push(this._ambientTexture);
  37096. }
  37097. if (this._opacityTexture) {
  37098. activeTextures.push(this._opacityTexture);
  37099. }
  37100. if (this._reflectionTexture) {
  37101. activeTextures.push(this._reflectionTexture);
  37102. }
  37103. if (this._emissiveTexture) {
  37104. activeTextures.push(this._emissiveTexture);
  37105. }
  37106. if (this._reflectivityTexture) {
  37107. activeTextures.push(this._reflectivityTexture);
  37108. }
  37109. if (this._metallicTexture) {
  37110. activeTextures.push(this._metallicTexture);
  37111. }
  37112. if (this._microSurfaceTexture) {
  37113. activeTextures.push(this._microSurfaceTexture);
  37114. }
  37115. if (this._bumpTexture) {
  37116. activeTextures.push(this._bumpTexture);
  37117. }
  37118. if (this._lightmapTexture) {
  37119. activeTextures.push(this._lightmapTexture);
  37120. }
  37121. if (this._refractionTexture) {
  37122. activeTextures.push(this._refractionTexture);
  37123. }
  37124. return activeTextures;
  37125. };
  37126. PBRMaterial.prototype.hasTexture = function (texture) {
  37127. if (_super.prototype.hasTexture.call(this, texture)) {
  37128. return true;
  37129. }
  37130. if (this._albedoTexture === texture) {
  37131. return true;
  37132. }
  37133. if (this._ambientTexture === texture) {
  37134. return true;
  37135. }
  37136. if (this._opacityTexture === texture) {
  37137. return true;
  37138. }
  37139. if (this._reflectionTexture === texture) {
  37140. return true;
  37141. }
  37142. if (this._reflectivityTexture === texture) {
  37143. return true;
  37144. }
  37145. if (this._metallicTexture === texture) {
  37146. return true;
  37147. }
  37148. if (this._microSurfaceTexture === texture) {
  37149. return true;
  37150. }
  37151. if (this._bumpTexture === texture) {
  37152. return true;
  37153. }
  37154. if (this._lightmapTexture === texture) {
  37155. return true;
  37156. }
  37157. if (this._refractionTexture === texture) {
  37158. return true;
  37159. }
  37160. return false;
  37161. };
  37162. PBRMaterial.prototype.clone = function (name) {
  37163. var _this = this;
  37164. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  37165. clone.id = name;
  37166. clone.name = name;
  37167. return clone;
  37168. };
  37169. PBRMaterial.prototype.serialize = function () {
  37170. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37171. serializationObject.customType = "BABYLON.PBRMaterial";
  37172. return serializationObject;
  37173. };
  37174. // Statics
  37175. PBRMaterial.Parse = function (source, scene, rootUrl) {
  37176. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  37177. };
  37178. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  37179. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  37180. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  37181. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  37182. __decorate([
  37183. BABYLON.serialize(),
  37184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37185. ], PBRMaterial.prototype, "directIntensity", void 0);
  37186. __decorate([
  37187. BABYLON.serialize(),
  37188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37189. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  37190. __decorate([
  37191. BABYLON.serialize(),
  37192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37193. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  37194. __decorate([
  37195. BABYLON.serialize(),
  37196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37197. ], PBRMaterial.prototype, "specularIntensity", void 0);
  37198. __decorate([
  37199. BABYLON.serialize(),
  37200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37201. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  37202. __decorate([
  37203. BABYLON.serializeAsTexture(),
  37204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37205. ], PBRMaterial.prototype, "albedoTexture", void 0);
  37206. __decorate([
  37207. BABYLON.serializeAsTexture(),
  37208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37209. ], PBRMaterial.prototype, "ambientTexture", void 0);
  37210. __decorate([
  37211. BABYLON.serialize(),
  37212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37213. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  37214. __decorate([
  37215. BABYLON.serializeAsTexture(),
  37216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37217. ], PBRMaterial.prototype, "opacityTexture", void 0);
  37218. __decorate([
  37219. BABYLON.serializeAsTexture(),
  37220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37221. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  37222. __decorate([
  37223. BABYLON.serializeAsTexture(),
  37224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37225. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  37226. __decorate([
  37227. BABYLON.serializeAsTexture(),
  37228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37229. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  37230. __decorate([
  37231. BABYLON.serializeAsTexture(),
  37232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37233. ], PBRMaterial.prototype, "metallicTexture", void 0);
  37234. __decorate([
  37235. BABYLON.serialize(),
  37236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37237. ], PBRMaterial.prototype, "metallic", void 0);
  37238. __decorate([
  37239. BABYLON.serialize(),
  37240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37241. ], PBRMaterial.prototype, "roughness", void 0);
  37242. __decorate([
  37243. BABYLON.serializeAsTexture(),
  37244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37245. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  37246. __decorate([
  37247. BABYLON.serializeAsTexture(),
  37248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37249. ], PBRMaterial.prototype, "bumpTexture", void 0);
  37250. __decorate([
  37251. BABYLON.serializeAsTexture(),
  37252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37253. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  37254. __decorate([
  37255. BABYLON.serializeAsTexture(),
  37256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37257. ], PBRMaterial.prototype, "refractionTexture", void 0);
  37258. __decorate([
  37259. BABYLON.serializeAsColor3("ambient"),
  37260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37261. ], PBRMaterial.prototype, "ambientColor", void 0);
  37262. __decorate([
  37263. BABYLON.serializeAsColor3("albedo"),
  37264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37265. ], PBRMaterial.prototype, "albedoColor", void 0);
  37266. __decorate([
  37267. BABYLON.serializeAsColor3("reflectivity"),
  37268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37269. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  37270. __decorate([
  37271. BABYLON.serializeAsColor3("reflection"),
  37272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37273. ], PBRMaterial.prototype, "reflectionColor", void 0);
  37274. __decorate([
  37275. BABYLON.serializeAsColor3("emissive"),
  37276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37277. ], PBRMaterial.prototype, "emissiveColor", void 0);
  37278. __decorate([
  37279. BABYLON.serialize(),
  37280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37281. ], PBRMaterial.prototype, "microSurface", void 0);
  37282. __decorate([
  37283. BABYLON.serialize(),
  37284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37285. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  37286. __decorate([
  37287. BABYLON.serialize(),
  37288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37289. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  37290. __decorate([
  37291. BABYLON.serialize(),
  37292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37293. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  37294. __decorate([
  37295. BABYLON.serialize(),
  37296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37297. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37298. __decorate([
  37299. BABYLON.serialize(),
  37300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37301. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  37302. __decorate([
  37303. BABYLON.serialize(),
  37304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37305. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  37306. __decorate([
  37307. BABYLON.serialize(),
  37308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37309. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  37310. __decorate([
  37311. BABYLON.serialize(),
  37312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37313. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  37314. __decorate([
  37315. BABYLON.serialize(),
  37316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37317. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  37318. __decorate([
  37319. BABYLON.serialize(),
  37320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37321. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  37322. __decorate([
  37323. BABYLON.serialize(),
  37324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37325. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  37326. __decorate([
  37327. BABYLON.serialize(),
  37328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37329. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  37330. __decorate([
  37331. BABYLON.serialize(),
  37332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37333. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  37334. __decorate([
  37335. BABYLON.serialize(),
  37336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37337. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  37338. __decorate([
  37339. BABYLON.serialize(),
  37340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37341. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  37342. __decorate([
  37343. BABYLON.serialize(),
  37344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37345. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  37346. __decorate([
  37347. BABYLON.serialize(),
  37348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37349. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  37350. __decorate([
  37351. BABYLON.serialize(),
  37352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37353. ], PBRMaterial.prototype, "useParallax", void 0);
  37354. __decorate([
  37355. BABYLON.serialize(),
  37356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37357. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  37358. __decorate([
  37359. BABYLON.serialize(),
  37360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37361. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  37362. __decorate([
  37363. BABYLON.serialize(),
  37364. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37365. ], PBRMaterial.prototype, "disableLighting", void 0);
  37366. __decorate([
  37367. BABYLON.serialize(),
  37368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37369. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  37370. __decorate([
  37371. BABYLON.serialize(),
  37372. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37373. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  37374. __decorate([
  37375. BABYLON.serialize(),
  37376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37377. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  37378. __decorate([
  37379. BABYLON.serialize(),
  37380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37381. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  37382. __decorate([
  37383. BABYLON.serialize(),
  37384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37385. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  37386. __decorate([
  37387. BABYLON.serialize(),
  37388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37389. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  37390. __decorate([
  37391. BABYLON.serializeAsTexture(),
  37392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37393. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  37394. __decorate([
  37395. BABYLON.serialize(),
  37396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37397. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  37398. __decorate([
  37399. BABYLON.serialize(),
  37400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37401. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  37402. __decorate([
  37403. BABYLON.serialize(),
  37404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37405. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  37406. return PBRMaterial;
  37407. }(BABYLON.PBRBaseMaterial));
  37408. BABYLON.PBRMaterial = PBRMaterial;
  37409. })(BABYLON || (BABYLON = {}));
  37410. //# sourceMappingURL=babylon.pbrMaterial.js.map
  37411. var BABYLON;
  37412. (function (BABYLON) {
  37413. /**
  37414. * The PBR material of BJS following the metal roughness convention.
  37415. *
  37416. * This fits to the PBR convention in the GLTF definition:
  37417. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  37418. */
  37419. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  37420. __extends(PBRMetallicRoughnessMaterial, _super);
  37421. /**
  37422. * Instantiates a new PBRMetalRoughnessMaterial instance.
  37423. *
  37424. * @param name The material name
  37425. * @param scene The scene the material will be use in.
  37426. */
  37427. function PBRMetallicRoughnessMaterial(name, scene) {
  37428. var _this = _super.call(this, name, scene) || this;
  37429. _this._useRoughnessFromMetallicTextureAlpha = false;
  37430. _this._useRoughnessFromMetallicTextureGreen = true;
  37431. _this._useMetallnessFromMetallicTextureBlue = true;
  37432. return _this;
  37433. }
  37434. /**
  37435. * Return the currrent class name of the material.
  37436. */
  37437. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  37438. return "PBRMetallicRoughnessMaterial";
  37439. };
  37440. /**
  37441. * Return the active textures of the material.
  37442. */
  37443. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  37444. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37445. if (this.baseTexture) {
  37446. activeTextures.push(this.baseTexture);
  37447. }
  37448. if (this.metallicRoughnessTexture) {
  37449. activeTextures.push(this.metallicRoughnessTexture);
  37450. }
  37451. return activeTextures;
  37452. };
  37453. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  37454. if (_super.prototype.hasTexture.call(this, texture)) {
  37455. return true;
  37456. }
  37457. if (this.baseTexture === texture) {
  37458. return true;
  37459. }
  37460. if (this.metallicRoughnessTexture === texture) {
  37461. return true;
  37462. }
  37463. return false;
  37464. };
  37465. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  37466. var _this = this;
  37467. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  37468. clone.id = name;
  37469. clone.name = name;
  37470. return clone;
  37471. };
  37472. /**
  37473. * Serialize the material to a parsable JSON object.
  37474. */
  37475. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  37476. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37477. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  37478. return serializationObject;
  37479. };
  37480. /**
  37481. * Parses a JSON object correponding to the serialize function.
  37482. */
  37483. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  37484. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  37485. };
  37486. __decorate([
  37487. BABYLON.serializeAsColor3(),
  37488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37489. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  37490. __decorate([
  37491. BABYLON.serializeAsTexture(),
  37492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37493. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  37494. __decorate([
  37495. BABYLON.serialize(),
  37496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37497. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  37498. __decorate([
  37499. BABYLON.serialize(),
  37500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37501. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  37502. __decorate([
  37503. BABYLON.serializeAsTexture(),
  37504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  37505. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  37506. return PBRMetallicRoughnessMaterial;
  37507. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37508. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  37509. })(BABYLON || (BABYLON = {}));
  37510. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  37511. var BABYLON;
  37512. (function (BABYLON) {
  37513. /**
  37514. * The PBR material of BJS following the specular glossiness convention.
  37515. *
  37516. * This fits to the PBR convention in the GLTF definition:
  37517. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  37518. */
  37519. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  37520. __extends(PBRSpecularGlossinessMaterial, _super);
  37521. /**
  37522. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  37523. *
  37524. * @param name The material name
  37525. * @param scene The scene the material will be use in.
  37526. */
  37527. function PBRSpecularGlossinessMaterial(name, scene) {
  37528. var _this = _super.call(this, name, scene) || this;
  37529. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  37530. return _this;
  37531. }
  37532. /**
  37533. * Return the currrent class name of the material.
  37534. */
  37535. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  37536. return "PBRSpecularGlossinessMaterial";
  37537. };
  37538. /**
  37539. * Return the active textures of the material.
  37540. */
  37541. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  37542. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37543. if (this.diffuseTexture) {
  37544. activeTextures.push(this.diffuseTexture);
  37545. }
  37546. if (this.specularGlossinessTexture) {
  37547. activeTextures.push(this.specularGlossinessTexture);
  37548. }
  37549. return activeTextures;
  37550. };
  37551. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  37552. if (_super.prototype.hasTexture.call(this, texture)) {
  37553. return true;
  37554. }
  37555. if (this.diffuseTexture === texture) {
  37556. return true;
  37557. }
  37558. if (this.specularGlossinessTexture === texture) {
  37559. return true;
  37560. }
  37561. return false;
  37562. };
  37563. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  37564. var _this = this;
  37565. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  37566. clone.id = name;
  37567. clone.name = name;
  37568. return clone;
  37569. };
  37570. /**
  37571. * Serialize the material to a parsable JSON object.
  37572. */
  37573. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  37574. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37575. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  37576. return serializationObject;
  37577. };
  37578. /**
  37579. * Parses a JSON object correponding to the serialize function.
  37580. */
  37581. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  37582. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  37583. };
  37584. __decorate([
  37585. BABYLON.serializeAsColor3("diffuse"),
  37586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37587. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  37588. __decorate([
  37589. BABYLON.serializeAsTexture(),
  37590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37591. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  37592. __decorate([
  37593. BABYLON.serializeAsColor3("specular"),
  37594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  37595. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  37596. __decorate([
  37597. BABYLON.serialize(),
  37598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  37599. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  37600. __decorate([
  37601. BABYLON.serializeAsTexture(),
  37602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  37603. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  37604. return PBRSpecularGlossinessMaterial;
  37605. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37606. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  37607. })(BABYLON || (BABYLON = {}));
  37608. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  37609. var BABYLON;
  37610. (function (BABYLON) {
  37611. BABYLON.CameraInputTypes = {};
  37612. var CameraInputsManager = /** @class */ (function () {
  37613. function CameraInputsManager(camera) {
  37614. this.attached = {};
  37615. this.camera = camera;
  37616. this.checkInputs = function () { };
  37617. }
  37618. CameraInputsManager.prototype.add = function (input) {
  37619. var type = input.getSimpleName();
  37620. if (this.attached[type]) {
  37621. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  37622. return;
  37623. }
  37624. this.attached[type] = input;
  37625. input.camera = this.camera;
  37626. //for checkInputs, we are dynamically creating a function
  37627. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  37628. if (input.checkInputs) {
  37629. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37630. }
  37631. if (this.attachedElement) {
  37632. input.attachControl(this.attachedElement);
  37633. }
  37634. };
  37635. CameraInputsManager.prototype.remove = function (inputToRemove) {
  37636. for (var cam in this.attached) {
  37637. var input = this.attached[cam];
  37638. if (input === inputToRemove) {
  37639. input.detachControl(this.attachedElement);
  37640. input.camera = null;
  37641. delete this.attached[cam];
  37642. this.rebuildInputCheck();
  37643. }
  37644. }
  37645. };
  37646. CameraInputsManager.prototype.removeByType = function (inputType) {
  37647. for (var cam in this.attached) {
  37648. var input = this.attached[cam];
  37649. if (input.getClassName() === inputType) {
  37650. input.detachControl(this.attachedElement);
  37651. input.camera = null;
  37652. delete this.attached[cam];
  37653. this.rebuildInputCheck();
  37654. }
  37655. }
  37656. };
  37657. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  37658. var current = this.checkInputs;
  37659. return function () {
  37660. current();
  37661. fn();
  37662. };
  37663. };
  37664. CameraInputsManager.prototype.attachInput = function (input) {
  37665. if (this.attachedElement) {
  37666. input.attachControl(this.attachedElement, this.noPreventDefault);
  37667. }
  37668. };
  37669. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  37670. if (noPreventDefault === void 0) { noPreventDefault = false; }
  37671. if (this.attachedElement) {
  37672. return;
  37673. }
  37674. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37675. this.attachedElement = element;
  37676. this.noPreventDefault = noPreventDefault;
  37677. for (var cam in this.attached) {
  37678. this.attached[cam].attachControl(element, noPreventDefault);
  37679. }
  37680. };
  37681. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  37682. if (disconnect === void 0) { disconnect = false; }
  37683. if (this.attachedElement !== element) {
  37684. return;
  37685. }
  37686. for (var cam in this.attached) {
  37687. this.attached[cam].detachControl(element);
  37688. if (disconnect) {
  37689. this.attached[cam].camera = null;
  37690. }
  37691. }
  37692. this.attachedElement = null;
  37693. };
  37694. CameraInputsManager.prototype.rebuildInputCheck = function () {
  37695. this.checkInputs = function () { };
  37696. for (var cam in this.attached) {
  37697. var input = this.attached[cam];
  37698. if (input.checkInputs) {
  37699. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37700. }
  37701. }
  37702. };
  37703. CameraInputsManager.prototype.clear = function () {
  37704. if (this.attachedElement) {
  37705. this.detachElement(this.attachedElement, true);
  37706. }
  37707. this.attached = {};
  37708. this.attachedElement = null;
  37709. this.checkInputs = function () { };
  37710. };
  37711. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  37712. var inputs = {};
  37713. for (var cam in this.attached) {
  37714. var input = this.attached[cam];
  37715. var res = BABYLON.SerializationHelper.Serialize(input);
  37716. inputs[input.getClassName()] = res;
  37717. }
  37718. serializedCamera.inputsmgr = inputs;
  37719. };
  37720. CameraInputsManager.prototype.parse = function (parsedCamera) {
  37721. var parsedInputs = parsedCamera.inputsmgr;
  37722. if (parsedInputs) {
  37723. this.clear();
  37724. for (var n in parsedInputs) {
  37725. var construct = BABYLON.CameraInputTypes[n];
  37726. if (construct) {
  37727. var parsedinput = parsedInputs[n];
  37728. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  37729. this.add(input);
  37730. }
  37731. }
  37732. }
  37733. else {
  37734. //2016-03-08 this part is for managing backward compatibility
  37735. for (var n in this.attached) {
  37736. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  37737. if (construct) {
  37738. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  37739. this.remove(this.attached[n]);
  37740. this.add(input);
  37741. }
  37742. }
  37743. }
  37744. };
  37745. return CameraInputsManager;
  37746. }());
  37747. BABYLON.CameraInputsManager = CameraInputsManager;
  37748. })(BABYLON || (BABYLON = {}));
  37749. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  37750. var BABYLON;
  37751. (function (BABYLON) {
  37752. var FreeCameraMouseInput = /** @class */ (function () {
  37753. function FreeCameraMouseInput(touchEnabled) {
  37754. if (touchEnabled === void 0) { touchEnabled = true; }
  37755. this.touchEnabled = touchEnabled;
  37756. this.buttons = [0, 1, 2];
  37757. this.angularSensibility = 2000.0;
  37758. this.previousPosition = null;
  37759. }
  37760. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  37761. var _this = this;
  37762. var engine = this.camera.getEngine();
  37763. if (!this._pointerInput) {
  37764. this._pointerInput = function (p, s) {
  37765. var evt = p.event;
  37766. if (engine.isInVRExclusivePointerMode) {
  37767. return;
  37768. }
  37769. if (!_this.touchEnabled && evt.pointerType === "touch") {
  37770. return;
  37771. }
  37772. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37773. return;
  37774. }
  37775. var srcElement = (evt.srcElement || evt.target);
  37776. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37777. try {
  37778. srcElement.setPointerCapture(evt.pointerId);
  37779. }
  37780. catch (e) {
  37781. //Nothing to do with the error. Execution will continue.
  37782. }
  37783. _this.previousPosition = {
  37784. x: evt.clientX,
  37785. y: evt.clientY
  37786. };
  37787. if (!noPreventDefault) {
  37788. evt.preventDefault();
  37789. element.focus();
  37790. }
  37791. }
  37792. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37793. try {
  37794. srcElement.releasePointerCapture(evt.pointerId);
  37795. }
  37796. catch (e) {
  37797. //Nothing to do with the error.
  37798. }
  37799. _this.previousPosition = null;
  37800. if (!noPreventDefault) {
  37801. evt.preventDefault();
  37802. }
  37803. }
  37804. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  37805. if (!_this.previousPosition || engine.isPointerLock) {
  37806. return;
  37807. }
  37808. var offsetX = evt.clientX - _this.previousPosition.x;
  37809. var offsetY = evt.clientY - _this.previousPosition.y;
  37810. if (_this.camera.getScene().useRightHandedSystem) {
  37811. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37812. }
  37813. else {
  37814. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37815. }
  37816. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37817. _this.previousPosition = {
  37818. x: evt.clientX,
  37819. y: evt.clientY
  37820. };
  37821. if (!noPreventDefault) {
  37822. evt.preventDefault();
  37823. }
  37824. }
  37825. };
  37826. }
  37827. this._onMouseMove = function (evt) {
  37828. if (!engine.isPointerLock) {
  37829. return;
  37830. }
  37831. if (engine.isInVRExclusivePointerMode) {
  37832. return;
  37833. }
  37834. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37835. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37836. if (_this.camera.getScene().useRightHandedSystem) {
  37837. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37838. }
  37839. else {
  37840. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37841. }
  37842. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37843. _this.previousPosition = null;
  37844. if (!noPreventDefault) {
  37845. evt.preventDefault();
  37846. }
  37847. };
  37848. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  37849. element.addEventListener("mousemove", this._onMouseMove, false);
  37850. };
  37851. FreeCameraMouseInput.prototype.detachControl = function (element) {
  37852. if (this._observer && element) {
  37853. this.camera.getScene().onPointerObservable.remove(this._observer);
  37854. if (this._onMouseMove) {
  37855. element.removeEventListener("mousemove", this._onMouseMove);
  37856. }
  37857. this._observer = null;
  37858. this._onMouseMove = null;
  37859. this.previousPosition = null;
  37860. }
  37861. };
  37862. FreeCameraMouseInput.prototype.getClassName = function () {
  37863. return "FreeCameraMouseInput";
  37864. };
  37865. FreeCameraMouseInput.prototype.getSimpleName = function () {
  37866. return "mouse";
  37867. };
  37868. __decorate([
  37869. BABYLON.serialize()
  37870. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  37871. __decorate([
  37872. BABYLON.serialize()
  37873. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  37874. return FreeCameraMouseInput;
  37875. }());
  37876. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  37877. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  37878. })(BABYLON || (BABYLON = {}));
  37879. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  37880. var BABYLON;
  37881. (function (BABYLON) {
  37882. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  37883. function FreeCameraKeyboardMoveInput() {
  37884. this._keys = new Array();
  37885. this.keysUp = [38];
  37886. this.keysDown = [40];
  37887. this.keysLeft = [37];
  37888. this.keysRight = [39];
  37889. }
  37890. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37891. var _this = this;
  37892. if (this._onCanvasBlurObserver) {
  37893. return;
  37894. }
  37895. this._scene = this.camera.getScene();
  37896. this._engine = this._scene.getEngine();
  37897. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37898. _this._keys = [];
  37899. });
  37900. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37901. var evt = info.event;
  37902. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37903. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37904. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37905. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37906. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37907. var index = _this._keys.indexOf(evt.keyCode);
  37908. if (index === -1) {
  37909. _this._keys.push(evt.keyCode);
  37910. }
  37911. if (!noPreventDefault) {
  37912. evt.preventDefault();
  37913. }
  37914. }
  37915. }
  37916. else {
  37917. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37918. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37919. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37920. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37921. var index = _this._keys.indexOf(evt.keyCode);
  37922. if (index >= 0) {
  37923. _this._keys.splice(index, 1);
  37924. }
  37925. if (!noPreventDefault) {
  37926. evt.preventDefault();
  37927. }
  37928. }
  37929. }
  37930. });
  37931. };
  37932. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37933. if (this._scene) {
  37934. if (this._onKeyboardObserver) {
  37935. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37936. }
  37937. if (this._onCanvasBlurObserver) {
  37938. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37939. }
  37940. this._onKeyboardObserver = null;
  37941. this._onCanvasBlurObserver = null;
  37942. }
  37943. this._keys = [];
  37944. };
  37945. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37946. if (this._onKeyboardObserver) {
  37947. var camera = this.camera;
  37948. // Keyboard
  37949. for (var index = 0; index < this._keys.length; index++) {
  37950. var keyCode = this._keys[index];
  37951. var speed = camera._computeLocalCameraSpeed();
  37952. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37953. camera._localDirection.copyFromFloats(-speed, 0, 0);
  37954. }
  37955. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37956. camera._localDirection.copyFromFloats(0, 0, speed);
  37957. }
  37958. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37959. camera._localDirection.copyFromFloats(speed, 0, 0);
  37960. }
  37961. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37962. camera._localDirection.copyFromFloats(0, 0, -speed);
  37963. }
  37964. if (camera.getScene().useRightHandedSystem) {
  37965. camera._localDirection.z *= -1;
  37966. }
  37967. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  37968. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  37969. camera.cameraDirection.addInPlace(camera._transformedDirection);
  37970. }
  37971. }
  37972. };
  37973. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  37974. return "FreeCameraKeyboardMoveInput";
  37975. };
  37976. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  37977. this._keys = [];
  37978. };
  37979. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37980. return "keyboard";
  37981. };
  37982. __decorate([
  37983. BABYLON.serialize()
  37984. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37985. __decorate([
  37986. BABYLON.serialize()
  37987. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37988. __decorate([
  37989. BABYLON.serialize()
  37990. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37991. __decorate([
  37992. BABYLON.serialize()
  37993. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37994. return FreeCameraKeyboardMoveInput;
  37995. }());
  37996. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  37997. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  37998. })(BABYLON || (BABYLON = {}));
  37999. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  38000. var BABYLON;
  38001. (function (BABYLON) {
  38002. var FreeCameraInputsManager = /** @class */ (function (_super) {
  38003. __extends(FreeCameraInputsManager, _super);
  38004. function FreeCameraInputsManager(camera) {
  38005. return _super.call(this, camera) || this;
  38006. }
  38007. FreeCameraInputsManager.prototype.addKeyboard = function () {
  38008. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  38009. return this;
  38010. };
  38011. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  38012. if (touchEnabled === void 0) { touchEnabled = true; }
  38013. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  38014. return this;
  38015. };
  38016. FreeCameraInputsManager.prototype.addGamepad = function () {
  38017. this.add(new BABYLON.FreeCameraGamepadInput());
  38018. return this;
  38019. };
  38020. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  38021. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  38022. return this;
  38023. };
  38024. FreeCameraInputsManager.prototype.addTouch = function () {
  38025. this.add(new BABYLON.FreeCameraTouchInput());
  38026. return this;
  38027. };
  38028. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  38029. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  38030. return this;
  38031. };
  38032. return FreeCameraInputsManager;
  38033. }(BABYLON.CameraInputsManager));
  38034. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  38035. })(BABYLON || (BABYLON = {}));
  38036. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  38037. var BABYLON;
  38038. (function (BABYLON) {
  38039. var TargetCamera = /** @class */ (function (_super) {
  38040. __extends(TargetCamera, _super);
  38041. function TargetCamera(name, position, scene) {
  38042. var _this = _super.call(this, name, position, scene) || this;
  38043. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38044. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  38045. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  38046. _this.speed = 2.0;
  38047. _this.noRotationConstraint = false;
  38048. _this.lockedTarget = null;
  38049. _this._currentTarget = BABYLON.Vector3.Zero();
  38050. _this._viewMatrix = BABYLON.Matrix.Zero();
  38051. _this._camMatrix = BABYLON.Matrix.Zero();
  38052. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38053. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38054. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38055. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  38056. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38057. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38058. _this._tempMatrix = BABYLON.Matrix.Zero();
  38059. return _this;
  38060. }
  38061. TargetCamera.prototype.getFrontPosition = function (distance) {
  38062. var direction = this.getTarget().subtract(this.position);
  38063. direction.normalize();
  38064. direction.scaleInPlace(distance);
  38065. return this.globalPosition.add(direction);
  38066. };
  38067. TargetCamera.prototype._getLockedTargetPosition = function () {
  38068. if (!this.lockedTarget) {
  38069. return null;
  38070. }
  38071. if (this.lockedTarget.absolutePosition) {
  38072. this.lockedTarget.computeWorldMatrix();
  38073. }
  38074. return this.lockedTarget.absolutePosition || this.lockedTarget;
  38075. };
  38076. TargetCamera.prototype.storeState = function () {
  38077. this._storedPosition = this.position.clone();
  38078. this._storedRotation = this.rotation.clone();
  38079. if (this.rotationQuaternion) {
  38080. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  38081. }
  38082. return _super.prototype.storeState.call(this);
  38083. };
  38084. /**
  38085. * Restored camera state. You must call storeState() first
  38086. */
  38087. TargetCamera.prototype._restoreStateValues = function () {
  38088. if (!_super.prototype._restoreStateValues.call(this)) {
  38089. return false;
  38090. }
  38091. this.position = this._storedPosition.clone();
  38092. this.rotation = this._storedRotation.clone();
  38093. if (this.rotationQuaternion) {
  38094. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  38095. }
  38096. this.cameraDirection.copyFromFloats(0, 0, 0);
  38097. this.cameraRotation.copyFromFloats(0, 0);
  38098. return true;
  38099. };
  38100. // Cache
  38101. TargetCamera.prototype._initCache = function () {
  38102. _super.prototype._initCache.call(this);
  38103. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38104. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38105. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38106. };
  38107. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  38108. if (!ignoreParentClass) {
  38109. _super.prototype._updateCache.call(this);
  38110. }
  38111. var lockedTargetPosition = this._getLockedTargetPosition();
  38112. if (!lockedTargetPosition) {
  38113. this._cache.lockedTarget = null;
  38114. }
  38115. else {
  38116. if (!this._cache.lockedTarget) {
  38117. this._cache.lockedTarget = lockedTargetPosition.clone();
  38118. }
  38119. else {
  38120. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  38121. }
  38122. }
  38123. this._cache.rotation.copyFrom(this.rotation);
  38124. if (this.rotationQuaternion)
  38125. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38126. };
  38127. // Synchronized
  38128. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  38129. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  38130. return false;
  38131. }
  38132. var lockedTargetPosition = this._getLockedTargetPosition();
  38133. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  38134. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  38135. };
  38136. // Methods
  38137. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  38138. var engine = this.getEngine();
  38139. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  38140. };
  38141. // Target
  38142. TargetCamera.prototype.setTarget = function (target) {
  38143. this.upVector.normalize();
  38144. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  38145. this._camMatrix.invert();
  38146. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  38147. var vDir = target.subtract(this.position);
  38148. if (vDir.x >= 0.0) {
  38149. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  38150. }
  38151. else {
  38152. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  38153. }
  38154. this.rotation.z = 0;
  38155. if (isNaN(this.rotation.x)) {
  38156. this.rotation.x = 0;
  38157. }
  38158. if (isNaN(this.rotation.y)) {
  38159. this.rotation.y = 0;
  38160. }
  38161. if (isNaN(this.rotation.z)) {
  38162. this.rotation.z = 0;
  38163. }
  38164. if (this.rotationQuaternion) {
  38165. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38166. }
  38167. };
  38168. /**
  38169. * Return the current target position of the camera. This value is expressed in local space.
  38170. */
  38171. TargetCamera.prototype.getTarget = function () {
  38172. return this._currentTarget;
  38173. };
  38174. TargetCamera.prototype._decideIfNeedsToMove = function () {
  38175. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38176. };
  38177. TargetCamera.prototype._updatePosition = function () {
  38178. if (this.parent) {
  38179. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  38180. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  38181. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  38182. return;
  38183. }
  38184. this.position.addInPlace(this.cameraDirection);
  38185. };
  38186. TargetCamera.prototype._checkInputs = function () {
  38187. var needToMove = this._decideIfNeedsToMove();
  38188. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  38189. // Move
  38190. if (needToMove) {
  38191. this._updatePosition();
  38192. }
  38193. // Rotate
  38194. if (needToRotate) {
  38195. this.rotation.x += this.cameraRotation.x;
  38196. this.rotation.y += this.cameraRotation.y;
  38197. //rotate, if quaternion is set and rotation was used
  38198. if (this.rotationQuaternion) {
  38199. var len = this.rotation.lengthSquared();
  38200. if (len) {
  38201. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38202. }
  38203. }
  38204. if (!this.noRotationConstraint) {
  38205. var limit = (Math.PI / 2) * 0.95;
  38206. if (this.rotation.x > limit)
  38207. this.rotation.x = limit;
  38208. if (this.rotation.x < -limit)
  38209. this.rotation.x = -limit;
  38210. }
  38211. }
  38212. // Inertia
  38213. if (needToMove) {
  38214. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  38215. this.cameraDirection.x = 0;
  38216. }
  38217. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  38218. this.cameraDirection.y = 0;
  38219. }
  38220. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  38221. this.cameraDirection.z = 0;
  38222. }
  38223. this.cameraDirection.scaleInPlace(this.inertia);
  38224. }
  38225. if (needToRotate) {
  38226. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  38227. this.cameraRotation.x = 0;
  38228. }
  38229. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  38230. this.cameraRotation.y = 0;
  38231. }
  38232. this.cameraRotation.scaleInPlace(this.inertia);
  38233. }
  38234. _super.prototype._checkInputs.call(this);
  38235. };
  38236. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  38237. if (this.rotationQuaternion) {
  38238. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  38239. }
  38240. else {
  38241. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  38242. }
  38243. //update the up vector!
  38244. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  38245. };
  38246. TargetCamera.prototype._getViewMatrix = function () {
  38247. if (!this.lockedTarget) {
  38248. // Compute
  38249. this._updateCameraRotationMatrix();
  38250. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  38251. // Computing target and final matrix
  38252. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  38253. }
  38254. else {
  38255. var targetPosition = this._getLockedTargetPosition();
  38256. if (targetPosition) {
  38257. this._currentTarget.copyFrom(targetPosition);
  38258. }
  38259. }
  38260. if (this.getScene().useRightHandedSystem) {
  38261. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  38262. }
  38263. else {
  38264. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  38265. }
  38266. return this._viewMatrix;
  38267. };
  38268. /**
  38269. * @override
  38270. * Override Camera.createRigCamera
  38271. */
  38272. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  38273. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  38274. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  38275. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  38276. if (!this.rotationQuaternion) {
  38277. this.rotationQuaternion = new BABYLON.Quaternion();
  38278. }
  38279. rigCamera._cameraRigParams = {};
  38280. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  38281. }
  38282. return rigCamera;
  38283. }
  38284. return null;
  38285. };
  38286. /**
  38287. * @override
  38288. * Override Camera._updateRigCameras
  38289. */
  38290. TargetCamera.prototype._updateRigCameras = function () {
  38291. var camLeft = this._rigCameras[0];
  38292. var camRight = this._rigCameras[1];
  38293. switch (this.cameraRigMode) {
  38294. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38295. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38296. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38297. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38298. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  38299. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  38300. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  38301. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  38302. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  38303. camLeft.setTarget(this.getTarget());
  38304. camRight.setTarget(this.getTarget());
  38305. break;
  38306. case BABYLON.Camera.RIG_MODE_VR:
  38307. if (camLeft.rotationQuaternion) {
  38308. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38309. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38310. }
  38311. else {
  38312. camLeft.rotation.copyFrom(this.rotation);
  38313. camRight.rotation.copyFrom(this.rotation);
  38314. }
  38315. camLeft.position.copyFrom(this.position);
  38316. camRight.position.copyFrom(this.position);
  38317. break;
  38318. }
  38319. _super.prototype._updateRigCameras.call(this);
  38320. };
  38321. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  38322. if (!this._rigCamTransformMatrix) {
  38323. this._rigCamTransformMatrix = new BABYLON.Matrix();
  38324. }
  38325. var target = this.getTarget();
  38326. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  38327. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  38328. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  38329. };
  38330. TargetCamera.prototype.getClassName = function () {
  38331. return "TargetCamera";
  38332. };
  38333. __decorate([
  38334. BABYLON.serializeAsVector3()
  38335. ], TargetCamera.prototype, "rotation", void 0);
  38336. __decorate([
  38337. BABYLON.serialize()
  38338. ], TargetCamera.prototype, "speed", void 0);
  38339. __decorate([
  38340. BABYLON.serializeAsMeshReference("lockedTargetId")
  38341. ], TargetCamera.prototype, "lockedTarget", void 0);
  38342. return TargetCamera;
  38343. }(BABYLON.Camera));
  38344. BABYLON.TargetCamera = TargetCamera;
  38345. })(BABYLON || (BABYLON = {}));
  38346. //# sourceMappingURL=babylon.targetCamera.js.map
  38347. var BABYLON;
  38348. (function (BABYLON) {
  38349. var FreeCamera = /** @class */ (function (_super) {
  38350. __extends(FreeCamera, _super);
  38351. function FreeCamera(name, position, scene) {
  38352. var _this = _super.call(this, name, position, scene) || this;
  38353. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  38354. _this.checkCollisions = false;
  38355. _this.applyGravity = false;
  38356. _this._needMoveForGravity = false;
  38357. _this._oldPosition = BABYLON.Vector3.Zero();
  38358. _this._diffPosition = BABYLON.Vector3.Zero();
  38359. _this._newPosition = BABYLON.Vector3.Zero();
  38360. // Collisions
  38361. _this._collisionMask = -1;
  38362. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38363. if (collidedMesh === void 0) { collidedMesh = null; }
  38364. //TODO move this to the collision coordinator!
  38365. if (_this.getScene().workerCollisions)
  38366. newPosition.multiplyInPlace(_this._collider.radius);
  38367. var updatePosition = function (newPos) {
  38368. _this._newPosition.copyFrom(newPos);
  38369. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  38370. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  38371. _this.position.addInPlace(_this._diffPosition);
  38372. if (_this.onCollide && collidedMesh) {
  38373. _this.onCollide(collidedMesh);
  38374. }
  38375. }
  38376. };
  38377. updatePosition(newPosition);
  38378. };
  38379. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  38380. _this.inputs.addKeyboard().addMouse();
  38381. return _this;
  38382. }
  38383. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  38384. //-- begin properties for backward compatibility for inputs
  38385. get: function () {
  38386. var mouse = this.inputs.attached["mouse"];
  38387. if (mouse)
  38388. return mouse.angularSensibility;
  38389. return 0;
  38390. },
  38391. set: function (value) {
  38392. var mouse = this.inputs.attached["mouse"];
  38393. if (mouse)
  38394. mouse.angularSensibility = value;
  38395. },
  38396. enumerable: true,
  38397. configurable: true
  38398. });
  38399. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  38400. get: function () {
  38401. var keyboard = this.inputs.attached["keyboard"];
  38402. if (keyboard)
  38403. return keyboard.keysUp;
  38404. return [];
  38405. },
  38406. set: function (value) {
  38407. var keyboard = this.inputs.attached["keyboard"];
  38408. if (keyboard)
  38409. keyboard.keysUp = value;
  38410. },
  38411. enumerable: true,
  38412. configurable: true
  38413. });
  38414. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  38415. get: function () {
  38416. var keyboard = this.inputs.attached["keyboard"];
  38417. if (keyboard)
  38418. return keyboard.keysDown;
  38419. return [];
  38420. },
  38421. set: function (value) {
  38422. var keyboard = this.inputs.attached["keyboard"];
  38423. if (keyboard)
  38424. keyboard.keysDown = value;
  38425. },
  38426. enumerable: true,
  38427. configurable: true
  38428. });
  38429. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  38430. get: function () {
  38431. var keyboard = this.inputs.attached["keyboard"];
  38432. if (keyboard)
  38433. return keyboard.keysLeft;
  38434. return [];
  38435. },
  38436. set: function (value) {
  38437. var keyboard = this.inputs.attached["keyboard"];
  38438. if (keyboard)
  38439. keyboard.keysLeft = value;
  38440. },
  38441. enumerable: true,
  38442. configurable: true
  38443. });
  38444. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  38445. get: function () {
  38446. var keyboard = this.inputs.attached["keyboard"];
  38447. if (keyboard)
  38448. return keyboard.keysRight;
  38449. return [];
  38450. },
  38451. set: function (value) {
  38452. var keyboard = this.inputs.attached["keyboard"];
  38453. if (keyboard)
  38454. keyboard.keysRight = value;
  38455. },
  38456. enumerable: true,
  38457. configurable: true
  38458. });
  38459. // Controls
  38460. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  38461. this.inputs.attachElement(element, noPreventDefault);
  38462. };
  38463. FreeCamera.prototype.detachControl = function (element) {
  38464. this.inputs.detachElement(element);
  38465. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38466. this.cameraRotation = new BABYLON.Vector2(0, 0);
  38467. };
  38468. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  38469. get: function () {
  38470. return this._collisionMask;
  38471. },
  38472. set: function (mask) {
  38473. this._collisionMask = !isNaN(mask) ? mask : -1;
  38474. },
  38475. enumerable: true,
  38476. configurable: true
  38477. });
  38478. FreeCamera.prototype._collideWithWorld = function (displacement) {
  38479. var globalPosition;
  38480. if (this.parent) {
  38481. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  38482. }
  38483. else {
  38484. globalPosition = this.position;
  38485. }
  38486. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  38487. if (!this._collider) {
  38488. this._collider = new BABYLON.Collider();
  38489. }
  38490. this._collider.radius = this.ellipsoid;
  38491. this._collider.collisionMask = this._collisionMask;
  38492. //no need for clone, as long as gravity is not on.
  38493. var actualDisplacement = displacement;
  38494. //add gravity to the direction to prevent the dual-collision checking
  38495. if (this.applyGravity) {
  38496. //this prevents mending with cameraDirection, a global variable of the free camera class.
  38497. actualDisplacement = displacement.add(this.getScene().gravity);
  38498. }
  38499. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  38500. };
  38501. FreeCamera.prototype._checkInputs = function () {
  38502. if (!this._localDirection) {
  38503. this._localDirection = BABYLON.Vector3.Zero();
  38504. this._transformedDirection = BABYLON.Vector3.Zero();
  38505. }
  38506. this.inputs.checkInputs();
  38507. _super.prototype._checkInputs.call(this);
  38508. };
  38509. FreeCamera.prototype._decideIfNeedsToMove = function () {
  38510. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38511. };
  38512. FreeCamera.prototype._updatePosition = function () {
  38513. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  38514. this._collideWithWorld(this.cameraDirection);
  38515. }
  38516. else {
  38517. _super.prototype._updatePosition.call(this);
  38518. }
  38519. };
  38520. FreeCamera.prototype.dispose = function () {
  38521. this.inputs.clear();
  38522. _super.prototype.dispose.call(this);
  38523. };
  38524. FreeCamera.prototype.getClassName = function () {
  38525. return "FreeCamera";
  38526. };
  38527. __decorate([
  38528. BABYLON.serializeAsVector3()
  38529. ], FreeCamera.prototype, "ellipsoid", void 0);
  38530. __decorate([
  38531. BABYLON.serialize()
  38532. ], FreeCamera.prototype, "checkCollisions", void 0);
  38533. __decorate([
  38534. BABYLON.serialize()
  38535. ], FreeCamera.prototype, "applyGravity", void 0);
  38536. return FreeCamera;
  38537. }(BABYLON.TargetCamera));
  38538. BABYLON.FreeCamera = FreeCamera;
  38539. })(BABYLON || (BABYLON = {}));
  38540. //# sourceMappingURL=babylon.freeCamera.js.map
  38541. var BABYLON;
  38542. (function (BABYLON) {
  38543. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  38544. function ArcRotateCameraKeyboardMoveInput() {
  38545. this._keys = new Array();
  38546. this.keysUp = [38];
  38547. this.keysDown = [40];
  38548. this.keysLeft = [37];
  38549. this.keysRight = [39];
  38550. this.keysReset = [220];
  38551. this.panningSensibility = 50.0;
  38552. this.zoomingSensibility = 25.0;
  38553. this.useAltToZoom = true;
  38554. }
  38555. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  38556. var _this = this;
  38557. if (this._onCanvasBlurObserver) {
  38558. return;
  38559. }
  38560. this._scene = this.camera.getScene();
  38561. this._engine = this._scene.getEngine();
  38562. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  38563. _this._keys = [];
  38564. });
  38565. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  38566. var evt = info.event;
  38567. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  38568. _this._ctrlPressed = evt.ctrlKey;
  38569. _this._altPressed = evt.altKey;
  38570. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38571. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38572. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38573. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  38574. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  38575. var index = _this._keys.indexOf(evt.keyCode);
  38576. if (index === -1) {
  38577. _this._keys.push(evt.keyCode);
  38578. }
  38579. if (evt.preventDefault) {
  38580. if (!noPreventDefault) {
  38581. evt.preventDefault();
  38582. }
  38583. }
  38584. }
  38585. }
  38586. else {
  38587. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38588. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38589. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38590. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  38591. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  38592. var index = _this._keys.indexOf(evt.keyCode);
  38593. if (index >= 0) {
  38594. _this._keys.splice(index, 1);
  38595. }
  38596. if (evt.preventDefault) {
  38597. if (!noPreventDefault) {
  38598. evt.preventDefault();
  38599. }
  38600. }
  38601. }
  38602. }
  38603. });
  38604. };
  38605. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  38606. if (this._scene) {
  38607. if (this._onKeyboardObserver) {
  38608. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  38609. }
  38610. if (this._onCanvasBlurObserver) {
  38611. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  38612. }
  38613. this._onKeyboardObserver = null;
  38614. this._onCanvasBlurObserver = null;
  38615. }
  38616. this._keys = [];
  38617. };
  38618. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  38619. if (this._onKeyboardObserver) {
  38620. var camera = this.camera;
  38621. for (var index = 0; index < this._keys.length; index++) {
  38622. var keyCode = this._keys[index];
  38623. if (this.keysLeft.indexOf(keyCode) !== -1) {
  38624. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38625. camera.inertialPanningX -= 1 / this.panningSensibility;
  38626. }
  38627. else {
  38628. camera.inertialAlphaOffset -= 0.01;
  38629. }
  38630. }
  38631. else if (this.keysUp.indexOf(keyCode) !== -1) {
  38632. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38633. camera.inertialPanningY += 1 / this.panningSensibility;
  38634. }
  38635. else if (this._altPressed && this.useAltToZoom) {
  38636. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  38637. }
  38638. else {
  38639. camera.inertialBetaOffset -= 0.01;
  38640. }
  38641. }
  38642. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38643. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38644. camera.inertialPanningX += 1 / this.panningSensibility;
  38645. }
  38646. else {
  38647. camera.inertialAlphaOffset += 0.01;
  38648. }
  38649. }
  38650. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38651. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38652. camera.inertialPanningY -= 1 / this.panningSensibility;
  38653. }
  38654. else if (this._altPressed && this.useAltToZoom) {
  38655. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  38656. }
  38657. else {
  38658. camera.inertialBetaOffset += 0.01;
  38659. }
  38660. }
  38661. else if (this.keysReset.indexOf(keyCode) !== -1) {
  38662. camera.restoreState();
  38663. }
  38664. }
  38665. }
  38666. };
  38667. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  38668. return "ArcRotateCameraKeyboardMoveInput";
  38669. };
  38670. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38671. return "keyboard";
  38672. };
  38673. __decorate([
  38674. BABYLON.serialize()
  38675. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38676. __decorate([
  38677. BABYLON.serialize()
  38678. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38679. __decorate([
  38680. BABYLON.serialize()
  38681. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38682. __decorate([
  38683. BABYLON.serialize()
  38684. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38685. __decorate([
  38686. BABYLON.serialize()
  38687. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  38688. __decorate([
  38689. BABYLON.serialize()
  38690. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  38691. __decorate([
  38692. BABYLON.serialize()
  38693. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  38694. __decorate([
  38695. BABYLON.serialize()
  38696. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  38697. return ArcRotateCameraKeyboardMoveInput;
  38698. }());
  38699. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  38700. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  38701. })(BABYLON || (BABYLON = {}));
  38702. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  38703. var BABYLON;
  38704. (function (BABYLON) {
  38705. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  38706. function ArcRotateCameraMouseWheelInput() {
  38707. this.wheelPrecision = 3.0;
  38708. /**
  38709. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  38710. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  38711. */
  38712. this.wheelDeltaPercentage = 0;
  38713. }
  38714. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  38715. var _this = this;
  38716. this._wheel = function (p, s) {
  38717. //sanity check - this should be a PointerWheel event.
  38718. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  38719. return;
  38720. var event = p.event;
  38721. var delta = 0;
  38722. if (event.wheelDelta) {
  38723. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  38724. }
  38725. else if (event.detail) {
  38726. delta = -event.detail / _this.wheelPrecision;
  38727. }
  38728. if (delta)
  38729. _this.camera.inertialRadiusOffset += delta;
  38730. if (event.preventDefault) {
  38731. if (!noPreventDefault) {
  38732. event.preventDefault();
  38733. }
  38734. }
  38735. };
  38736. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  38737. };
  38738. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  38739. if (this._observer && element) {
  38740. this.camera.getScene().onPointerObservable.remove(this._observer);
  38741. this._observer = null;
  38742. this._wheel = null;
  38743. }
  38744. };
  38745. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  38746. return "ArcRotateCameraMouseWheelInput";
  38747. };
  38748. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  38749. return "mousewheel";
  38750. };
  38751. __decorate([
  38752. BABYLON.serialize()
  38753. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  38754. __decorate([
  38755. BABYLON.serialize()
  38756. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  38757. return ArcRotateCameraMouseWheelInput;
  38758. }());
  38759. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  38760. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  38761. })(BABYLON || (BABYLON = {}));
  38762. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  38763. var BABYLON;
  38764. (function (BABYLON) {
  38765. var ArcRotateCameraPointersInput = /** @class */ (function () {
  38766. function ArcRotateCameraPointersInput() {
  38767. this.buttons = [0, 1, 2];
  38768. this.angularSensibilityX = 1000.0;
  38769. this.angularSensibilityY = 1000.0;
  38770. this.pinchPrecision = 12.0;
  38771. /**
  38772. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  38773. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  38774. */
  38775. this.pinchDeltaPercentage = 0;
  38776. this.panningSensibility = 1000.0;
  38777. this.multiTouchPanning = true;
  38778. this.multiTouchPanAndZoom = true;
  38779. this._isPanClick = false;
  38780. this.pinchInwards = true;
  38781. }
  38782. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  38783. var _this = this;
  38784. var engine = this.camera.getEngine();
  38785. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  38786. var pointA = null;
  38787. var pointB = null;
  38788. var previousPinchSquaredDistance = 0;
  38789. var initialDistance = 0;
  38790. var twoFingerActivityCount = 0;
  38791. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  38792. this._pointerInput = function (p, s) {
  38793. var evt = p.event;
  38794. var isTouch = p.event.pointerType === "touch";
  38795. if (engine.isInVRExclusivePointerMode) {
  38796. return;
  38797. }
  38798. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38799. return;
  38800. }
  38801. var srcElement = (evt.srcElement || evt.target);
  38802. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38803. try {
  38804. srcElement.setPointerCapture(evt.pointerId);
  38805. }
  38806. catch (e) {
  38807. //Nothing to do with the error. Execution will continue.
  38808. }
  38809. // Manage panning with pan button click
  38810. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  38811. // manage pointers
  38812. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  38813. if (pointA === null) {
  38814. pointA = cacheSoloPointer;
  38815. }
  38816. else if (pointB === null) {
  38817. pointB = cacheSoloPointer;
  38818. }
  38819. if (!noPreventDefault) {
  38820. evt.preventDefault();
  38821. element.focus();
  38822. }
  38823. }
  38824. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  38825. _this.camera.restoreState();
  38826. }
  38827. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38828. try {
  38829. srcElement.releasePointerCapture(evt.pointerId);
  38830. }
  38831. catch (e) {
  38832. //Nothing to do with the error.
  38833. }
  38834. cacheSoloPointer = null;
  38835. previousPinchSquaredDistance = 0;
  38836. previousMultiTouchPanPosition.isPaning = false;
  38837. previousMultiTouchPanPosition.isPinching = false;
  38838. twoFingerActivityCount = 0;
  38839. initialDistance = 0;
  38840. if (!isTouch) {
  38841. pointB = null; // Mouse and pen are mono pointer
  38842. }
  38843. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  38844. //but emptying completly pointers collection is required to fix a bug on iPhone :
  38845. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  38846. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  38847. if (engine.badOS) {
  38848. pointA = pointB = null;
  38849. }
  38850. else {
  38851. //only remove the impacted pointer in case of multitouch allowing on most
  38852. //platforms switching from rotate to zoom and pan seamlessly.
  38853. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  38854. pointA = pointB;
  38855. pointB = null;
  38856. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38857. }
  38858. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  38859. pointB = null;
  38860. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38861. }
  38862. else {
  38863. pointA = pointB = null;
  38864. }
  38865. }
  38866. if (!noPreventDefault) {
  38867. evt.preventDefault();
  38868. }
  38869. }
  38870. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38871. if (!noPreventDefault) {
  38872. evt.preventDefault();
  38873. }
  38874. // One button down
  38875. if (pointA && pointB === null && cacheSoloPointer) {
  38876. if (_this.panningSensibility !== 0 &&
  38877. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  38878. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  38879. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  38880. }
  38881. else {
  38882. var offsetX = evt.clientX - cacheSoloPointer.x;
  38883. var offsetY = evt.clientY - cacheSoloPointer.y;
  38884. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38885. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38886. }
  38887. cacheSoloPointer.x = evt.clientX;
  38888. cacheSoloPointer.y = evt.clientY;
  38889. }
  38890. else if (pointA && pointB) {
  38891. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  38892. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  38893. ed.x = evt.clientX;
  38894. ed.y = evt.clientY;
  38895. var direction = _this.pinchInwards ? 1 : -1;
  38896. var distX = pointA.x - pointB.x;
  38897. var distY = pointA.y - pointB.y;
  38898. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  38899. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  38900. if (previousPinchSquaredDistance === 0) {
  38901. initialDistance = pinchDistance;
  38902. previousPinchSquaredDistance = pinchSquaredDistance;
  38903. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  38904. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  38905. return;
  38906. }
  38907. if (_this.multiTouchPanAndZoom) {
  38908. if (_this.pinchDeltaPercentage) {
  38909. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38910. }
  38911. else {
  38912. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38913. (_this.pinchPrecision *
  38914. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38915. direction);
  38916. }
  38917. if (_this.panningSensibility !== 0) {
  38918. var pointersCenterX = (pointA.x + pointB.x) / 2;
  38919. var pointersCenterY = (pointA.y + pointB.y) / 2;
  38920. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  38921. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  38922. previousMultiTouchPanPosition.x = pointersCenterX;
  38923. previousMultiTouchPanPosition.y = pointersCenterY;
  38924. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  38925. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  38926. }
  38927. }
  38928. else {
  38929. twoFingerActivityCount++;
  38930. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  38931. if (_this.pinchDeltaPercentage) {
  38932. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38933. }
  38934. else {
  38935. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38936. (_this.pinchPrecision *
  38937. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38938. direction);
  38939. }
  38940. previousMultiTouchPanPosition.isPaning = false;
  38941. previousMultiTouchPanPosition.isPinching = true;
  38942. }
  38943. else {
  38944. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  38945. if (!previousMultiTouchPanPosition.isPaning) {
  38946. previousMultiTouchPanPosition.isPaning = true;
  38947. previousMultiTouchPanPosition.isPinching = false;
  38948. previousMultiTouchPanPosition.x = ed.x;
  38949. previousMultiTouchPanPosition.y = ed.y;
  38950. return;
  38951. }
  38952. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  38953. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  38954. }
  38955. }
  38956. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  38957. previousMultiTouchPanPosition.x = ed.x;
  38958. previousMultiTouchPanPosition.y = ed.y;
  38959. }
  38960. }
  38961. previousPinchSquaredDistance = pinchSquaredDistance;
  38962. }
  38963. }
  38964. };
  38965. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  38966. this._onContextMenu = function (evt) {
  38967. evt.preventDefault();
  38968. };
  38969. if (!this.camera._useCtrlForPanning) {
  38970. element.addEventListener("contextmenu", this._onContextMenu, false);
  38971. }
  38972. this._onLostFocus = function () {
  38973. //this._keys = [];
  38974. pointA = pointB = null;
  38975. previousPinchSquaredDistance = 0;
  38976. previousMultiTouchPanPosition.isPaning = false;
  38977. previousMultiTouchPanPosition.isPinching = false;
  38978. twoFingerActivityCount = 0;
  38979. cacheSoloPointer = null;
  38980. initialDistance = 0;
  38981. };
  38982. this._onMouseMove = function (evt) {
  38983. if (!engine.isPointerLock) {
  38984. return;
  38985. }
  38986. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38987. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38988. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38989. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38990. if (!noPreventDefault) {
  38991. evt.preventDefault();
  38992. }
  38993. };
  38994. this._onGestureStart = function (e) {
  38995. if (window.MSGesture === undefined) {
  38996. return;
  38997. }
  38998. if (!_this._MSGestureHandler) {
  38999. _this._MSGestureHandler = new MSGesture();
  39000. _this._MSGestureHandler.target = element;
  39001. }
  39002. _this._MSGestureHandler.addPointer(e.pointerId);
  39003. };
  39004. this._onGesture = function (e) {
  39005. _this.camera.radius *= e.scale;
  39006. if (e.preventDefault) {
  39007. if (!noPreventDefault) {
  39008. e.stopPropagation();
  39009. e.preventDefault();
  39010. }
  39011. }
  39012. };
  39013. element.addEventListener("mousemove", this._onMouseMove, false);
  39014. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  39015. element.addEventListener("MSGestureChange", this._onGesture, false);
  39016. BABYLON.Tools.RegisterTopRootEvents([
  39017. { name: "blur", handler: this._onLostFocus }
  39018. ]);
  39019. };
  39020. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  39021. if (this._onLostFocus) {
  39022. BABYLON.Tools.UnregisterTopRootEvents([
  39023. { name: "blur", handler: this._onLostFocus }
  39024. ]);
  39025. }
  39026. if (element && this._observer) {
  39027. this.camera.getScene().onPointerObservable.remove(this._observer);
  39028. this._observer = null;
  39029. if (this._onContextMenu) {
  39030. element.removeEventListener("contextmenu", this._onContextMenu);
  39031. }
  39032. if (this._onMouseMove) {
  39033. element.removeEventListener("mousemove", this._onMouseMove);
  39034. }
  39035. if (this._onGestureStart) {
  39036. element.removeEventListener("MSPointerDown", this._onGestureStart);
  39037. }
  39038. if (this._onGesture) {
  39039. element.removeEventListener("MSGestureChange", this._onGesture);
  39040. }
  39041. this._isPanClick = false;
  39042. this.pinchInwards = true;
  39043. this._onMouseMove = null;
  39044. this._onGestureStart = null;
  39045. this._onGesture = null;
  39046. this._MSGestureHandler = null;
  39047. this._onLostFocus = null;
  39048. this._onContextMenu = null;
  39049. }
  39050. };
  39051. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  39052. return "ArcRotateCameraPointersInput";
  39053. };
  39054. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  39055. return "pointers";
  39056. };
  39057. __decorate([
  39058. BABYLON.serialize()
  39059. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  39060. __decorate([
  39061. BABYLON.serialize()
  39062. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  39063. __decorate([
  39064. BABYLON.serialize()
  39065. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  39066. __decorate([
  39067. BABYLON.serialize()
  39068. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  39069. __decorate([
  39070. BABYLON.serialize()
  39071. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  39072. __decorate([
  39073. BABYLON.serialize()
  39074. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  39075. __decorate([
  39076. BABYLON.serialize()
  39077. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  39078. __decorate([
  39079. BABYLON.serialize()
  39080. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  39081. return ArcRotateCameraPointersInput;
  39082. }());
  39083. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  39084. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  39085. })(BABYLON || (BABYLON = {}));
  39086. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  39087. var BABYLON;
  39088. (function (BABYLON) {
  39089. var ArcRotateCamera = /** @class */ (function (_super) {
  39090. __extends(ArcRotateCamera, _super);
  39091. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  39092. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  39093. _this.inertialAlphaOffset = 0;
  39094. _this.inertialBetaOffset = 0;
  39095. _this.inertialRadiusOffset = 0;
  39096. _this.lowerAlphaLimit = null;
  39097. _this.upperAlphaLimit = null;
  39098. _this.lowerBetaLimit = 0.01;
  39099. _this.upperBetaLimit = Math.PI;
  39100. _this.lowerRadiusLimit = null;
  39101. _this.upperRadiusLimit = null;
  39102. _this.inertialPanningX = 0;
  39103. _this.inertialPanningY = 0;
  39104. _this.pinchToPanMaxDistance = 20;
  39105. _this.panningDistanceLimit = null;
  39106. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  39107. _this.panningInertia = 0.9;
  39108. //-- end properties for backward compatibility for inputs
  39109. _this.zoomOnFactor = 1;
  39110. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  39111. _this.allowUpsideDown = true;
  39112. _this._viewMatrix = new BABYLON.Matrix();
  39113. // Panning
  39114. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  39115. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  39116. _this.checkCollisions = false;
  39117. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  39118. _this._previousPosition = BABYLON.Vector3.Zero();
  39119. _this._collisionVelocity = BABYLON.Vector3.Zero();
  39120. _this._newPosition = BABYLON.Vector3.Zero();
  39121. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39122. if (collidedMesh === void 0) { collidedMesh = null; }
  39123. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  39124. newPosition.multiplyInPlace(_this._collider.radius);
  39125. }
  39126. if (!collidedMesh) {
  39127. _this._previousPosition.copyFrom(_this.position);
  39128. }
  39129. else {
  39130. _this.setPosition(newPosition);
  39131. if (_this.onCollide) {
  39132. _this.onCollide(collidedMesh);
  39133. }
  39134. }
  39135. // Recompute because of constraints
  39136. var cosa = Math.cos(_this.alpha);
  39137. var sina = Math.sin(_this.alpha);
  39138. var cosb = Math.cos(_this.beta);
  39139. var sinb = Math.sin(_this.beta);
  39140. if (sinb === 0) {
  39141. sinb = 0.0001;
  39142. }
  39143. var target = _this._getTargetPosition();
  39144. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  39145. _this.position.copyFrom(_this._newPosition);
  39146. var up = _this.upVector;
  39147. if (_this.allowUpsideDown && _this.beta < 0) {
  39148. up = up.clone();
  39149. up = up.negate();
  39150. }
  39151. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  39152. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  39153. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  39154. _this._collisionTriggered = false;
  39155. };
  39156. _this._target = BABYLON.Vector3.Zero();
  39157. if (target) {
  39158. _this.setTarget(target);
  39159. }
  39160. _this.alpha = alpha;
  39161. _this.beta = beta;
  39162. _this.radius = radius;
  39163. _this.getViewMatrix();
  39164. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  39165. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  39166. return _this;
  39167. }
  39168. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  39169. get: function () {
  39170. return this._target;
  39171. },
  39172. set: function (value) {
  39173. this.setTarget(value);
  39174. },
  39175. enumerable: true,
  39176. configurable: true
  39177. });
  39178. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  39179. //-- begin properties for backward compatibility for inputs
  39180. get: function () {
  39181. var pointers = this.inputs.attached["pointers"];
  39182. if (pointers)
  39183. return pointers.angularSensibilityX;
  39184. return 0;
  39185. },
  39186. set: function (value) {
  39187. var pointers = this.inputs.attached["pointers"];
  39188. if (pointers) {
  39189. pointers.angularSensibilityX = value;
  39190. }
  39191. },
  39192. enumerable: true,
  39193. configurable: true
  39194. });
  39195. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  39196. get: function () {
  39197. var pointers = this.inputs.attached["pointers"];
  39198. if (pointers)
  39199. return pointers.angularSensibilityY;
  39200. return 0;
  39201. },
  39202. set: function (value) {
  39203. var pointers = this.inputs.attached["pointers"];
  39204. if (pointers) {
  39205. pointers.angularSensibilityY = value;
  39206. }
  39207. },
  39208. enumerable: true,
  39209. configurable: true
  39210. });
  39211. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  39212. get: function () {
  39213. var pointers = this.inputs.attached["pointers"];
  39214. if (pointers)
  39215. return pointers.pinchPrecision;
  39216. return 0;
  39217. },
  39218. set: function (value) {
  39219. var pointers = this.inputs.attached["pointers"];
  39220. if (pointers) {
  39221. pointers.pinchPrecision = value;
  39222. }
  39223. },
  39224. enumerable: true,
  39225. configurable: true
  39226. });
  39227. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  39228. get: function () {
  39229. var pointers = this.inputs.attached["pointers"];
  39230. if (pointers)
  39231. return pointers.pinchDeltaPercentage;
  39232. return 0;
  39233. },
  39234. set: function (value) {
  39235. var pointers = this.inputs.attached["pointers"];
  39236. if (pointers) {
  39237. pointers.pinchDeltaPercentage = value;
  39238. }
  39239. },
  39240. enumerable: true,
  39241. configurable: true
  39242. });
  39243. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  39244. get: function () {
  39245. var pointers = this.inputs.attached["pointers"];
  39246. if (pointers)
  39247. return pointers.panningSensibility;
  39248. return 0;
  39249. },
  39250. set: function (value) {
  39251. var pointers = this.inputs.attached["pointers"];
  39252. if (pointers) {
  39253. pointers.panningSensibility = value;
  39254. }
  39255. },
  39256. enumerable: true,
  39257. configurable: true
  39258. });
  39259. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  39260. get: function () {
  39261. var keyboard = this.inputs.attached["keyboard"];
  39262. if (keyboard)
  39263. return keyboard.keysUp;
  39264. return [];
  39265. },
  39266. set: function (value) {
  39267. var keyboard = this.inputs.attached["keyboard"];
  39268. if (keyboard)
  39269. keyboard.keysUp = value;
  39270. },
  39271. enumerable: true,
  39272. configurable: true
  39273. });
  39274. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  39275. get: function () {
  39276. var keyboard = this.inputs.attached["keyboard"];
  39277. if (keyboard)
  39278. return keyboard.keysDown;
  39279. return [];
  39280. },
  39281. set: function (value) {
  39282. var keyboard = this.inputs.attached["keyboard"];
  39283. if (keyboard)
  39284. keyboard.keysDown = value;
  39285. },
  39286. enumerable: true,
  39287. configurable: true
  39288. });
  39289. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  39290. get: function () {
  39291. var keyboard = this.inputs.attached["keyboard"];
  39292. if (keyboard)
  39293. return keyboard.keysLeft;
  39294. return [];
  39295. },
  39296. set: function (value) {
  39297. var keyboard = this.inputs.attached["keyboard"];
  39298. if (keyboard)
  39299. keyboard.keysLeft = value;
  39300. },
  39301. enumerable: true,
  39302. configurable: true
  39303. });
  39304. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  39305. get: function () {
  39306. var keyboard = this.inputs.attached["keyboard"];
  39307. if (keyboard)
  39308. return keyboard.keysRight;
  39309. return [];
  39310. },
  39311. set: function (value) {
  39312. var keyboard = this.inputs.attached["keyboard"];
  39313. if (keyboard)
  39314. keyboard.keysRight = value;
  39315. },
  39316. enumerable: true,
  39317. configurable: true
  39318. });
  39319. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  39320. get: function () {
  39321. var mousewheel = this.inputs.attached["mousewheel"];
  39322. if (mousewheel)
  39323. return mousewheel.wheelPrecision;
  39324. return 0;
  39325. },
  39326. set: function (value) {
  39327. var mousewheel = this.inputs.attached["mousewheel"];
  39328. if (mousewheel)
  39329. mousewheel.wheelPrecision = value;
  39330. },
  39331. enumerable: true,
  39332. configurable: true
  39333. });
  39334. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  39335. get: function () {
  39336. var mousewheel = this.inputs.attached["mousewheel"];
  39337. if (mousewheel)
  39338. return mousewheel.wheelDeltaPercentage;
  39339. return 0;
  39340. },
  39341. set: function (value) {
  39342. var mousewheel = this.inputs.attached["mousewheel"];
  39343. if (mousewheel)
  39344. mousewheel.wheelDeltaPercentage = value;
  39345. },
  39346. enumerable: true,
  39347. configurable: true
  39348. });
  39349. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  39350. get: function () {
  39351. return this._bouncingBehavior;
  39352. },
  39353. enumerable: true,
  39354. configurable: true
  39355. });
  39356. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  39357. get: function () {
  39358. return this._bouncingBehavior != null;
  39359. },
  39360. set: function (value) {
  39361. if (value === this.useBouncingBehavior) {
  39362. return;
  39363. }
  39364. if (value) {
  39365. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  39366. this.addBehavior(this._bouncingBehavior);
  39367. }
  39368. else if (this._bouncingBehavior) {
  39369. this.removeBehavior(this._bouncingBehavior);
  39370. this._bouncingBehavior = null;
  39371. }
  39372. },
  39373. enumerable: true,
  39374. configurable: true
  39375. });
  39376. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  39377. get: function () {
  39378. return this._framingBehavior;
  39379. },
  39380. enumerable: true,
  39381. configurable: true
  39382. });
  39383. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  39384. get: function () {
  39385. return this._framingBehavior != null;
  39386. },
  39387. set: function (value) {
  39388. if (value === this.useFramingBehavior) {
  39389. return;
  39390. }
  39391. if (value) {
  39392. this._framingBehavior = new BABYLON.FramingBehavior();
  39393. this.addBehavior(this._framingBehavior);
  39394. }
  39395. else if (this._framingBehavior) {
  39396. this.removeBehavior(this._framingBehavior);
  39397. this._framingBehavior = null;
  39398. }
  39399. },
  39400. enumerable: true,
  39401. configurable: true
  39402. });
  39403. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  39404. get: function () {
  39405. return this._autoRotationBehavior;
  39406. },
  39407. enumerable: true,
  39408. configurable: true
  39409. });
  39410. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  39411. get: function () {
  39412. return this._autoRotationBehavior != null;
  39413. },
  39414. set: function (value) {
  39415. if (value === this.useAutoRotationBehavior) {
  39416. return;
  39417. }
  39418. if (value) {
  39419. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  39420. this.addBehavior(this._autoRotationBehavior);
  39421. }
  39422. else if (this._autoRotationBehavior) {
  39423. this.removeBehavior(this._autoRotationBehavior);
  39424. this._autoRotationBehavior = null;
  39425. }
  39426. },
  39427. enumerable: true,
  39428. configurable: true
  39429. });
  39430. // Cache
  39431. ArcRotateCamera.prototype._initCache = function () {
  39432. _super.prototype._initCache.call(this);
  39433. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39434. this._cache.alpha = undefined;
  39435. this._cache.beta = undefined;
  39436. this._cache.radius = undefined;
  39437. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  39438. };
  39439. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  39440. if (!ignoreParentClass) {
  39441. _super.prototype._updateCache.call(this);
  39442. }
  39443. this._cache._target.copyFrom(this._getTargetPosition());
  39444. this._cache.alpha = this.alpha;
  39445. this._cache.beta = this.beta;
  39446. this._cache.radius = this.radius;
  39447. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  39448. };
  39449. ArcRotateCamera.prototype._getTargetPosition = function () {
  39450. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  39451. var pos = this._targetHost.getAbsolutePosition();
  39452. if (this._targetBoundingCenter) {
  39453. pos.addToRef(this._targetBoundingCenter, this._target);
  39454. }
  39455. else {
  39456. this._target.copyFrom(pos);
  39457. }
  39458. }
  39459. var lockedTargetPosition = this._getLockedTargetPosition();
  39460. if (lockedTargetPosition) {
  39461. return lockedTargetPosition;
  39462. }
  39463. return this._target;
  39464. };
  39465. ArcRotateCamera.prototype.storeState = function () {
  39466. this._storedAlpha = this.alpha;
  39467. this._storedBeta = this.beta;
  39468. this._storedRadius = this.radius;
  39469. this._storedTarget = this._getTargetPosition().clone();
  39470. return _super.prototype.storeState.call(this);
  39471. };
  39472. /**
  39473. * Restored camera state. You must call storeState() first
  39474. */
  39475. ArcRotateCamera.prototype._restoreStateValues = function () {
  39476. if (!_super.prototype._restoreStateValues.call(this)) {
  39477. return false;
  39478. }
  39479. this.alpha = this._storedAlpha;
  39480. this.beta = this._storedBeta;
  39481. this.radius = this._storedRadius;
  39482. this.setTarget(this._storedTarget.clone());
  39483. this.inertialAlphaOffset = 0;
  39484. this.inertialBetaOffset = 0;
  39485. this.inertialRadiusOffset = 0;
  39486. this.inertialPanningX = 0;
  39487. this.inertialPanningY = 0;
  39488. return true;
  39489. };
  39490. // Synchronized
  39491. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  39492. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  39493. return false;
  39494. return this._cache._target.equals(this._getTargetPosition())
  39495. && this._cache.alpha === this.alpha
  39496. && this._cache.beta === this.beta
  39497. && this._cache.radius === this.radius
  39498. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  39499. };
  39500. // Methods
  39501. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  39502. var _this = this;
  39503. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  39504. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  39505. this._useCtrlForPanning = useCtrlForPanning;
  39506. this._panningMouseButton = panningMouseButton;
  39507. this.inputs.attachElement(element, noPreventDefault);
  39508. this._reset = function () {
  39509. _this.inertialAlphaOffset = 0;
  39510. _this.inertialBetaOffset = 0;
  39511. _this.inertialRadiusOffset = 0;
  39512. _this.inertialPanningX = 0;
  39513. _this.inertialPanningY = 0;
  39514. };
  39515. };
  39516. ArcRotateCamera.prototype.detachControl = function (element) {
  39517. this.inputs.detachElement(element);
  39518. if (this._reset) {
  39519. this._reset();
  39520. }
  39521. };
  39522. ArcRotateCamera.prototype._checkInputs = function () {
  39523. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  39524. if (this._collisionTriggered) {
  39525. return;
  39526. }
  39527. this.inputs.checkInputs();
  39528. // Inertia
  39529. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  39530. if (this.getScene().useRightHandedSystem) {
  39531. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39532. }
  39533. else {
  39534. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39535. }
  39536. this.beta += this.inertialBetaOffset;
  39537. this.radius -= this.inertialRadiusOffset;
  39538. this.inertialAlphaOffset *= this.inertia;
  39539. this.inertialBetaOffset *= this.inertia;
  39540. this.inertialRadiusOffset *= this.inertia;
  39541. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  39542. this.inertialAlphaOffset = 0;
  39543. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  39544. this.inertialBetaOffset = 0;
  39545. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  39546. this.inertialRadiusOffset = 0;
  39547. }
  39548. // Panning inertia
  39549. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  39550. if (!this._localDirection) {
  39551. this._localDirection = BABYLON.Vector3.Zero();
  39552. this._transformedDirection = BABYLON.Vector3.Zero();
  39553. }
  39554. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  39555. this._localDirection.multiplyInPlace(this.panningAxis);
  39556. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  39557. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  39558. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  39559. if (!this.panningAxis.y) {
  39560. this._transformedDirection.y = 0;
  39561. }
  39562. if (!this._targetHost) {
  39563. if (this.panningDistanceLimit) {
  39564. this._transformedDirection.addInPlace(this._target);
  39565. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  39566. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  39567. this._target.copyFrom(this._transformedDirection);
  39568. }
  39569. }
  39570. else {
  39571. this._target.addInPlace(this._transformedDirection);
  39572. }
  39573. }
  39574. this.inertialPanningX *= this.panningInertia;
  39575. this.inertialPanningY *= this.panningInertia;
  39576. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  39577. this.inertialPanningX = 0;
  39578. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  39579. this.inertialPanningY = 0;
  39580. }
  39581. // Limits
  39582. this._checkLimits();
  39583. _super.prototype._checkInputs.call(this);
  39584. };
  39585. ArcRotateCamera.prototype._checkLimits = function () {
  39586. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  39587. if (this.allowUpsideDown && this.beta > Math.PI) {
  39588. this.beta = this.beta - (2 * Math.PI);
  39589. }
  39590. }
  39591. else {
  39592. if (this.beta < this.lowerBetaLimit) {
  39593. this.beta = this.lowerBetaLimit;
  39594. }
  39595. }
  39596. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  39597. if (this.allowUpsideDown && this.beta < -Math.PI) {
  39598. this.beta = this.beta + (2 * Math.PI);
  39599. }
  39600. }
  39601. else {
  39602. if (this.beta > this.upperBetaLimit) {
  39603. this.beta = this.upperBetaLimit;
  39604. }
  39605. }
  39606. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  39607. this.alpha = this.lowerAlphaLimit;
  39608. }
  39609. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  39610. this.alpha = this.upperAlphaLimit;
  39611. }
  39612. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  39613. this.radius = this.lowerRadiusLimit;
  39614. }
  39615. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  39616. this.radius = this.upperRadiusLimit;
  39617. }
  39618. };
  39619. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  39620. var radiusv3 = this.position.subtract(this._getTargetPosition());
  39621. this.radius = radiusv3.length();
  39622. if (this.radius === 0) {
  39623. this.radius = 0.0001; // Just to avoid division by zero
  39624. }
  39625. // Alpha
  39626. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  39627. if (radiusv3.z < 0) {
  39628. this.alpha = 2 * Math.PI - this.alpha;
  39629. }
  39630. // Beta
  39631. this.beta = Math.acos(radiusv3.y / this.radius);
  39632. this._checkLimits();
  39633. };
  39634. ArcRotateCamera.prototype.setPosition = function (position) {
  39635. if (this.position.equals(position)) {
  39636. return;
  39637. }
  39638. this.position.copyFrom(position);
  39639. this.rebuildAnglesAndRadius();
  39640. };
  39641. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  39642. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  39643. if (allowSamePosition === void 0) { allowSamePosition = false; }
  39644. if (target.getBoundingInfo) {
  39645. if (toBoundingCenter) {
  39646. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  39647. }
  39648. else {
  39649. this._targetBoundingCenter = null;
  39650. }
  39651. this._targetHost = target;
  39652. this._target = this._getTargetPosition();
  39653. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  39654. }
  39655. else {
  39656. var newTarget = target;
  39657. var currentTarget = this._getTargetPosition();
  39658. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  39659. return;
  39660. }
  39661. this._targetHost = null;
  39662. this._target = newTarget;
  39663. this._targetBoundingCenter = null;
  39664. this.onMeshTargetChangedObservable.notifyObservers(null);
  39665. }
  39666. this.rebuildAnglesAndRadius();
  39667. };
  39668. ArcRotateCamera.prototype._getViewMatrix = function () {
  39669. // Compute
  39670. var cosa = Math.cos(this.alpha);
  39671. var sina = Math.sin(this.alpha);
  39672. var cosb = Math.cos(this.beta);
  39673. var sinb = Math.sin(this.beta);
  39674. if (sinb === 0) {
  39675. sinb = 0.0001;
  39676. }
  39677. var target = this._getTargetPosition();
  39678. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  39679. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  39680. if (!this._collider) {
  39681. this._collider = new BABYLON.Collider();
  39682. }
  39683. this._collider.radius = this.collisionRadius;
  39684. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  39685. this._collisionTriggered = true;
  39686. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39687. }
  39688. else {
  39689. this.position.copyFrom(this._newPosition);
  39690. var up = this.upVector;
  39691. if (this.allowUpsideDown && sinb < 0) {
  39692. up = up.clone();
  39693. up = up.negate();
  39694. }
  39695. if (this.getScene().useRightHandedSystem) {
  39696. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  39697. }
  39698. else {
  39699. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  39700. }
  39701. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  39702. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  39703. }
  39704. this._currentTarget = target;
  39705. return this._viewMatrix;
  39706. };
  39707. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  39708. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39709. meshes = meshes || this.getScene().meshes;
  39710. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  39711. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  39712. this.radius = distance * this.zoomOnFactor;
  39713. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  39714. };
  39715. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  39716. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39717. var meshesOrMinMaxVector;
  39718. var distance;
  39719. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  39720. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  39721. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  39722. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  39723. }
  39724. else {
  39725. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  39726. meshesOrMinMaxVector = minMaxVectorAndDistance;
  39727. distance = minMaxVectorAndDistance.distance;
  39728. }
  39729. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  39730. if (!doNotUpdateMaxZ) {
  39731. this.maxZ = distance * 2;
  39732. }
  39733. };
  39734. /**
  39735. * @override
  39736. * Override Camera.createRigCamera
  39737. */
  39738. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39739. var alphaShift = 0;
  39740. switch (this.cameraRigMode) {
  39741. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39742. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39743. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39744. case BABYLON.Camera.RIG_MODE_VR:
  39745. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  39746. break;
  39747. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39748. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  39749. break;
  39750. }
  39751. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  39752. rigCam._cameraRigParams = {};
  39753. return rigCam;
  39754. };
  39755. /**
  39756. * @override
  39757. * Override Camera._updateRigCameras
  39758. */
  39759. ArcRotateCamera.prototype._updateRigCameras = function () {
  39760. var camLeft = this._rigCameras[0];
  39761. var camRight = this._rigCameras[1];
  39762. camLeft.beta = camRight.beta = this.beta;
  39763. camLeft.radius = camRight.radius = this.radius;
  39764. switch (this.cameraRigMode) {
  39765. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39766. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39767. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39768. case BABYLON.Camera.RIG_MODE_VR:
  39769. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39770. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39771. break;
  39772. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39773. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39774. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39775. break;
  39776. }
  39777. _super.prototype._updateRigCameras.call(this);
  39778. };
  39779. ArcRotateCamera.prototype.dispose = function () {
  39780. this.inputs.clear();
  39781. _super.prototype.dispose.call(this);
  39782. };
  39783. ArcRotateCamera.prototype.getClassName = function () {
  39784. return "ArcRotateCamera";
  39785. };
  39786. __decorate([
  39787. BABYLON.serialize()
  39788. ], ArcRotateCamera.prototype, "alpha", void 0);
  39789. __decorate([
  39790. BABYLON.serialize()
  39791. ], ArcRotateCamera.prototype, "beta", void 0);
  39792. __decorate([
  39793. BABYLON.serialize()
  39794. ], ArcRotateCamera.prototype, "radius", void 0);
  39795. __decorate([
  39796. BABYLON.serializeAsVector3("target")
  39797. ], ArcRotateCamera.prototype, "_target", void 0);
  39798. __decorate([
  39799. BABYLON.serialize()
  39800. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  39801. __decorate([
  39802. BABYLON.serialize()
  39803. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  39804. __decorate([
  39805. BABYLON.serialize()
  39806. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  39807. __decorate([
  39808. BABYLON.serialize()
  39809. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  39810. __decorate([
  39811. BABYLON.serialize()
  39812. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  39813. __decorate([
  39814. BABYLON.serialize()
  39815. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  39816. __decorate([
  39817. BABYLON.serialize()
  39818. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  39819. __decorate([
  39820. BABYLON.serialize()
  39821. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  39822. __decorate([
  39823. BABYLON.serialize()
  39824. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  39825. __decorate([
  39826. BABYLON.serialize()
  39827. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  39828. __decorate([
  39829. BABYLON.serialize()
  39830. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  39831. __decorate([
  39832. BABYLON.serialize()
  39833. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  39834. __decorate([
  39835. BABYLON.serialize()
  39836. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  39837. __decorate([
  39838. BABYLON.serializeAsVector3()
  39839. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  39840. __decorate([
  39841. BABYLON.serialize()
  39842. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  39843. __decorate([
  39844. BABYLON.serialize()
  39845. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  39846. __decorate([
  39847. BABYLON.serialize()
  39848. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  39849. return ArcRotateCamera;
  39850. }(BABYLON.TargetCamera));
  39851. BABYLON.ArcRotateCamera = ArcRotateCamera;
  39852. })(BABYLON || (BABYLON = {}));
  39853. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  39854. var BABYLON;
  39855. (function (BABYLON) {
  39856. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  39857. __extends(ArcRotateCameraInputsManager, _super);
  39858. function ArcRotateCameraInputsManager(camera) {
  39859. return _super.call(this, camera) || this;
  39860. }
  39861. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  39862. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  39863. return this;
  39864. };
  39865. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  39866. this.add(new BABYLON.ArcRotateCameraPointersInput());
  39867. return this;
  39868. };
  39869. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  39870. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  39871. return this;
  39872. };
  39873. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  39874. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  39875. return this;
  39876. };
  39877. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  39878. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  39879. return this;
  39880. };
  39881. return ArcRotateCameraInputsManager;
  39882. }(BABYLON.CameraInputsManager));
  39883. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  39884. })(BABYLON || (BABYLON = {}));
  39885. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  39886. var BABYLON;
  39887. (function (BABYLON) {
  39888. var HemisphericLight = /** @class */ (function (_super) {
  39889. __extends(HemisphericLight, _super);
  39890. /**
  39891. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  39892. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  39893. * The HemisphericLight can't cast shadows.
  39894. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39895. */
  39896. function HemisphericLight(name, direction, scene) {
  39897. var _this = _super.call(this, name, scene) || this;
  39898. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39899. _this.direction = direction || BABYLON.Vector3.Up();
  39900. return _this;
  39901. }
  39902. HemisphericLight.prototype._buildUniformLayout = function () {
  39903. this._uniformBuffer.addUniform("vLightData", 4);
  39904. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39905. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39906. this._uniformBuffer.addUniform("vLightGround", 3);
  39907. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39908. this._uniformBuffer.addUniform("depthValues", 2);
  39909. this._uniformBuffer.create();
  39910. };
  39911. /**
  39912. * Returns the string "HemisphericLight".
  39913. */
  39914. HemisphericLight.prototype.getClassName = function () {
  39915. return "HemisphericLight";
  39916. };
  39917. /**
  39918. * Sets the HemisphericLight direction towards the passed target (Vector3).
  39919. * Returns the updated direction.
  39920. */
  39921. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  39922. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  39923. return this.direction;
  39924. };
  39925. HemisphericLight.prototype.getShadowGenerator = function () {
  39926. return null;
  39927. };
  39928. /**
  39929. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  39930. * Returns the HemisphericLight.
  39931. */
  39932. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  39933. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39934. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  39935. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  39936. return this;
  39937. };
  39938. HemisphericLight.prototype._getWorldMatrix = function () {
  39939. if (!this._worldMatrix) {
  39940. this._worldMatrix = BABYLON.Matrix.Identity();
  39941. }
  39942. return this._worldMatrix;
  39943. };
  39944. /**
  39945. * Returns the integer 3.
  39946. */
  39947. HemisphericLight.prototype.getTypeID = function () {
  39948. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  39949. };
  39950. __decorate([
  39951. BABYLON.serializeAsColor3()
  39952. ], HemisphericLight.prototype, "groundColor", void 0);
  39953. __decorate([
  39954. BABYLON.serializeAsVector3()
  39955. ], HemisphericLight.prototype, "direction", void 0);
  39956. return HemisphericLight;
  39957. }(BABYLON.Light));
  39958. BABYLON.HemisphericLight = HemisphericLight;
  39959. })(BABYLON || (BABYLON = {}));
  39960. //# sourceMappingURL=babylon.hemisphericLight.js.map
  39961. var BABYLON;
  39962. (function (BABYLON) {
  39963. var ShadowLight = /** @class */ (function (_super) {
  39964. __extends(ShadowLight, _super);
  39965. function ShadowLight() {
  39966. var _this = _super !== null && _super.apply(this, arguments) || this;
  39967. _this._needProjectionMatrixCompute = true;
  39968. return _this;
  39969. }
  39970. Object.defineProperty(ShadowLight.prototype, "direction", {
  39971. get: function () {
  39972. return this._direction;
  39973. },
  39974. set: function (value) {
  39975. this._direction = value;
  39976. },
  39977. enumerable: true,
  39978. configurable: true
  39979. });
  39980. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  39981. get: function () {
  39982. return this._shadowMinZ;
  39983. },
  39984. set: function (value) {
  39985. this._shadowMinZ = value;
  39986. this.forceProjectionMatrixCompute();
  39987. },
  39988. enumerable: true,
  39989. configurable: true
  39990. });
  39991. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  39992. get: function () {
  39993. return this._shadowMaxZ;
  39994. },
  39995. set: function (value) {
  39996. this._shadowMaxZ = value;
  39997. this.forceProjectionMatrixCompute();
  39998. },
  39999. enumerable: true,
  40000. configurable: true
  40001. });
  40002. /**
  40003. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  40004. */
  40005. ShadowLight.prototype.computeTransformedInformation = function () {
  40006. if (this.parent && this.parent.getWorldMatrix) {
  40007. if (!this.transformedPosition) {
  40008. this.transformedPosition = BABYLON.Vector3.Zero();
  40009. }
  40010. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  40011. // In case the direction is present.
  40012. if (this.direction) {
  40013. if (!this.transformedDirection) {
  40014. this.transformedDirection = BABYLON.Vector3.Zero();
  40015. }
  40016. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  40017. }
  40018. return true;
  40019. }
  40020. return false;
  40021. };
  40022. /**
  40023. * Return the depth scale used for the shadow map.
  40024. */
  40025. ShadowLight.prototype.getDepthScale = function () {
  40026. return 50.0;
  40027. };
  40028. /**
  40029. * Returns the light direction (Vector3) for any passed face index.
  40030. */
  40031. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  40032. return this.transformedDirection ? this.transformedDirection : this.direction;
  40033. };
  40034. /**
  40035. * Returns the DirectionalLight absolute position in the World.
  40036. */
  40037. ShadowLight.prototype.getAbsolutePosition = function () {
  40038. return this.transformedPosition ? this.transformedPosition : this.position;
  40039. };
  40040. /**
  40041. * Sets the DirectionalLight direction toward the passed target (Vector3).
  40042. * Returns the updated DirectionalLight direction (Vector3).
  40043. */
  40044. ShadowLight.prototype.setDirectionToTarget = function (target) {
  40045. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  40046. return this.direction;
  40047. };
  40048. /**
  40049. * Returns the light rotation (Vector3).
  40050. */
  40051. ShadowLight.prototype.getRotation = function () {
  40052. this.direction.normalize();
  40053. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  40054. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  40055. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  40056. };
  40057. /**
  40058. * Boolean : false by default.
  40059. */
  40060. ShadowLight.prototype.needCube = function () {
  40061. return false;
  40062. };
  40063. /**
  40064. * Specifies wether or not the projection matrix should be recomputed this frame.
  40065. */
  40066. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  40067. return this._needProjectionMatrixCompute;
  40068. };
  40069. /**
  40070. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  40071. */
  40072. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  40073. this._needProjectionMatrixCompute = true;
  40074. };
  40075. /**
  40076. * Get the world matrix of the sahdow lights.
  40077. */
  40078. ShadowLight.prototype._getWorldMatrix = function () {
  40079. if (!this._worldMatrix) {
  40080. this._worldMatrix = BABYLON.Matrix.Identity();
  40081. }
  40082. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  40083. return this._worldMatrix;
  40084. };
  40085. /**
  40086. * Gets the minZ used for shadow according to both the scene and the light.
  40087. * @param activeCamera
  40088. */
  40089. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  40090. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  40091. };
  40092. /**
  40093. * Gets the maxZ used for shadow according to both the scene and the light.
  40094. * @param activeCamera
  40095. */
  40096. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  40097. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  40098. };
  40099. /**
  40100. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  40101. * Returns the light.
  40102. */
  40103. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40104. if (this.customProjectionMatrixBuilder) {
  40105. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  40106. }
  40107. else {
  40108. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40109. }
  40110. return this;
  40111. };
  40112. __decorate([
  40113. BABYLON.serializeAsVector3()
  40114. ], ShadowLight.prototype, "position", void 0);
  40115. __decorate([
  40116. BABYLON.serializeAsVector3()
  40117. ], ShadowLight.prototype, "direction", null);
  40118. __decorate([
  40119. BABYLON.serialize()
  40120. ], ShadowLight.prototype, "shadowMinZ", null);
  40121. __decorate([
  40122. BABYLON.serialize()
  40123. ], ShadowLight.prototype, "shadowMaxZ", null);
  40124. return ShadowLight;
  40125. }(BABYLON.Light));
  40126. BABYLON.ShadowLight = ShadowLight;
  40127. })(BABYLON || (BABYLON = {}));
  40128. //# sourceMappingURL=babylon.shadowLight.js.map
  40129. var BABYLON;
  40130. (function (BABYLON) {
  40131. var PointLight = /** @class */ (function (_super) {
  40132. __extends(PointLight, _super);
  40133. /**
  40134. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  40135. * A PointLight emits the light in every direction.
  40136. * It can cast shadows.
  40137. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  40138. * ```javascript
  40139. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  40140. * ```
  40141. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40142. */
  40143. function PointLight(name, position, scene) {
  40144. var _this = _super.call(this, name, scene) || this;
  40145. _this._shadowAngle = Math.PI / 2;
  40146. _this.position = position;
  40147. return _this;
  40148. }
  40149. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  40150. /**
  40151. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40152. * This specifies what angle the shadow will use to be created.
  40153. *
  40154. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40155. */
  40156. get: function () {
  40157. return this._shadowAngle;
  40158. },
  40159. /**
  40160. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40161. * This specifies what angle the shadow will use to be created.
  40162. *
  40163. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40164. */
  40165. set: function (value) {
  40166. this._shadowAngle = value;
  40167. this.forceProjectionMatrixCompute();
  40168. },
  40169. enumerable: true,
  40170. configurable: true
  40171. });
  40172. Object.defineProperty(PointLight.prototype, "direction", {
  40173. get: function () {
  40174. return this._direction;
  40175. },
  40176. /**
  40177. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40178. */
  40179. set: function (value) {
  40180. var previousNeedCube = this.needCube();
  40181. this._direction = value;
  40182. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  40183. this._shadowGenerator.recreateShadowMap();
  40184. }
  40185. },
  40186. enumerable: true,
  40187. configurable: true
  40188. });
  40189. /**
  40190. * Returns the string "PointLight"
  40191. */
  40192. PointLight.prototype.getClassName = function () {
  40193. return "PointLight";
  40194. };
  40195. /**
  40196. * Returns the integer 0.
  40197. */
  40198. PointLight.prototype.getTypeID = function () {
  40199. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  40200. };
  40201. /**
  40202. * Specifies wether or not the shadowmap should be a cube texture.
  40203. */
  40204. PointLight.prototype.needCube = function () {
  40205. return !this.direction;
  40206. };
  40207. /**
  40208. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  40209. */
  40210. PointLight.prototype.getShadowDirection = function (faceIndex) {
  40211. if (this.direction) {
  40212. return _super.prototype.getShadowDirection.call(this, faceIndex);
  40213. }
  40214. else {
  40215. switch (faceIndex) {
  40216. case 0:
  40217. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  40218. case 1:
  40219. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  40220. case 2:
  40221. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  40222. case 3:
  40223. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  40224. case 4:
  40225. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  40226. case 5:
  40227. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  40228. }
  40229. }
  40230. return BABYLON.Vector3.Zero();
  40231. };
  40232. /**
  40233. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  40234. * - fov = PI / 2
  40235. * - aspect ratio : 1.0
  40236. * - z-near and far equal to the active camera minZ and maxZ.
  40237. * Returns the PointLight.
  40238. */
  40239. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40240. var activeCamera = this.getScene().activeCamera;
  40241. if (!activeCamera) {
  40242. return;
  40243. }
  40244. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40245. };
  40246. PointLight.prototype._buildUniformLayout = function () {
  40247. this._uniformBuffer.addUniform("vLightData", 4);
  40248. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40249. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40250. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40251. this._uniformBuffer.addUniform("depthValues", 2);
  40252. this._uniformBuffer.create();
  40253. };
  40254. /**
  40255. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  40256. * Returns the PointLight.
  40257. */
  40258. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  40259. if (this.computeTransformedInformation()) {
  40260. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  40261. return this;
  40262. }
  40263. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  40264. return this;
  40265. };
  40266. __decorate([
  40267. BABYLON.serialize()
  40268. ], PointLight.prototype, "shadowAngle", null);
  40269. return PointLight;
  40270. }(BABYLON.ShadowLight));
  40271. BABYLON.PointLight = PointLight;
  40272. })(BABYLON || (BABYLON = {}));
  40273. //# sourceMappingURL=babylon.pointLight.js.map
  40274. var BABYLON;
  40275. (function (BABYLON) {
  40276. var DirectionalLight = /** @class */ (function (_super) {
  40277. __extends(DirectionalLight, _super);
  40278. /**
  40279. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  40280. * The directional light is emitted from everywhere in the given direction.
  40281. * It can cast shawdows.
  40282. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40283. */
  40284. function DirectionalLight(name, direction, scene) {
  40285. var _this = _super.call(this, name, scene) || this;
  40286. _this._shadowFrustumSize = 0;
  40287. _this._shadowOrthoScale = 0.5;
  40288. _this.autoUpdateExtends = true;
  40289. // Cache
  40290. _this._orthoLeft = Number.MAX_VALUE;
  40291. _this._orthoRight = Number.MIN_VALUE;
  40292. _this._orthoTop = Number.MIN_VALUE;
  40293. _this._orthoBottom = Number.MAX_VALUE;
  40294. _this.position = direction.scale(-1.0);
  40295. _this.direction = direction;
  40296. return _this;
  40297. }
  40298. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  40299. /**
  40300. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  40301. */
  40302. get: function () {
  40303. return this._shadowFrustumSize;
  40304. },
  40305. /**
  40306. * Specifies a fix frustum size for the shadow generation.
  40307. */
  40308. set: function (value) {
  40309. this._shadowFrustumSize = value;
  40310. this.forceProjectionMatrixCompute();
  40311. },
  40312. enumerable: true,
  40313. configurable: true
  40314. });
  40315. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  40316. get: function () {
  40317. return this._shadowOrthoScale;
  40318. },
  40319. set: function (value) {
  40320. this._shadowOrthoScale = value;
  40321. this.forceProjectionMatrixCompute();
  40322. },
  40323. enumerable: true,
  40324. configurable: true
  40325. });
  40326. /**
  40327. * Returns the string "DirectionalLight".
  40328. */
  40329. DirectionalLight.prototype.getClassName = function () {
  40330. return "DirectionalLight";
  40331. };
  40332. /**
  40333. * Returns the integer 1.
  40334. */
  40335. DirectionalLight.prototype.getTypeID = function () {
  40336. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  40337. };
  40338. /**
  40339. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  40340. * Returns the DirectionalLight Shadow projection matrix.
  40341. */
  40342. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40343. if (this.shadowFrustumSize > 0) {
  40344. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  40345. }
  40346. else {
  40347. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40348. }
  40349. };
  40350. /**
  40351. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  40352. * Returns the DirectionalLight Shadow projection matrix.
  40353. */
  40354. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  40355. var activeCamera = this.getScene().activeCamera;
  40356. if (!activeCamera) {
  40357. return;
  40358. }
  40359. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40360. };
  40361. /**
  40362. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  40363. * Returns the DirectionalLight Shadow projection matrix.
  40364. */
  40365. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40366. var activeCamera = this.getScene().activeCamera;
  40367. if (!activeCamera) {
  40368. return;
  40369. }
  40370. // Check extends
  40371. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  40372. var tempVector3 = BABYLON.Vector3.Zero();
  40373. this._orthoLeft = Number.MAX_VALUE;
  40374. this._orthoRight = Number.MIN_VALUE;
  40375. this._orthoTop = Number.MIN_VALUE;
  40376. this._orthoBottom = Number.MAX_VALUE;
  40377. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  40378. var mesh = renderList[meshIndex];
  40379. if (!mesh) {
  40380. continue;
  40381. }
  40382. var boundingInfo = mesh.getBoundingInfo();
  40383. var boundingBox = boundingInfo.boundingBox;
  40384. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  40385. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  40386. if (tempVector3.x < this._orthoLeft)
  40387. this._orthoLeft = tempVector3.x;
  40388. if (tempVector3.y < this._orthoBottom)
  40389. this._orthoBottom = tempVector3.y;
  40390. if (tempVector3.x > this._orthoRight)
  40391. this._orthoRight = tempVector3.x;
  40392. if (tempVector3.y > this._orthoTop)
  40393. this._orthoTop = tempVector3.y;
  40394. }
  40395. }
  40396. }
  40397. var xOffset = this._orthoRight - this._orthoLeft;
  40398. var yOffset = this._orthoTop - this._orthoBottom;
  40399. 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);
  40400. };
  40401. DirectionalLight.prototype._buildUniformLayout = function () {
  40402. this._uniformBuffer.addUniform("vLightData", 4);
  40403. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40404. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40405. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40406. this._uniformBuffer.addUniform("depthValues", 2);
  40407. this._uniformBuffer.create();
  40408. };
  40409. /**
  40410. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  40411. * Returns the DirectionalLight.
  40412. */
  40413. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  40414. if (this.computeTransformedInformation()) {
  40415. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  40416. return this;
  40417. }
  40418. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  40419. return this;
  40420. };
  40421. /**
  40422. * Gets the minZ used for shadow according to both the scene and the light.
  40423. *
  40424. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40425. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40426. * @param activeCamera
  40427. */
  40428. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  40429. return 1;
  40430. };
  40431. /**
  40432. * Gets the maxZ used for shadow according to both the scene and the light.
  40433. *
  40434. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40435. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40436. * @param activeCamera
  40437. */
  40438. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  40439. return 1;
  40440. };
  40441. __decorate([
  40442. BABYLON.serialize()
  40443. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  40444. __decorate([
  40445. BABYLON.serialize()
  40446. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  40447. __decorate([
  40448. BABYLON.serialize()
  40449. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  40450. return DirectionalLight;
  40451. }(BABYLON.ShadowLight));
  40452. BABYLON.DirectionalLight = DirectionalLight;
  40453. })(BABYLON || (BABYLON = {}));
  40454. //# sourceMappingURL=babylon.directionalLight.js.map
  40455. var BABYLON;
  40456. (function (BABYLON) {
  40457. var SpotLight = /** @class */ (function (_super) {
  40458. __extends(SpotLight, _super);
  40459. /**
  40460. * Creates a SpotLight object in the scene with the passed parameters :
  40461. * - `position` (Vector3) is the initial SpotLight position,
  40462. * - `direction` (Vector3) is the initial SpotLight direction,
  40463. * - `angle` (float, in radians) is the spot light cone angle,
  40464. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  40465. * A spot light is a simply light oriented cone.
  40466. * It can cast shadows.
  40467. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40468. */
  40469. function SpotLight(name, position, direction, angle, exponent, scene) {
  40470. var _this = _super.call(this, name, scene) || this;
  40471. _this.position = position;
  40472. _this.direction = direction;
  40473. _this.angle = angle;
  40474. _this.exponent = exponent;
  40475. return _this;
  40476. }
  40477. Object.defineProperty(SpotLight.prototype, "angle", {
  40478. get: function () {
  40479. return this._angle;
  40480. },
  40481. set: function (value) {
  40482. this._angle = value;
  40483. this.forceProjectionMatrixCompute();
  40484. },
  40485. enumerable: true,
  40486. configurable: true
  40487. });
  40488. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  40489. get: function () {
  40490. return this._shadowAngleScale;
  40491. },
  40492. /**
  40493. * Allows scaling the angle of the light for shadow generation only.
  40494. */
  40495. set: function (value) {
  40496. this._shadowAngleScale = value;
  40497. this.forceProjectionMatrixCompute();
  40498. },
  40499. enumerable: true,
  40500. configurable: true
  40501. });
  40502. /**
  40503. * Returns the string "SpotLight".
  40504. */
  40505. SpotLight.prototype.getClassName = function () {
  40506. return "SpotLight";
  40507. };
  40508. /**
  40509. * Returns the integer 2.
  40510. */
  40511. SpotLight.prototype.getTypeID = function () {
  40512. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  40513. };
  40514. /**
  40515. * 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.
  40516. * Returns the SpotLight.
  40517. */
  40518. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40519. var activeCamera = this.getScene().activeCamera;
  40520. if (!activeCamera) {
  40521. return;
  40522. }
  40523. this._shadowAngleScale = this._shadowAngleScale || 1;
  40524. var angle = this._shadowAngleScale * this._angle;
  40525. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40526. };
  40527. SpotLight.prototype._buildUniformLayout = function () {
  40528. this._uniformBuffer.addUniform("vLightData", 4);
  40529. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40530. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40531. this._uniformBuffer.addUniform("vLightDirection", 3);
  40532. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40533. this._uniformBuffer.addUniform("depthValues", 2);
  40534. this._uniformBuffer.create();
  40535. };
  40536. /**
  40537. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  40538. * Return the SpotLight.
  40539. */
  40540. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  40541. var normalizeDirection;
  40542. if (this.computeTransformedInformation()) {
  40543. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  40544. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  40545. }
  40546. else {
  40547. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  40548. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40549. }
  40550. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  40551. return this;
  40552. };
  40553. __decorate([
  40554. BABYLON.serialize()
  40555. ], SpotLight.prototype, "angle", null);
  40556. __decorate([
  40557. BABYLON.serialize()
  40558. /**
  40559. * Allows scaling the angle of the light for shadow generation only.
  40560. */
  40561. ], SpotLight.prototype, "shadowAngleScale", null);
  40562. __decorate([
  40563. BABYLON.serialize()
  40564. ], SpotLight.prototype, "exponent", void 0);
  40565. return SpotLight;
  40566. }(BABYLON.ShadowLight));
  40567. BABYLON.SpotLight = SpotLight;
  40568. })(BABYLON || (BABYLON = {}));
  40569. //# sourceMappingURL=babylon.spotLight.js.map
  40570. var BABYLON;
  40571. (function (BABYLON) {
  40572. var AnimationRange = /** @class */ (function () {
  40573. function AnimationRange(name, from, to) {
  40574. this.name = name;
  40575. this.from = from;
  40576. this.to = to;
  40577. }
  40578. AnimationRange.prototype.clone = function () {
  40579. return new AnimationRange(this.name, this.from, this.to);
  40580. };
  40581. return AnimationRange;
  40582. }());
  40583. BABYLON.AnimationRange = AnimationRange;
  40584. /**
  40585. * Composed of a frame, and an action function
  40586. */
  40587. var AnimationEvent = /** @class */ (function () {
  40588. function AnimationEvent(frame, action, onlyOnce) {
  40589. this.frame = frame;
  40590. this.action = action;
  40591. this.onlyOnce = onlyOnce;
  40592. this.isDone = false;
  40593. }
  40594. return AnimationEvent;
  40595. }());
  40596. BABYLON.AnimationEvent = AnimationEvent;
  40597. var PathCursor = /** @class */ (function () {
  40598. function PathCursor(path) {
  40599. this.path = path;
  40600. this._onchange = new Array();
  40601. this.value = 0;
  40602. this.animations = new Array();
  40603. }
  40604. PathCursor.prototype.getPoint = function () {
  40605. var point = this.path.getPointAtLengthPosition(this.value);
  40606. return new BABYLON.Vector3(point.x, 0, point.y);
  40607. };
  40608. PathCursor.prototype.moveAhead = function (step) {
  40609. if (step === void 0) { step = 0.002; }
  40610. this.move(step);
  40611. return this;
  40612. };
  40613. PathCursor.prototype.moveBack = function (step) {
  40614. if (step === void 0) { step = 0.002; }
  40615. this.move(-step);
  40616. return this;
  40617. };
  40618. PathCursor.prototype.move = function (step) {
  40619. if (Math.abs(step) > 1) {
  40620. throw "step size should be less than 1.";
  40621. }
  40622. this.value += step;
  40623. this.ensureLimits();
  40624. this.raiseOnChange();
  40625. return this;
  40626. };
  40627. PathCursor.prototype.ensureLimits = function () {
  40628. while (this.value > 1) {
  40629. this.value -= 1;
  40630. }
  40631. while (this.value < 0) {
  40632. this.value += 1;
  40633. }
  40634. return this;
  40635. };
  40636. // used by animation engine
  40637. PathCursor.prototype.raiseOnChange = function () {
  40638. var _this = this;
  40639. this._onchange.forEach(function (f) { return f(_this); });
  40640. return this;
  40641. };
  40642. PathCursor.prototype.onchange = function (f) {
  40643. this._onchange.push(f);
  40644. return this;
  40645. };
  40646. return PathCursor;
  40647. }());
  40648. BABYLON.PathCursor = PathCursor;
  40649. var Animation = /** @class */ (function () {
  40650. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  40651. this.name = name;
  40652. this.targetProperty = targetProperty;
  40653. this.framePerSecond = framePerSecond;
  40654. this.dataType = dataType;
  40655. this.loopMode = loopMode;
  40656. this.enableBlending = enableBlending;
  40657. this._runtimeAnimations = new Array();
  40658. // The set of event that will be linked to this animation
  40659. this._events = new Array();
  40660. this.blendingSpeed = 0.01;
  40661. this._ranges = {};
  40662. this.targetPropertyPath = targetProperty.split(".");
  40663. this.dataType = dataType;
  40664. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  40665. }
  40666. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  40667. var dataType = undefined;
  40668. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  40669. dataType = Animation.ANIMATIONTYPE_FLOAT;
  40670. }
  40671. else if (from instanceof BABYLON.Quaternion) {
  40672. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  40673. }
  40674. else if (from instanceof BABYLON.Vector3) {
  40675. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  40676. }
  40677. else if (from instanceof BABYLON.Vector2) {
  40678. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  40679. }
  40680. else if (from instanceof BABYLON.Color3) {
  40681. dataType = Animation.ANIMATIONTYPE_COLOR3;
  40682. }
  40683. else if (from instanceof BABYLON.Size) {
  40684. dataType = Animation.ANIMATIONTYPE_SIZE;
  40685. }
  40686. if (dataType == undefined) {
  40687. return null;
  40688. }
  40689. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  40690. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  40691. animation.setKeys(keys);
  40692. if (easingFunction !== undefined) {
  40693. animation.setEasingFunction(easingFunction);
  40694. }
  40695. return animation;
  40696. };
  40697. /**
  40698. * Sets up an animation.
  40699. * @param property the property to animate
  40700. * @param animationType the animation type to apply
  40701. * @param easingFunction the easing function used in the animation
  40702. * @returns The created animation
  40703. */
  40704. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  40705. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40706. animation.setEasingFunction(easingFunction);
  40707. return animation;
  40708. };
  40709. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40710. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40711. if (!animation) {
  40712. return null;
  40713. }
  40714. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40715. };
  40716. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40717. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40718. if (!animation) {
  40719. return null;
  40720. }
  40721. node.animations.push(animation);
  40722. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40723. };
  40724. /**
  40725. * Transition property of the Camera to the target Value.
  40726. * @param property The property to transition
  40727. * @param targetValue The target Value of the property
  40728. * @param host The object where the property to animate belongs
  40729. * @param scene Scene used to run the animation
  40730. * @param frameRate Framerate (in frame/s) to use
  40731. * @param transition The transition type we want to use
  40732. * @param duration The duration of the animation, in milliseconds
  40733. * @param onAnimationEnd Call back trigger at the end of the animation.
  40734. */
  40735. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  40736. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  40737. if (duration <= 0) {
  40738. host[property] = targetValue;
  40739. if (onAnimationEnd) {
  40740. onAnimationEnd();
  40741. }
  40742. return null;
  40743. }
  40744. var endFrame = frameRate * (duration / 1000);
  40745. transition.setKeys([{
  40746. frame: 0,
  40747. value: host[property].clone ? host[property].clone() : host[property]
  40748. },
  40749. {
  40750. frame: endFrame,
  40751. value: targetValue
  40752. }]);
  40753. if (!host.animations) {
  40754. host.animations = [];
  40755. }
  40756. host.animations.push(transition);
  40757. var animation = scene.beginAnimation(host, 0, endFrame, false);
  40758. animation.onAnimationEnd = onAnimationEnd;
  40759. return animation;
  40760. };
  40761. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  40762. /**
  40763. * Return the array of runtime animations currently using this animation
  40764. */
  40765. get: function () {
  40766. return this._runtimeAnimations;
  40767. },
  40768. enumerable: true,
  40769. configurable: true
  40770. });
  40771. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  40772. get: function () {
  40773. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  40774. var runtimeAnimation = _a[_i];
  40775. if (!runtimeAnimation.isStopped) {
  40776. return true;
  40777. }
  40778. }
  40779. return false;
  40780. },
  40781. enumerable: true,
  40782. configurable: true
  40783. });
  40784. // Methods
  40785. /**
  40786. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  40787. */
  40788. Animation.prototype.toString = function (fullDetails) {
  40789. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  40790. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  40791. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  40792. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  40793. if (fullDetails) {
  40794. ret += ", Ranges: {";
  40795. var first = true;
  40796. for (var name in this._ranges) {
  40797. if (first) {
  40798. ret += ", ";
  40799. first = false;
  40800. }
  40801. ret += name;
  40802. }
  40803. ret += "}";
  40804. }
  40805. return ret;
  40806. };
  40807. /**
  40808. * Add an event to this animation.
  40809. */
  40810. Animation.prototype.addEvent = function (event) {
  40811. this._events.push(event);
  40812. };
  40813. /**
  40814. * Remove all events found at the given frame
  40815. * @param frame
  40816. */
  40817. Animation.prototype.removeEvents = function (frame) {
  40818. for (var index = 0; index < this._events.length; index++) {
  40819. if (this._events[index].frame === frame) {
  40820. this._events.splice(index, 1);
  40821. index--;
  40822. }
  40823. }
  40824. };
  40825. Animation.prototype.getEvents = function () {
  40826. return this._events;
  40827. };
  40828. Animation.prototype.createRange = function (name, from, to) {
  40829. // check name not already in use; could happen for bones after serialized
  40830. if (!this._ranges[name]) {
  40831. this._ranges[name] = new AnimationRange(name, from, to);
  40832. }
  40833. };
  40834. Animation.prototype.deleteRange = function (name, deleteFrames) {
  40835. if (deleteFrames === void 0) { deleteFrames = true; }
  40836. var range = this._ranges[name];
  40837. if (!range) {
  40838. return;
  40839. }
  40840. if (deleteFrames) {
  40841. var from = range.from;
  40842. var to = range.to;
  40843. // this loop MUST go high to low for multiple splices to work
  40844. for (var key = this._keys.length - 1; key >= 0; key--) {
  40845. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  40846. this._keys.splice(key, 1);
  40847. }
  40848. }
  40849. }
  40850. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  40851. };
  40852. Animation.prototype.getRange = function (name) {
  40853. return this._ranges[name];
  40854. };
  40855. Animation.prototype.getKeys = function () {
  40856. return this._keys;
  40857. };
  40858. Animation.prototype.getHighestFrame = function () {
  40859. var ret = 0;
  40860. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  40861. if (ret < this._keys[key].frame) {
  40862. ret = this._keys[key].frame;
  40863. }
  40864. }
  40865. return ret;
  40866. };
  40867. Animation.prototype.getEasingFunction = function () {
  40868. return this._easingFunction;
  40869. };
  40870. Animation.prototype.setEasingFunction = function (easingFunction) {
  40871. this._easingFunction = easingFunction;
  40872. };
  40873. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  40874. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  40875. };
  40876. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40877. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40878. };
  40879. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  40880. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  40881. };
  40882. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40883. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  40884. };
  40885. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  40886. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  40887. };
  40888. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40889. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40890. };
  40891. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  40892. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  40893. };
  40894. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40895. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40896. };
  40897. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  40898. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  40899. };
  40900. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  40901. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  40902. };
  40903. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  40904. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  40905. };
  40906. Animation.prototype.clone = function () {
  40907. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  40908. clone.enableBlending = this.enableBlending;
  40909. clone.blendingSpeed = this.blendingSpeed;
  40910. if (this._keys) {
  40911. clone.setKeys(this._keys);
  40912. }
  40913. if (this._ranges) {
  40914. clone._ranges = {};
  40915. for (var name in this._ranges) {
  40916. var range = this._ranges[name];
  40917. if (!range) {
  40918. continue;
  40919. }
  40920. clone._ranges[name] = range.clone();
  40921. }
  40922. }
  40923. return clone;
  40924. };
  40925. Animation.prototype.setKeys = function (values) {
  40926. this._keys = values.slice(0);
  40927. };
  40928. Animation.prototype.serialize = function () {
  40929. var serializationObject = {};
  40930. serializationObject.name = this.name;
  40931. serializationObject.property = this.targetProperty;
  40932. serializationObject.framePerSecond = this.framePerSecond;
  40933. serializationObject.dataType = this.dataType;
  40934. serializationObject.loopBehavior = this.loopMode;
  40935. serializationObject.enableBlending = this.enableBlending;
  40936. serializationObject.blendingSpeed = this.blendingSpeed;
  40937. var dataType = this.dataType;
  40938. serializationObject.keys = [];
  40939. var keys = this.getKeys();
  40940. for (var index = 0; index < keys.length; index++) {
  40941. var animationKey = keys[index];
  40942. var key = {};
  40943. key.frame = animationKey.frame;
  40944. switch (dataType) {
  40945. case Animation.ANIMATIONTYPE_FLOAT:
  40946. key.values = [animationKey.value];
  40947. break;
  40948. case Animation.ANIMATIONTYPE_QUATERNION:
  40949. case Animation.ANIMATIONTYPE_MATRIX:
  40950. case Animation.ANIMATIONTYPE_VECTOR3:
  40951. case Animation.ANIMATIONTYPE_COLOR3:
  40952. key.values = animationKey.value.asArray();
  40953. break;
  40954. }
  40955. serializationObject.keys.push(key);
  40956. }
  40957. serializationObject.ranges = [];
  40958. for (var name in this._ranges) {
  40959. var source = this._ranges[name];
  40960. if (!source) {
  40961. continue;
  40962. }
  40963. var range = {};
  40964. range.name = name;
  40965. range.from = source.from;
  40966. range.to = source.to;
  40967. serializationObject.ranges.push(range);
  40968. }
  40969. return serializationObject;
  40970. };
  40971. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  40972. get: function () {
  40973. return Animation._ANIMATIONTYPE_FLOAT;
  40974. },
  40975. enumerable: true,
  40976. configurable: true
  40977. });
  40978. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  40979. get: function () {
  40980. return Animation._ANIMATIONTYPE_VECTOR3;
  40981. },
  40982. enumerable: true,
  40983. configurable: true
  40984. });
  40985. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  40986. get: function () {
  40987. return Animation._ANIMATIONTYPE_VECTOR2;
  40988. },
  40989. enumerable: true,
  40990. configurable: true
  40991. });
  40992. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  40993. get: function () {
  40994. return Animation._ANIMATIONTYPE_SIZE;
  40995. },
  40996. enumerable: true,
  40997. configurable: true
  40998. });
  40999. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  41000. get: function () {
  41001. return Animation._ANIMATIONTYPE_QUATERNION;
  41002. },
  41003. enumerable: true,
  41004. configurable: true
  41005. });
  41006. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  41007. get: function () {
  41008. return Animation._ANIMATIONTYPE_MATRIX;
  41009. },
  41010. enumerable: true,
  41011. configurable: true
  41012. });
  41013. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  41014. get: function () {
  41015. return Animation._ANIMATIONTYPE_COLOR3;
  41016. },
  41017. enumerable: true,
  41018. configurable: true
  41019. });
  41020. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  41021. get: function () {
  41022. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  41023. },
  41024. enumerable: true,
  41025. configurable: true
  41026. });
  41027. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  41028. get: function () {
  41029. return Animation._ANIMATIONLOOPMODE_CYCLE;
  41030. },
  41031. enumerable: true,
  41032. configurable: true
  41033. });
  41034. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  41035. get: function () {
  41036. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  41037. },
  41038. enumerable: true,
  41039. configurable: true
  41040. });
  41041. Animation.Parse = function (parsedAnimation) {
  41042. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  41043. var dataType = parsedAnimation.dataType;
  41044. var keys = [];
  41045. var data;
  41046. var index;
  41047. if (parsedAnimation.enableBlending) {
  41048. animation.enableBlending = parsedAnimation.enableBlending;
  41049. }
  41050. if (parsedAnimation.blendingSpeed) {
  41051. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  41052. }
  41053. for (index = 0; index < parsedAnimation.keys.length; index++) {
  41054. var key = parsedAnimation.keys[index];
  41055. var inTangent;
  41056. var outTangent;
  41057. switch (dataType) {
  41058. case Animation.ANIMATIONTYPE_FLOAT:
  41059. data = key.values[0];
  41060. if (key.values.length >= 1) {
  41061. inTangent = key.values[1];
  41062. }
  41063. if (key.values.length >= 2) {
  41064. outTangent = key.values[2];
  41065. }
  41066. break;
  41067. case Animation.ANIMATIONTYPE_QUATERNION:
  41068. data = BABYLON.Quaternion.FromArray(key.values);
  41069. if (key.values.length >= 8) {
  41070. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  41071. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  41072. inTangent = _inTangent;
  41073. }
  41074. }
  41075. if (key.values.length >= 12) {
  41076. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  41077. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  41078. outTangent = _outTangent;
  41079. }
  41080. }
  41081. break;
  41082. case Animation.ANIMATIONTYPE_MATRIX:
  41083. data = BABYLON.Matrix.FromArray(key.values);
  41084. break;
  41085. case Animation.ANIMATIONTYPE_COLOR3:
  41086. data = BABYLON.Color3.FromArray(key.values);
  41087. break;
  41088. case Animation.ANIMATIONTYPE_VECTOR3:
  41089. default:
  41090. data = BABYLON.Vector3.FromArray(key.values);
  41091. break;
  41092. }
  41093. var keyData = {};
  41094. keyData.frame = key.frame;
  41095. keyData.value = data;
  41096. if (inTangent != undefined) {
  41097. keyData.inTangent = inTangent;
  41098. }
  41099. if (outTangent != undefined) {
  41100. keyData.outTangent = outTangent;
  41101. }
  41102. keys.push(keyData);
  41103. }
  41104. animation.setKeys(keys);
  41105. if (parsedAnimation.ranges) {
  41106. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  41107. data = parsedAnimation.ranges[index];
  41108. animation.createRange(data.name, data.from, data.to);
  41109. }
  41110. }
  41111. return animation;
  41112. };
  41113. Animation.AppendSerializedAnimations = function (source, destination) {
  41114. if (source.animations) {
  41115. destination.animations = [];
  41116. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  41117. var animation = source.animations[animationIndex];
  41118. destination.animations.push(animation.serialize());
  41119. }
  41120. }
  41121. };
  41122. Animation.AllowMatricesInterpolation = false;
  41123. // Statics
  41124. Animation._ANIMATIONTYPE_FLOAT = 0;
  41125. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  41126. Animation._ANIMATIONTYPE_QUATERNION = 2;
  41127. Animation._ANIMATIONTYPE_MATRIX = 3;
  41128. Animation._ANIMATIONTYPE_COLOR3 = 4;
  41129. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  41130. Animation._ANIMATIONTYPE_SIZE = 6;
  41131. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  41132. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  41133. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  41134. return Animation;
  41135. }());
  41136. BABYLON.Animation = Animation;
  41137. })(BABYLON || (BABYLON = {}));
  41138. //# sourceMappingURL=babylon.animation.js.map
  41139. var BABYLON;
  41140. (function (BABYLON) {
  41141. var RuntimeAnimation = /** @class */ (function () {
  41142. function RuntimeAnimation(target, animation) {
  41143. this._offsetsCache = {};
  41144. this._highLimitsCache = {};
  41145. this._stopped = false;
  41146. this._blendingFactor = 0;
  41147. this._ratioOffset = 0;
  41148. this._animation = animation;
  41149. this._target = target;
  41150. animation._runtimeAnimations.push(this);
  41151. }
  41152. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  41153. get: function () {
  41154. return this._animation;
  41155. },
  41156. enumerable: true,
  41157. configurable: true
  41158. });
  41159. RuntimeAnimation.prototype.reset = function () {
  41160. this._offsetsCache = {};
  41161. this._highLimitsCache = {};
  41162. this.currentFrame = 0;
  41163. this._blendingFactor = 0;
  41164. this._originalBlendValue = null;
  41165. };
  41166. RuntimeAnimation.prototype.isStopped = function () {
  41167. return this._stopped;
  41168. };
  41169. RuntimeAnimation.prototype.dispose = function () {
  41170. var index = this._animation.runtimeAnimations.indexOf(this);
  41171. if (index > -1) {
  41172. this._animation.runtimeAnimations.splice(index, 1);
  41173. }
  41174. };
  41175. RuntimeAnimation.prototype._getKeyValue = function (value) {
  41176. if (typeof value === "function") {
  41177. return value();
  41178. }
  41179. return value;
  41180. };
  41181. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  41182. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  41183. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  41184. }
  41185. this.currentFrame = currentFrame;
  41186. var keys = this._animation.getKeys();
  41187. // Try to get a hash to find the right key
  41188. 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));
  41189. if (keys[startKeyIndex].frame >= currentFrame) {
  41190. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  41191. startKeyIndex--;
  41192. }
  41193. }
  41194. for (var key = startKeyIndex; key < keys.length; key++) {
  41195. var endKey = keys[key + 1];
  41196. if (endKey.frame >= currentFrame) {
  41197. var startKey = keys[key];
  41198. var startValue = this._getKeyValue(startKey.value);
  41199. var endValue = this._getKeyValue(endKey.value);
  41200. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  41201. var frameDelta = endKey.frame - startKey.frame;
  41202. // gradient : percent of currentFrame between the frame inf and the frame sup
  41203. var gradient = (currentFrame - startKey.frame) / frameDelta;
  41204. // check for easingFunction and correction of gradient
  41205. var easingFunction = this._animation.getEasingFunction();
  41206. if (easingFunction != null) {
  41207. gradient = easingFunction.ease(gradient);
  41208. }
  41209. switch (this._animation.dataType) {
  41210. // Float
  41211. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41212. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  41213. switch (loopMode) {
  41214. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41215. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41216. return floatValue;
  41217. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41218. return offsetValue * repeatCount + floatValue;
  41219. }
  41220. break;
  41221. // Quaternion
  41222. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41223. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  41224. switch (loopMode) {
  41225. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41226. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41227. return quatValue;
  41228. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41229. return quatValue.add(offsetValue.scale(repeatCount));
  41230. }
  41231. return quatValue;
  41232. // Vector3
  41233. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41234. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  41235. switch (loopMode) {
  41236. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41237. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41238. return vec3Value;
  41239. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41240. return vec3Value.add(offsetValue.scale(repeatCount));
  41241. }
  41242. // Vector2
  41243. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41244. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  41245. switch (loopMode) {
  41246. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41247. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41248. return vec2Value;
  41249. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41250. return vec2Value.add(offsetValue.scale(repeatCount));
  41251. }
  41252. // Size
  41253. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41254. switch (loopMode) {
  41255. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41256. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41257. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  41258. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41259. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41260. }
  41261. // Color3
  41262. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41263. switch (loopMode) {
  41264. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41265. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41266. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  41267. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41268. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41269. }
  41270. // Matrix
  41271. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  41272. switch (loopMode) {
  41273. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41274. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41275. if (BABYLON.Animation.AllowMatricesInterpolation) {
  41276. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  41277. }
  41278. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41279. return startValue;
  41280. }
  41281. default:
  41282. break;
  41283. }
  41284. break;
  41285. }
  41286. }
  41287. return this._getKeyValue(keys[keys.length - 1].value);
  41288. };
  41289. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  41290. if (blend === void 0) { blend = false; }
  41291. // Set value
  41292. var path;
  41293. var destination;
  41294. var targetPropertyPath = this._animation.targetPropertyPath;
  41295. if (targetPropertyPath.length > 1) {
  41296. var property = this._target[targetPropertyPath[0]];
  41297. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  41298. property = property[targetPropertyPath[index]];
  41299. }
  41300. path = targetPropertyPath[targetPropertyPath.length - 1];
  41301. destination = property;
  41302. }
  41303. else {
  41304. path = targetPropertyPath[0];
  41305. destination = this._target;
  41306. }
  41307. // Blending
  41308. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  41309. if (!this._originalBlendValue) {
  41310. if (destination[path].clone) {
  41311. this._originalBlendValue = destination[path].clone();
  41312. }
  41313. else {
  41314. this._originalBlendValue = destination[path];
  41315. }
  41316. }
  41317. if (this._originalBlendValue.prototype) {
  41318. if (this._originalBlendValue.prototype.Lerp) {
  41319. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  41320. }
  41321. else {
  41322. destination[path] = currentValue;
  41323. }
  41324. }
  41325. else if (this._originalBlendValue.m) {
  41326. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  41327. }
  41328. else {
  41329. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  41330. }
  41331. this._blendingFactor += this._animation.blendingSpeed;
  41332. }
  41333. else {
  41334. destination[path] = currentValue;
  41335. }
  41336. if (this._target.markAsDirty) {
  41337. this._target.markAsDirty(this._animation.targetProperty);
  41338. }
  41339. };
  41340. RuntimeAnimation.prototype.goToFrame = function (frame) {
  41341. var keys = this._animation.getKeys();
  41342. if (frame < keys[0].frame) {
  41343. frame = keys[0].frame;
  41344. }
  41345. else if (frame > keys[keys.length - 1].frame) {
  41346. frame = keys[keys.length - 1].frame;
  41347. }
  41348. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  41349. this.setValue(currentValue);
  41350. };
  41351. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  41352. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  41353. this._ratioOffset = this._previousRatio - newRatio;
  41354. };
  41355. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  41356. if (blend === void 0) { blend = false; }
  41357. var targetPropertyPath = this._animation.targetPropertyPath;
  41358. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  41359. this._stopped = true;
  41360. return false;
  41361. }
  41362. var returnValue = true;
  41363. var keys = this._animation.getKeys();
  41364. // Adding a start key at frame 0 if missing
  41365. if (keys[0].frame !== 0) {
  41366. var newKey = { frame: 0, value: keys[0].value };
  41367. keys.splice(0, 0, newKey);
  41368. }
  41369. // Check limits
  41370. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  41371. from = keys[0].frame;
  41372. }
  41373. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  41374. to = keys[keys.length - 1].frame;
  41375. }
  41376. //to and from cannot be the same key
  41377. if (from === to) {
  41378. if (from > keys[0].frame) {
  41379. from--;
  41380. }
  41381. else if (to < keys[keys.length - 1].frame) {
  41382. to++;
  41383. }
  41384. }
  41385. // Compute ratio
  41386. var range = to - from;
  41387. var offsetValue;
  41388. // ratio represents the frame delta between from and to
  41389. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  41390. var highLimitValue = 0;
  41391. this._previousDelay = delay;
  41392. this._previousRatio = ratio;
  41393. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  41394. returnValue = false;
  41395. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  41396. }
  41397. else {
  41398. // Get max value if required
  41399. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  41400. var keyOffset = to.toString() + from.toString();
  41401. if (!this._offsetsCache[keyOffset]) {
  41402. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  41403. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  41404. switch (this._animation.dataType) {
  41405. // Float
  41406. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41407. this._offsetsCache[keyOffset] = toValue - fromValue;
  41408. break;
  41409. // Quaternion
  41410. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41411. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41412. break;
  41413. // Vector3
  41414. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41415. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41416. // Vector2
  41417. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41418. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41419. // Size
  41420. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41421. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41422. // Color3
  41423. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41424. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41425. default:
  41426. break;
  41427. }
  41428. this._highLimitsCache[keyOffset] = toValue;
  41429. }
  41430. highLimitValue = this._highLimitsCache[keyOffset];
  41431. offsetValue = this._offsetsCache[keyOffset];
  41432. }
  41433. }
  41434. if (offsetValue === undefined) {
  41435. switch (this._animation.dataType) {
  41436. // Float
  41437. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41438. offsetValue = 0;
  41439. break;
  41440. // Quaternion
  41441. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41442. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  41443. break;
  41444. // Vector3
  41445. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41446. offsetValue = BABYLON.Vector3.Zero();
  41447. break;
  41448. // Vector2
  41449. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41450. offsetValue = BABYLON.Vector2.Zero();
  41451. break;
  41452. // Size
  41453. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41454. offsetValue = BABYLON.Size.Zero();
  41455. break;
  41456. // Color3
  41457. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41458. offsetValue = BABYLON.Color3.Black();
  41459. }
  41460. }
  41461. // Compute value
  41462. var repeatCount = (ratio / range) >> 0;
  41463. var currentFrame = returnValue ? from + ratio % range : to;
  41464. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  41465. // Set value
  41466. this.setValue(currentValue);
  41467. // Check events
  41468. var events = this._animation.getEvents();
  41469. for (var index = 0; index < events.length; index++) {
  41470. // Make sure current frame has passed event frame and that event frame is within the current range
  41471. // Also, handle both forward and reverse animations
  41472. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  41473. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  41474. var event = events[index];
  41475. if (!event.isDone) {
  41476. // If event should be done only once, remove it.
  41477. if (event.onlyOnce) {
  41478. events.splice(index, 1);
  41479. index--;
  41480. }
  41481. event.isDone = true;
  41482. event.action();
  41483. } // Don't do anything if the event has already be done.
  41484. }
  41485. else if (events[index].isDone && !events[index].onlyOnce) {
  41486. // reset event, the animation is looping
  41487. events[index].isDone = false;
  41488. }
  41489. }
  41490. if (!returnValue) {
  41491. this._stopped = true;
  41492. }
  41493. return returnValue;
  41494. };
  41495. return RuntimeAnimation;
  41496. }());
  41497. BABYLON.RuntimeAnimation = RuntimeAnimation;
  41498. })(BABYLON || (BABYLON = {}));
  41499. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  41500. var BABYLON;
  41501. (function (BABYLON) {
  41502. var Animatable = /** @class */ (function () {
  41503. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  41504. if (fromFrame === void 0) { fromFrame = 0; }
  41505. if (toFrame === void 0) { toFrame = 100; }
  41506. if (loopAnimation === void 0) { loopAnimation = false; }
  41507. if (speedRatio === void 0) { speedRatio = 1.0; }
  41508. this.target = target;
  41509. this.fromFrame = fromFrame;
  41510. this.toFrame = toFrame;
  41511. this.loopAnimation = loopAnimation;
  41512. this.onAnimationEnd = onAnimationEnd;
  41513. this._localDelayOffset = null;
  41514. this._pausedDelay = null;
  41515. this._runtimeAnimations = new Array();
  41516. this._paused = false;
  41517. this._speedRatio = 1;
  41518. this.animationStarted = false;
  41519. if (animations) {
  41520. this.appendAnimations(target, animations);
  41521. }
  41522. this._speedRatio = speedRatio;
  41523. this._scene = scene;
  41524. scene._activeAnimatables.push(this);
  41525. }
  41526. Object.defineProperty(Animatable.prototype, "speedRatio", {
  41527. get: function () {
  41528. return this._speedRatio;
  41529. },
  41530. set: function (value) {
  41531. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  41532. var animation = this._runtimeAnimations[index];
  41533. animation._prepareForSpeedRatioChange(value);
  41534. }
  41535. this._speedRatio = value;
  41536. },
  41537. enumerable: true,
  41538. configurable: true
  41539. });
  41540. // Methods
  41541. Animatable.prototype.getAnimations = function () {
  41542. return this._runtimeAnimations;
  41543. };
  41544. Animatable.prototype.appendAnimations = function (target, animations) {
  41545. for (var index = 0; index < animations.length; index++) {
  41546. var animation = animations[index];
  41547. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  41548. }
  41549. };
  41550. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  41551. var runtimeAnimations = this._runtimeAnimations;
  41552. for (var index = 0; index < runtimeAnimations.length; index++) {
  41553. if (runtimeAnimations[index].animation.targetProperty === property) {
  41554. return runtimeAnimations[index].animation;
  41555. }
  41556. }
  41557. return null;
  41558. };
  41559. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  41560. var runtimeAnimations = this._runtimeAnimations;
  41561. for (var index = 0; index < runtimeAnimations.length; index++) {
  41562. if (runtimeAnimations[index].animation.targetProperty === property) {
  41563. return runtimeAnimations[index];
  41564. }
  41565. }
  41566. return null;
  41567. };
  41568. Animatable.prototype.reset = function () {
  41569. var runtimeAnimations = this._runtimeAnimations;
  41570. for (var index = 0; index < runtimeAnimations.length; index++) {
  41571. runtimeAnimations[index].reset();
  41572. }
  41573. this._localDelayOffset = null;
  41574. this._pausedDelay = null;
  41575. };
  41576. Animatable.prototype.enableBlending = function (blendingSpeed) {
  41577. var runtimeAnimations = this._runtimeAnimations;
  41578. for (var index = 0; index < runtimeAnimations.length; index++) {
  41579. runtimeAnimations[index].animation.enableBlending = true;
  41580. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  41581. }
  41582. };
  41583. Animatable.prototype.disableBlending = function () {
  41584. var runtimeAnimations = this._runtimeAnimations;
  41585. for (var index = 0; index < runtimeAnimations.length; index++) {
  41586. runtimeAnimations[index].animation.enableBlending = false;
  41587. }
  41588. };
  41589. Animatable.prototype.goToFrame = function (frame) {
  41590. var runtimeAnimations = this._runtimeAnimations;
  41591. if (runtimeAnimations[0]) {
  41592. var fps = runtimeAnimations[0].animation.framePerSecond;
  41593. var currentFrame = runtimeAnimations[0].currentFrame;
  41594. var adjustTime = frame - currentFrame;
  41595. var delay = adjustTime * 1000 / fps;
  41596. if (this._localDelayOffset === null) {
  41597. this._localDelayOffset = 0;
  41598. }
  41599. this._localDelayOffset -= delay;
  41600. }
  41601. for (var index = 0; index < runtimeAnimations.length; index++) {
  41602. runtimeAnimations[index].goToFrame(frame);
  41603. }
  41604. };
  41605. Animatable.prototype.pause = function () {
  41606. if (this._paused) {
  41607. return;
  41608. }
  41609. this._paused = true;
  41610. };
  41611. Animatable.prototype.restart = function () {
  41612. this._paused = false;
  41613. };
  41614. Animatable.prototype.stop = function (animationName) {
  41615. if (animationName) {
  41616. var idx = this._scene._activeAnimatables.indexOf(this);
  41617. if (idx > -1) {
  41618. var runtimeAnimations = this._runtimeAnimations;
  41619. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  41620. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  41621. continue;
  41622. }
  41623. runtimeAnimations[index].dispose();
  41624. runtimeAnimations.splice(index, 1);
  41625. }
  41626. if (runtimeAnimations.length == 0) {
  41627. this._scene._activeAnimatables.splice(idx, 1);
  41628. if (this.onAnimationEnd) {
  41629. this.onAnimationEnd();
  41630. }
  41631. }
  41632. }
  41633. }
  41634. else {
  41635. var index = this._scene._activeAnimatables.indexOf(this);
  41636. if (index > -1) {
  41637. this._scene._activeAnimatables.splice(index, 1);
  41638. var runtimeAnimations = this._runtimeAnimations;
  41639. for (var index = 0; index < runtimeAnimations.length; index++) {
  41640. runtimeAnimations[index].dispose();
  41641. }
  41642. if (this.onAnimationEnd) {
  41643. this.onAnimationEnd();
  41644. }
  41645. }
  41646. }
  41647. };
  41648. Animatable.prototype._animate = function (delay) {
  41649. if (this._paused) {
  41650. this.animationStarted = false;
  41651. if (this._pausedDelay === null) {
  41652. this._pausedDelay = delay;
  41653. }
  41654. return true;
  41655. }
  41656. if (this._localDelayOffset === null) {
  41657. this._localDelayOffset = delay;
  41658. }
  41659. else if (this._pausedDelay !== null) {
  41660. this._localDelayOffset += delay - this._pausedDelay;
  41661. this._pausedDelay = null;
  41662. }
  41663. // Animating
  41664. var running = false;
  41665. var runtimeAnimations = this._runtimeAnimations;
  41666. var index;
  41667. for (index = 0; index < runtimeAnimations.length; index++) {
  41668. var animation = runtimeAnimations[index];
  41669. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  41670. running = running || isRunning;
  41671. }
  41672. this.animationStarted = running;
  41673. if (!running) {
  41674. // Remove from active animatables
  41675. index = this._scene._activeAnimatables.indexOf(this);
  41676. this._scene._activeAnimatables.splice(index, 1);
  41677. // Dispose all runtime animations
  41678. for (index = 0; index < runtimeAnimations.length; index++) {
  41679. runtimeAnimations[index].dispose();
  41680. }
  41681. }
  41682. if (!running && this.onAnimationEnd) {
  41683. this.onAnimationEnd();
  41684. this.onAnimationEnd = null;
  41685. }
  41686. return running;
  41687. };
  41688. return Animatable;
  41689. }());
  41690. BABYLON.Animatable = Animatable;
  41691. })(BABYLON || (BABYLON = {}));
  41692. //# sourceMappingURL=babylon.animatable.js.map
  41693. var BABYLON;
  41694. (function (BABYLON) {
  41695. var EasingFunction = /** @class */ (function () {
  41696. function EasingFunction() {
  41697. // Properties
  41698. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  41699. }
  41700. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  41701. get: function () {
  41702. return EasingFunction._EASINGMODE_EASEIN;
  41703. },
  41704. enumerable: true,
  41705. configurable: true
  41706. });
  41707. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  41708. get: function () {
  41709. return EasingFunction._EASINGMODE_EASEOUT;
  41710. },
  41711. enumerable: true,
  41712. configurable: true
  41713. });
  41714. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  41715. get: function () {
  41716. return EasingFunction._EASINGMODE_EASEINOUT;
  41717. },
  41718. enumerable: true,
  41719. configurable: true
  41720. });
  41721. EasingFunction.prototype.setEasingMode = function (easingMode) {
  41722. var n = Math.min(Math.max(easingMode, 0), 2);
  41723. this._easingMode = n;
  41724. };
  41725. EasingFunction.prototype.getEasingMode = function () {
  41726. return this._easingMode;
  41727. };
  41728. EasingFunction.prototype.easeInCore = function (gradient) {
  41729. throw new Error('You must implement this method');
  41730. };
  41731. EasingFunction.prototype.ease = function (gradient) {
  41732. switch (this._easingMode) {
  41733. case EasingFunction.EASINGMODE_EASEIN:
  41734. return this.easeInCore(gradient);
  41735. case EasingFunction.EASINGMODE_EASEOUT:
  41736. return (1 - this.easeInCore(1 - gradient));
  41737. }
  41738. if (gradient >= 0.5) {
  41739. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  41740. }
  41741. return (this.easeInCore(gradient * 2) * 0.5);
  41742. };
  41743. //Statics
  41744. EasingFunction._EASINGMODE_EASEIN = 0;
  41745. EasingFunction._EASINGMODE_EASEOUT = 1;
  41746. EasingFunction._EASINGMODE_EASEINOUT = 2;
  41747. return EasingFunction;
  41748. }());
  41749. BABYLON.EasingFunction = EasingFunction;
  41750. var CircleEase = /** @class */ (function (_super) {
  41751. __extends(CircleEase, _super);
  41752. function CircleEase() {
  41753. return _super !== null && _super.apply(this, arguments) || this;
  41754. }
  41755. CircleEase.prototype.easeInCore = function (gradient) {
  41756. gradient = Math.max(0, Math.min(1, gradient));
  41757. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  41758. };
  41759. return CircleEase;
  41760. }(EasingFunction));
  41761. BABYLON.CircleEase = CircleEase;
  41762. var BackEase = /** @class */ (function (_super) {
  41763. __extends(BackEase, _super);
  41764. function BackEase(amplitude) {
  41765. if (amplitude === void 0) { amplitude = 1; }
  41766. var _this = _super.call(this) || this;
  41767. _this.amplitude = amplitude;
  41768. return _this;
  41769. }
  41770. BackEase.prototype.easeInCore = function (gradient) {
  41771. var num = Math.max(0, this.amplitude);
  41772. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  41773. };
  41774. return BackEase;
  41775. }(EasingFunction));
  41776. BABYLON.BackEase = BackEase;
  41777. var BounceEase = /** @class */ (function (_super) {
  41778. __extends(BounceEase, _super);
  41779. function BounceEase(bounces, bounciness) {
  41780. if (bounces === void 0) { bounces = 3; }
  41781. if (bounciness === void 0) { bounciness = 2; }
  41782. var _this = _super.call(this) || this;
  41783. _this.bounces = bounces;
  41784. _this.bounciness = bounciness;
  41785. return _this;
  41786. }
  41787. BounceEase.prototype.easeInCore = function (gradient) {
  41788. var y = Math.max(0.0, this.bounces);
  41789. var bounciness = this.bounciness;
  41790. if (bounciness <= 1.0) {
  41791. bounciness = 1.001;
  41792. }
  41793. var num9 = Math.pow(bounciness, y);
  41794. var num5 = 1.0 - bounciness;
  41795. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  41796. var num15 = gradient * num4;
  41797. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  41798. var num3 = Math.floor(num65);
  41799. var num13 = num3 + 1.0;
  41800. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  41801. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  41802. var num7 = (num8 + num12) * 0.5;
  41803. var num6 = gradient - num7;
  41804. var num2 = num7 - num8;
  41805. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  41806. };
  41807. return BounceEase;
  41808. }(EasingFunction));
  41809. BABYLON.BounceEase = BounceEase;
  41810. var CubicEase = /** @class */ (function (_super) {
  41811. __extends(CubicEase, _super);
  41812. function CubicEase() {
  41813. return _super !== null && _super.apply(this, arguments) || this;
  41814. }
  41815. CubicEase.prototype.easeInCore = function (gradient) {
  41816. return (gradient * gradient * gradient);
  41817. };
  41818. return CubicEase;
  41819. }(EasingFunction));
  41820. BABYLON.CubicEase = CubicEase;
  41821. var ElasticEase = /** @class */ (function (_super) {
  41822. __extends(ElasticEase, _super);
  41823. function ElasticEase(oscillations, springiness) {
  41824. if (oscillations === void 0) { oscillations = 3; }
  41825. if (springiness === void 0) { springiness = 3; }
  41826. var _this = _super.call(this) || this;
  41827. _this.oscillations = oscillations;
  41828. _this.springiness = springiness;
  41829. return _this;
  41830. }
  41831. ElasticEase.prototype.easeInCore = function (gradient) {
  41832. var num2;
  41833. var num3 = Math.max(0.0, this.oscillations);
  41834. var num = Math.max(0.0, this.springiness);
  41835. if (num == 0) {
  41836. num2 = gradient;
  41837. }
  41838. else {
  41839. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  41840. }
  41841. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  41842. };
  41843. return ElasticEase;
  41844. }(EasingFunction));
  41845. BABYLON.ElasticEase = ElasticEase;
  41846. var ExponentialEase = /** @class */ (function (_super) {
  41847. __extends(ExponentialEase, _super);
  41848. function ExponentialEase(exponent) {
  41849. if (exponent === void 0) { exponent = 2; }
  41850. var _this = _super.call(this) || this;
  41851. _this.exponent = exponent;
  41852. return _this;
  41853. }
  41854. ExponentialEase.prototype.easeInCore = function (gradient) {
  41855. if (this.exponent <= 0) {
  41856. return gradient;
  41857. }
  41858. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  41859. };
  41860. return ExponentialEase;
  41861. }(EasingFunction));
  41862. BABYLON.ExponentialEase = ExponentialEase;
  41863. var PowerEase = /** @class */ (function (_super) {
  41864. __extends(PowerEase, _super);
  41865. function PowerEase(power) {
  41866. if (power === void 0) { power = 2; }
  41867. var _this = _super.call(this) || this;
  41868. _this.power = power;
  41869. return _this;
  41870. }
  41871. PowerEase.prototype.easeInCore = function (gradient) {
  41872. var y = Math.max(0.0, this.power);
  41873. return Math.pow(gradient, y);
  41874. };
  41875. return PowerEase;
  41876. }(EasingFunction));
  41877. BABYLON.PowerEase = PowerEase;
  41878. var QuadraticEase = /** @class */ (function (_super) {
  41879. __extends(QuadraticEase, _super);
  41880. function QuadraticEase() {
  41881. return _super !== null && _super.apply(this, arguments) || this;
  41882. }
  41883. QuadraticEase.prototype.easeInCore = function (gradient) {
  41884. return (gradient * gradient);
  41885. };
  41886. return QuadraticEase;
  41887. }(EasingFunction));
  41888. BABYLON.QuadraticEase = QuadraticEase;
  41889. var QuarticEase = /** @class */ (function (_super) {
  41890. __extends(QuarticEase, _super);
  41891. function QuarticEase() {
  41892. return _super !== null && _super.apply(this, arguments) || this;
  41893. }
  41894. QuarticEase.prototype.easeInCore = function (gradient) {
  41895. return (gradient * gradient * gradient * gradient);
  41896. };
  41897. return QuarticEase;
  41898. }(EasingFunction));
  41899. BABYLON.QuarticEase = QuarticEase;
  41900. var QuinticEase = /** @class */ (function (_super) {
  41901. __extends(QuinticEase, _super);
  41902. function QuinticEase() {
  41903. return _super !== null && _super.apply(this, arguments) || this;
  41904. }
  41905. QuinticEase.prototype.easeInCore = function (gradient) {
  41906. return (gradient * gradient * gradient * gradient * gradient);
  41907. };
  41908. return QuinticEase;
  41909. }(EasingFunction));
  41910. BABYLON.QuinticEase = QuinticEase;
  41911. var SineEase = /** @class */ (function (_super) {
  41912. __extends(SineEase, _super);
  41913. function SineEase() {
  41914. return _super !== null && _super.apply(this, arguments) || this;
  41915. }
  41916. SineEase.prototype.easeInCore = function (gradient) {
  41917. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  41918. };
  41919. return SineEase;
  41920. }(EasingFunction));
  41921. BABYLON.SineEase = SineEase;
  41922. var BezierCurveEase = /** @class */ (function (_super) {
  41923. __extends(BezierCurveEase, _super);
  41924. function BezierCurveEase(x1, y1, x2, y2) {
  41925. if (x1 === void 0) { x1 = 0; }
  41926. if (y1 === void 0) { y1 = 0; }
  41927. if (x2 === void 0) { x2 = 1; }
  41928. if (y2 === void 0) { y2 = 1; }
  41929. var _this = _super.call(this) || this;
  41930. _this.x1 = x1;
  41931. _this.y1 = y1;
  41932. _this.x2 = x2;
  41933. _this.y2 = y2;
  41934. return _this;
  41935. }
  41936. BezierCurveEase.prototype.easeInCore = function (gradient) {
  41937. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  41938. };
  41939. return BezierCurveEase;
  41940. }(EasingFunction));
  41941. BABYLON.BezierCurveEase = BezierCurveEase;
  41942. })(BABYLON || (BABYLON = {}));
  41943. //# sourceMappingURL=babylon.easing.js.map
  41944. var BABYLON;
  41945. (function (BABYLON) {
  41946. var Condition = /** @class */ (function () {
  41947. function Condition(actionManager) {
  41948. this._actionManager = actionManager;
  41949. }
  41950. Condition.prototype.isValid = function () {
  41951. return true;
  41952. };
  41953. Condition.prototype._getProperty = function (propertyPath) {
  41954. return this._actionManager._getProperty(propertyPath);
  41955. };
  41956. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  41957. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41958. };
  41959. Condition.prototype.serialize = function () {
  41960. };
  41961. Condition.prototype._serialize = function (serializedCondition) {
  41962. return {
  41963. type: 2,
  41964. children: [],
  41965. name: serializedCondition.name,
  41966. properties: serializedCondition.properties
  41967. };
  41968. };
  41969. return Condition;
  41970. }());
  41971. BABYLON.Condition = Condition;
  41972. var ValueCondition = /** @class */ (function (_super) {
  41973. __extends(ValueCondition, _super);
  41974. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  41975. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  41976. var _this = _super.call(this, actionManager) || this;
  41977. _this.propertyPath = propertyPath;
  41978. _this.value = value;
  41979. _this.operator = operator;
  41980. _this._target = target;
  41981. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  41982. _this._property = _this._getProperty(_this.propertyPath);
  41983. return _this;
  41984. }
  41985. Object.defineProperty(ValueCondition, "IsEqual", {
  41986. get: function () {
  41987. return ValueCondition._IsEqual;
  41988. },
  41989. enumerable: true,
  41990. configurable: true
  41991. });
  41992. Object.defineProperty(ValueCondition, "IsDifferent", {
  41993. get: function () {
  41994. return ValueCondition._IsDifferent;
  41995. },
  41996. enumerable: true,
  41997. configurable: true
  41998. });
  41999. Object.defineProperty(ValueCondition, "IsGreater", {
  42000. get: function () {
  42001. return ValueCondition._IsGreater;
  42002. },
  42003. enumerable: true,
  42004. configurable: true
  42005. });
  42006. Object.defineProperty(ValueCondition, "IsLesser", {
  42007. get: function () {
  42008. return ValueCondition._IsLesser;
  42009. },
  42010. enumerable: true,
  42011. configurable: true
  42012. });
  42013. // Methods
  42014. ValueCondition.prototype.isValid = function () {
  42015. switch (this.operator) {
  42016. case ValueCondition.IsGreater:
  42017. return this._effectiveTarget[this._property] > this.value;
  42018. case ValueCondition.IsLesser:
  42019. return this._effectiveTarget[this._property] < this.value;
  42020. case ValueCondition.IsEqual:
  42021. case ValueCondition.IsDifferent:
  42022. var check;
  42023. if (this.value.equals) {
  42024. check = this.value.equals(this._effectiveTarget[this._property]);
  42025. }
  42026. else {
  42027. check = this.value === this._effectiveTarget[this._property];
  42028. }
  42029. return this.operator === ValueCondition.IsEqual ? check : !check;
  42030. }
  42031. return false;
  42032. };
  42033. ValueCondition.prototype.serialize = function () {
  42034. return this._serialize({
  42035. name: "ValueCondition",
  42036. properties: [
  42037. BABYLON.Action._GetTargetProperty(this._target),
  42038. { name: "propertyPath", value: this.propertyPath },
  42039. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42040. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  42041. ]
  42042. });
  42043. };
  42044. ValueCondition.GetOperatorName = function (operator) {
  42045. switch (operator) {
  42046. case ValueCondition._IsEqual: return "IsEqual";
  42047. case ValueCondition._IsDifferent: return "IsDifferent";
  42048. case ValueCondition._IsGreater: return "IsGreater";
  42049. case ValueCondition._IsLesser: return "IsLesser";
  42050. default: return "";
  42051. }
  42052. };
  42053. // Statics
  42054. ValueCondition._IsEqual = 0;
  42055. ValueCondition._IsDifferent = 1;
  42056. ValueCondition._IsGreater = 2;
  42057. ValueCondition._IsLesser = 3;
  42058. return ValueCondition;
  42059. }(Condition));
  42060. BABYLON.ValueCondition = ValueCondition;
  42061. var PredicateCondition = /** @class */ (function (_super) {
  42062. __extends(PredicateCondition, _super);
  42063. function PredicateCondition(actionManager, predicate) {
  42064. var _this = _super.call(this, actionManager) || this;
  42065. _this.predicate = predicate;
  42066. return _this;
  42067. }
  42068. PredicateCondition.prototype.isValid = function () {
  42069. return this.predicate();
  42070. };
  42071. return PredicateCondition;
  42072. }(Condition));
  42073. BABYLON.PredicateCondition = PredicateCondition;
  42074. var StateCondition = /** @class */ (function (_super) {
  42075. __extends(StateCondition, _super);
  42076. function StateCondition(actionManager, target, value) {
  42077. var _this = _super.call(this, actionManager) || this;
  42078. _this.value = value;
  42079. _this._target = target;
  42080. return _this;
  42081. }
  42082. // Methods
  42083. StateCondition.prototype.isValid = function () {
  42084. return this._target.state === this.value;
  42085. };
  42086. StateCondition.prototype.serialize = function () {
  42087. return this._serialize({
  42088. name: "StateCondition",
  42089. properties: [
  42090. BABYLON.Action._GetTargetProperty(this._target),
  42091. { name: "value", value: this.value }
  42092. ]
  42093. });
  42094. };
  42095. return StateCondition;
  42096. }(Condition));
  42097. BABYLON.StateCondition = StateCondition;
  42098. })(BABYLON || (BABYLON = {}));
  42099. //# sourceMappingURL=babylon.condition.js.map
  42100. var BABYLON;
  42101. (function (BABYLON) {
  42102. var Action = /** @class */ (function () {
  42103. function Action(triggerOptions, condition) {
  42104. this.triggerOptions = triggerOptions;
  42105. this.onBeforeExecuteObservable = new BABYLON.Observable();
  42106. if (triggerOptions.parameter) {
  42107. this.trigger = triggerOptions.trigger;
  42108. this._triggerParameter = triggerOptions.parameter;
  42109. }
  42110. else {
  42111. this.trigger = triggerOptions;
  42112. }
  42113. this._nextActiveAction = this;
  42114. this._condition = condition;
  42115. }
  42116. // Methods
  42117. Action.prototype._prepare = function () {
  42118. };
  42119. Action.prototype.getTriggerParameter = function () {
  42120. return this._triggerParameter;
  42121. };
  42122. Action.prototype._executeCurrent = function (evt) {
  42123. if (this._nextActiveAction._condition) {
  42124. var condition = this._nextActiveAction._condition;
  42125. var currentRenderId = this._actionManager.getScene().getRenderId();
  42126. // We cache the current evaluation for the current frame
  42127. if (condition._evaluationId === currentRenderId) {
  42128. if (!condition._currentResult) {
  42129. return;
  42130. }
  42131. }
  42132. else {
  42133. condition._evaluationId = currentRenderId;
  42134. if (!condition.isValid()) {
  42135. condition._currentResult = false;
  42136. return;
  42137. }
  42138. condition._currentResult = true;
  42139. }
  42140. }
  42141. this.onBeforeExecuteObservable.notifyObservers(this);
  42142. this._nextActiveAction.execute(evt);
  42143. this.skipToNextActiveAction();
  42144. };
  42145. Action.prototype.execute = function (evt) {
  42146. };
  42147. Action.prototype.skipToNextActiveAction = function () {
  42148. if (this._nextActiveAction._child) {
  42149. if (!this._nextActiveAction._child._actionManager) {
  42150. this._nextActiveAction._child._actionManager = this._actionManager;
  42151. }
  42152. this._nextActiveAction = this._nextActiveAction._child;
  42153. }
  42154. else {
  42155. this._nextActiveAction = this;
  42156. }
  42157. };
  42158. Action.prototype.then = function (action) {
  42159. this._child = action;
  42160. action._actionManager = this._actionManager;
  42161. action._prepare();
  42162. return action;
  42163. };
  42164. Action.prototype._getProperty = function (propertyPath) {
  42165. return this._actionManager._getProperty(propertyPath);
  42166. };
  42167. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  42168. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42169. };
  42170. Action.prototype.serialize = function (parent) {
  42171. };
  42172. // Called by BABYLON.Action objects in serialize(...). Internal use
  42173. Action.prototype._serialize = function (serializedAction, parent) {
  42174. var serializationObject = {
  42175. type: 1,
  42176. children: [],
  42177. name: serializedAction.name,
  42178. properties: serializedAction.properties || []
  42179. };
  42180. // Serialize child
  42181. if (this._child) {
  42182. this._child.serialize(serializationObject);
  42183. }
  42184. // Check if "this" has a condition
  42185. if (this._condition) {
  42186. var serializedCondition = this._condition.serialize();
  42187. serializedCondition.children.push(serializationObject);
  42188. if (parent) {
  42189. parent.children.push(serializedCondition);
  42190. }
  42191. return serializedCondition;
  42192. }
  42193. if (parent) {
  42194. parent.children.push(serializationObject);
  42195. }
  42196. return serializationObject;
  42197. };
  42198. Action._SerializeValueAsString = function (value) {
  42199. if (typeof value === "number") {
  42200. return value.toString();
  42201. }
  42202. if (typeof value === "boolean") {
  42203. return value ? "true" : "false";
  42204. }
  42205. if (value instanceof BABYLON.Vector2) {
  42206. return value.x + ", " + value.y;
  42207. }
  42208. if (value instanceof BABYLON.Vector3) {
  42209. return value.x + ", " + value.y + ", " + value.z;
  42210. }
  42211. if (value instanceof BABYLON.Color3) {
  42212. return value.r + ", " + value.g + ", " + value.b;
  42213. }
  42214. if (value instanceof BABYLON.Color4) {
  42215. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  42216. }
  42217. return value; // string
  42218. };
  42219. Action._GetTargetProperty = function (target) {
  42220. return {
  42221. name: "target",
  42222. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  42223. : target instanceof BABYLON.Light ? "LightProperties"
  42224. : target instanceof BABYLON.Camera ? "CameraProperties"
  42225. : "SceneProperties",
  42226. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  42227. };
  42228. };
  42229. return Action;
  42230. }());
  42231. BABYLON.Action = Action;
  42232. })(BABYLON || (BABYLON = {}));
  42233. //# sourceMappingURL=babylon.action.js.map
  42234. var BABYLON;
  42235. (function (BABYLON) {
  42236. /**
  42237. * ActionEvent is the event beint sent when an action is triggered.
  42238. */
  42239. var ActionEvent = /** @class */ (function () {
  42240. /**
  42241. * @param source The mesh or sprite that triggered the action.
  42242. * @param pointerX The X mouse cursor position at the time of the event
  42243. * @param pointerY The Y mouse cursor position at the time of the event
  42244. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  42245. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  42246. */
  42247. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  42248. this.source = source;
  42249. this.pointerX = pointerX;
  42250. this.pointerY = pointerY;
  42251. this.meshUnderPointer = meshUnderPointer;
  42252. this.sourceEvent = sourceEvent;
  42253. this.additionalData = additionalData;
  42254. }
  42255. /**
  42256. * Helper function to auto-create an ActionEvent from a source mesh.
  42257. * @param source The source mesh that triggered the event
  42258. * @param evt {Event} The original (browser) event
  42259. */
  42260. ActionEvent.CreateNew = function (source, evt, additionalData) {
  42261. var scene = source.getScene();
  42262. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42263. };
  42264. /**
  42265. * Helper function to auto-create an ActionEvent from a source mesh.
  42266. * @param source The source sprite that triggered the event
  42267. * @param scene Scene associated with the sprite
  42268. * @param evt {Event} The original (browser) event
  42269. */
  42270. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  42271. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42272. };
  42273. /**
  42274. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  42275. * @param scene the scene where the event occurred
  42276. * @param evt {Event} The original (browser) event
  42277. */
  42278. ActionEvent.CreateNewFromScene = function (scene, evt) {
  42279. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  42280. };
  42281. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  42282. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  42283. };
  42284. return ActionEvent;
  42285. }());
  42286. BABYLON.ActionEvent = ActionEvent;
  42287. /**
  42288. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  42289. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  42290. */
  42291. var ActionManager = /** @class */ (function () {
  42292. function ActionManager(scene) {
  42293. // Members
  42294. this.actions = new Array();
  42295. this.hoverCursor = '';
  42296. this._scene = scene;
  42297. scene._actionManagers.push(this);
  42298. }
  42299. Object.defineProperty(ActionManager, "NothingTrigger", {
  42300. get: function () {
  42301. return ActionManager._NothingTrigger;
  42302. },
  42303. enumerable: true,
  42304. configurable: true
  42305. });
  42306. Object.defineProperty(ActionManager, "OnPickTrigger", {
  42307. get: function () {
  42308. return ActionManager._OnPickTrigger;
  42309. },
  42310. enumerable: true,
  42311. configurable: true
  42312. });
  42313. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  42314. get: function () {
  42315. return ActionManager._OnLeftPickTrigger;
  42316. },
  42317. enumerable: true,
  42318. configurable: true
  42319. });
  42320. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  42321. get: function () {
  42322. return ActionManager._OnRightPickTrigger;
  42323. },
  42324. enumerable: true,
  42325. configurable: true
  42326. });
  42327. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  42328. get: function () {
  42329. return ActionManager._OnCenterPickTrigger;
  42330. },
  42331. enumerable: true,
  42332. configurable: true
  42333. });
  42334. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  42335. get: function () {
  42336. return ActionManager._OnPickDownTrigger;
  42337. },
  42338. enumerable: true,
  42339. configurable: true
  42340. });
  42341. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  42342. get: function () {
  42343. return ActionManager._OnDoublePickTrigger;
  42344. },
  42345. enumerable: true,
  42346. configurable: true
  42347. });
  42348. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  42349. get: function () {
  42350. return ActionManager._OnPickUpTrigger;
  42351. },
  42352. enumerable: true,
  42353. configurable: true
  42354. });
  42355. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  42356. /// This trigger will only be raised if you also declared a OnPickDown
  42357. get: function () {
  42358. return ActionManager._OnPickOutTrigger;
  42359. },
  42360. enumerable: true,
  42361. configurable: true
  42362. });
  42363. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  42364. get: function () {
  42365. return ActionManager._OnLongPressTrigger;
  42366. },
  42367. enumerable: true,
  42368. configurable: true
  42369. });
  42370. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  42371. get: function () {
  42372. return ActionManager._OnPointerOverTrigger;
  42373. },
  42374. enumerable: true,
  42375. configurable: true
  42376. });
  42377. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  42378. get: function () {
  42379. return ActionManager._OnPointerOutTrigger;
  42380. },
  42381. enumerable: true,
  42382. configurable: true
  42383. });
  42384. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  42385. get: function () {
  42386. return ActionManager._OnEveryFrameTrigger;
  42387. },
  42388. enumerable: true,
  42389. configurable: true
  42390. });
  42391. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  42392. get: function () {
  42393. return ActionManager._OnIntersectionEnterTrigger;
  42394. },
  42395. enumerable: true,
  42396. configurable: true
  42397. });
  42398. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  42399. get: function () {
  42400. return ActionManager._OnIntersectionExitTrigger;
  42401. },
  42402. enumerable: true,
  42403. configurable: true
  42404. });
  42405. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  42406. get: function () {
  42407. return ActionManager._OnKeyDownTrigger;
  42408. },
  42409. enumerable: true,
  42410. configurable: true
  42411. });
  42412. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  42413. get: function () {
  42414. return ActionManager._OnKeyUpTrigger;
  42415. },
  42416. enumerable: true,
  42417. configurable: true
  42418. });
  42419. // Methods
  42420. ActionManager.prototype.dispose = function () {
  42421. var index = this._scene._actionManagers.indexOf(this);
  42422. for (var i = 0; i < this.actions.length; i++) {
  42423. var action = this.actions[i];
  42424. ActionManager.Triggers[action.trigger]--;
  42425. if (ActionManager.Triggers[action.trigger] === 0) {
  42426. delete ActionManager.Triggers[action.trigger];
  42427. }
  42428. }
  42429. if (index > -1) {
  42430. this._scene._actionManagers.splice(index, 1);
  42431. }
  42432. };
  42433. ActionManager.prototype.getScene = function () {
  42434. return this._scene;
  42435. };
  42436. /**
  42437. * Does this action manager handles actions of any of the given triggers
  42438. * @param {number[]} triggers - the triggers to be tested
  42439. * @return {boolean} whether one (or more) of the triggers is handeled
  42440. */
  42441. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  42442. for (var index = 0; index < this.actions.length; index++) {
  42443. var action = this.actions[index];
  42444. if (triggers.indexOf(action.trigger) > -1) {
  42445. return true;
  42446. }
  42447. }
  42448. return false;
  42449. };
  42450. /**
  42451. * Does this action manager handles actions of a given trigger
  42452. * @param {number} trigger - the trigger to be tested
  42453. * @return {boolean} whether the trigger is handeled
  42454. */
  42455. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  42456. for (var index = 0; index < this.actions.length; index++) {
  42457. var action = this.actions[index];
  42458. if (action.trigger === trigger) {
  42459. return true;
  42460. }
  42461. }
  42462. return false;
  42463. };
  42464. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  42465. /**
  42466. * Does this action manager has pointer triggers
  42467. * @return {boolean} whether or not it has pointer triggers
  42468. */
  42469. get: function () {
  42470. for (var index = 0; index < this.actions.length; index++) {
  42471. var action = this.actions[index];
  42472. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  42473. return true;
  42474. }
  42475. }
  42476. return false;
  42477. },
  42478. enumerable: true,
  42479. configurable: true
  42480. });
  42481. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  42482. /**
  42483. * Does this action manager has pick triggers
  42484. * @return {boolean} whether or not it has pick triggers
  42485. */
  42486. get: function () {
  42487. for (var index = 0; index < this.actions.length; index++) {
  42488. var action = this.actions[index];
  42489. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  42490. return true;
  42491. }
  42492. }
  42493. return false;
  42494. },
  42495. enumerable: true,
  42496. configurable: true
  42497. });
  42498. Object.defineProperty(ActionManager, "HasTriggers", {
  42499. /**
  42500. * Does exist one action manager with at least one trigger
  42501. * @return {boolean} whether or not it exists one action manager with one trigger
  42502. **/
  42503. get: function () {
  42504. for (var t in ActionManager.Triggers) {
  42505. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42506. return true;
  42507. }
  42508. }
  42509. return false;
  42510. },
  42511. enumerable: true,
  42512. configurable: true
  42513. });
  42514. Object.defineProperty(ActionManager, "HasPickTriggers", {
  42515. /**
  42516. * Does exist one action manager with at least one pick trigger
  42517. * @return {boolean} whether or not it exists one action manager with one pick trigger
  42518. **/
  42519. get: function () {
  42520. for (var t in ActionManager.Triggers) {
  42521. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42522. var t_int = parseInt(t);
  42523. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  42524. return true;
  42525. }
  42526. }
  42527. }
  42528. return false;
  42529. },
  42530. enumerable: true,
  42531. configurable: true
  42532. });
  42533. /**
  42534. * Does exist one action manager that handles actions of a given trigger
  42535. * @param {number} trigger - the trigger to be tested
  42536. * @return {boolean} whether the trigger is handeled by at least one action manager
  42537. **/
  42538. ActionManager.HasSpecificTrigger = function (trigger) {
  42539. for (var t in ActionManager.Triggers) {
  42540. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42541. var t_int = parseInt(t);
  42542. if (t_int === trigger) {
  42543. return true;
  42544. }
  42545. }
  42546. }
  42547. return false;
  42548. };
  42549. /**
  42550. * Registers an action to this action manager
  42551. * @param {BABYLON.Action} action - the action to be registered
  42552. * @return {BABYLON.Action} the action amended (prepared) after registration
  42553. */
  42554. ActionManager.prototype.registerAction = function (action) {
  42555. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  42556. if (this.getScene().actionManager !== this) {
  42557. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  42558. return null;
  42559. }
  42560. }
  42561. this.actions.push(action);
  42562. if (ActionManager.Triggers[action.trigger]) {
  42563. ActionManager.Triggers[action.trigger]++;
  42564. }
  42565. else {
  42566. ActionManager.Triggers[action.trigger] = 1;
  42567. }
  42568. action._actionManager = this;
  42569. action._prepare();
  42570. return action;
  42571. };
  42572. /**
  42573. * Process a specific trigger
  42574. * @param {number} trigger - the trigger to process
  42575. * @param evt {BABYLON.ActionEvent} the event details to be processed
  42576. */
  42577. ActionManager.prototype.processTrigger = function (trigger, evt) {
  42578. for (var index = 0; index < this.actions.length; index++) {
  42579. var action = this.actions[index];
  42580. if (action.trigger === trigger) {
  42581. if (evt) {
  42582. if (trigger === ActionManager.OnKeyUpTrigger
  42583. || trigger === ActionManager.OnKeyDownTrigger) {
  42584. var parameter = action.getTriggerParameter();
  42585. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  42586. if (!parameter.toLowerCase) {
  42587. continue;
  42588. }
  42589. var lowerCase = parameter.toLowerCase();
  42590. if (lowerCase !== evt.sourceEvent.key) {
  42591. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  42592. var actualkey = String.fromCharCode(unicode).toLowerCase();
  42593. if (actualkey !== lowerCase) {
  42594. continue;
  42595. }
  42596. }
  42597. }
  42598. }
  42599. }
  42600. action._executeCurrent(evt);
  42601. }
  42602. }
  42603. };
  42604. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  42605. var properties = propertyPath.split(".");
  42606. for (var index = 0; index < properties.length - 1; index++) {
  42607. target = target[properties[index]];
  42608. }
  42609. return target;
  42610. };
  42611. ActionManager.prototype._getProperty = function (propertyPath) {
  42612. var properties = propertyPath.split(".");
  42613. return properties[properties.length - 1];
  42614. };
  42615. ActionManager.prototype.serialize = function (name) {
  42616. var root = {
  42617. children: new Array(),
  42618. name: name,
  42619. type: 3,
  42620. properties: new Array() // Empty for root but required
  42621. };
  42622. for (var i = 0; i < this.actions.length; i++) {
  42623. var triggerObject = {
  42624. type: 0,
  42625. children: new Array(),
  42626. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  42627. properties: new Array()
  42628. };
  42629. var triggerOptions = this.actions[i].triggerOptions;
  42630. if (triggerOptions && typeof triggerOptions !== "number") {
  42631. if (triggerOptions.parameter instanceof BABYLON.Node) {
  42632. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  42633. }
  42634. else {
  42635. var parameter = {};
  42636. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  42637. if (triggerOptions.parameter.mesh) {
  42638. parameter._meshId = triggerOptions.parameter.mesh.id;
  42639. }
  42640. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  42641. }
  42642. }
  42643. // Serialize child action, recursively
  42644. this.actions[i].serialize(triggerObject);
  42645. // Add serialized trigger
  42646. root.children.push(triggerObject);
  42647. }
  42648. return root;
  42649. };
  42650. ActionManager.Parse = function (parsedActions, object, scene) {
  42651. var actionManager = new BABYLON.ActionManager(scene);
  42652. if (object === null)
  42653. scene.actionManager = actionManager;
  42654. else
  42655. object.actionManager = actionManager;
  42656. // instanciate a new object
  42657. var instanciate = function (name, params) {
  42658. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  42659. newInstance.constructor.apply(newInstance, params);
  42660. return newInstance;
  42661. };
  42662. var parseParameter = function (name, value, target, propertyPath) {
  42663. if (propertyPath === null) {
  42664. // String, boolean or float
  42665. var floatValue = parseFloat(value);
  42666. if (value === "true" || value === "false")
  42667. return value === "true";
  42668. else
  42669. return isNaN(floatValue) ? value : floatValue;
  42670. }
  42671. var effectiveTarget = propertyPath.split(".");
  42672. var values = value.split(",");
  42673. // Get effective Target
  42674. for (var i = 0; i < effectiveTarget.length; i++) {
  42675. target = target[effectiveTarget[i]];
  42676. }
  42677. // Return appropriate value with its type
  42678. if (typeof (target) === "boolean")
  42679. return values[0] === "true";
  42680. if (typeof (target) === "string")
  42681. return values[0];
  42682. // Parameters with multiple values such as Vector3 etc.
  42683. var split = new Array();
  42684. for (var i = 0; i < values.length; i++)
  42685. split.push(parseFloat(values[i]));
  42686. if (target instanceof BABYLON.Vector3)
  42687. return BABYLON.Vector3.FromArray(split);
  42688. if (target instanceof BABYLON.Vector4)
  42689. return BABYLON.Vector4.FromArray(split);
  42690. if (target instanceof BABYLON.Color3)
  42691. return BABYLON.Color3.FromArray(split);
  42692. if (target instanceof BABYLON.Color4)
  42693. return BABYLON.Color4.FromArray(split);
  42694. return parseFloat(values[0]);
  42695. };
  42696. // traverse graph per trigger
  42697. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  42698. if (combineArray === void 0) { combineArray = null; }
  42699. if (parsedAction.detached)
  42700. return;
  42701. var parameters = new Array();
  42702. var target = null;
  42703. var propertyPath = null;
  42704. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  42705. // Parameters
  42706. if (parsedAction.type === 2)
  42707. parameters.push(actionManager);
  42708. else
  42709. parameters.push(trigger);
  42710. if (combine) {
  42711. var actions = new Array();
  42712. for (var j = 0; j < parsedAction.combine.length; j++) {
  42713. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  42714. }
  42715. parameters.push(actions);
  42716. }
  42717. else {
  42718. for (var i = 0; i < parsedAction.properties.length; i++) {
  42719. var value = parsedAction.properties[i].value;
  42720. var name = parsedAction.properties[i].name;
  42721. var targetType = parsedAction.properties[i].targetType;
  42722. if (name === "target")
  42723. if (targetType !== null && targetType === "SceneProperties")
  42724. value = target = scene;
  42725. else
  42726. value = target = scene.getNodeByName(value);
  42727. else if (name === "parent")
  42728. value = scene.getNodeByName(value);
  42729. else if (name === "sound")
  42730. value = scene.getSoundByName(value);
  42731. else if (name !== "propertyPath") {
  42732. if (parsedAction.type === 2 && name === "operator")
  42733. value = BABYLON.ValueCondition[value];
  42734. else
  42735. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  42736. }
  42737. else {
  42738. propertyPath = value;
  42739. }
  42740. parameters.push(value);
  42741. }
  42742. }
  42743. if (combineArray === null) {
  42744. parameters.push(condition);
  42745. }
  42746. else {
  42747. parameters.push(null);
  42748. }
  42749. // If interpolate value action
  42750. if (parsedAction.name === "InterpolateValueAction") {
  42751. var param = parameters[parameters.length - 2];
  42752. parameters[parameters.length - 1] = param;
  42753. parameters[parameters.length - 2] = condition;
  42754. }
  42755. // Action or condition(s) and not CombineAction
  42756. var newAction = instanciate(parsedAction.name, parameters);
  42757. if (newAction instanceof BABYLON.Condition && condition !== null) {
  42758. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  42759. if (action)
  42760. action.then(nothing);
  42761. else
  42762. actionManager.registerAction(nothing);
  42763. action = nothing;
  42764. }
  42765. if (combineArray === null) {
  42766. if (newAction instanceof BABYLON.Condition) {
  42767. condition = newAction;
  42768. newAction = action;
  42769. }
  42770. else {
  42771. condition = null;
  42772. if (action)
  42773. action.then(newAction);
  42774. else
  42775. actionManager.registerAction(newAction);
  42776. }
  42777. }
  42778. else {
  42779. combineArray.push(newAction);
  42780. }
  42781. for (var i = 0; i < parsedAction.children.length; i++)
  42782. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  42783. };
  42784. // triggers
  42785. for (var i = 0; i < parsedActions.children.length; i++) {
  42786. var triggerParams;
  42787. var trigger = parsedActions.children[i];
  42788. if (trigger.properties.length > 0) {
  42789. var param = trigger.properties[0].value;
  42790. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  42791. if (value._meshId) {
  42792. value.mesh = scene.getMeshByID(value._meshId);
  42793. }
  42794. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  42795. }
  42796. else
  42797. triggerParams = ActionManager[trigger.name];
  42798. for (var j = 0; j < trigger.children.length; j++) {
  42799. if (!trigger.detached)
  42800. traverse(trigger.children[j], triggerParams, null, null);
  42801. }
  42802. }
  42803. };
  42804. ActionManager.GetTriggerName = function (trigger) {
  42805. switch (trigger) {
  42806. case 0: return "NothingTrigger";
  42807. case 1: return "OnPickTrigger";
  42808. case 2: return "OnLeftPickTrigger";
  42809. case 3: return "OnRightPickTrigger";
  42810. case 4: return "OnCenterPickTrigger";
  42811. case 5: return "OnPickDownTrigger";
  42812. case 6: return "OnPickUpTrigger";
  42813. case 7: return "OnLongPressTrigger";
  42814. case 8: return "OnPointerOverTrigger";
  42815. case 9: return "OnPointerOutTrigger";
  42816. case 10: return "OnEveryFrameTrigger";
  42817. case 11: return "OnIntersectionEnterTrigger";
  42818. case 12: return "OnIntersectionExitTrigger";
  42819. case 13: return "OnKeyDownTrigger";
  42820. case 14: return "OnKeyUpTrigger";
  42821. case 15: return "OnPickOutTrigger";
  42822. default: return "";
  42823. }
  42824. };
  42825. // Statics
  42826. ActionManager._NothingTrigger = 0;
  42827. ActionManager._OnPickTrigger = 1;
  42828. ActionManager._OnLeftPickTrigger = 2;
  42829. ActionManager._OnRightPickTrigger = 3;
  42830. ActionManager._OnCenterPickTrigger = 4;
  42831. ActionManager._OnPickDownTrigger = 5;
  42832. ActionManager._OnDoublePickTrigger = 6;
  42833. ActionManager._OnPickUpTrigger = 7;
  42834. ActionManager._OnLongPressTrigger = 8;
  42835. ActionManager._OnPointerOverTrigger = 9;
  42836. ActionManager._OnPointerOutTrigger = 10;
  42837. ActionManager._OnEveryFrameTrigger = 11;
  42838. ActionManager._OnIntersectionEnterTrigger = 12;
  42839. ActionManager._OnIntersectionExitTrigger = 13;
  42840. ActionManager._OnKeyDownTrigger = 14;
  42841. ActionManager._OnKeyUpTrigger = 15;
  42842. ActionManager._OnPickOutTrigger = 16;
  42843. ActionManager.Triggers = {};
  42844. return ActionManager;
  42845. }());
  42846. BABYLON.ActionManager = ActionManager;
  42847. })(BABYLON || (BABYLON = {}));
  42848. //# sourceMappingURL=babylon.actionManager.js.map
  42849. var BABYLON;
  42850. (function (BABYLON) {
  42851. var InterpolateValueAction = /** @class */ (function (_super) {
  42852. __extends(InterpolateValueAction, _super);
  42853. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  42854. if (duration === void 0) { duration = 1000; }
  42855. var _this = _super.call(this, triggerOptions, condition) || this;
  42856. _this.propertyPath = propertyPath;
  42857. _this.value = value;
  42858. _this.duration = duration;
  42859. _this.stopOtherAnimations = stopOtherAnimations;
  42860. _this.onInterpolationDone = onInterpolationDone;
  42861. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  42862. _this._target = _this._effectiveTarget = target;
  42863. return _this;
  42864. }
  42865. InterpolateValueAction.prototype._prepare = function () {
  42866. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42867. this._property = this._getProperty(this.propertyPath);
  42868. };
  42869. InterpolateValueAction.prototype.execute = function () {
  42870. var _this = this;
  42871. var scene = this._actionManager.getScene();
  42872. var keys = [
  42873. {
  42874. frame: 0,
  42875. value: this._effectiveTarget[this._property]
  42876. }, {
  42877. frame: 100,
  42878. value: this.value
  42879. }
  42880. ];
  42881. var dataType;
  42882. if (typeof this.value === "number") {
  42883. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  42884. }
  42885. else if (this.value instanceof BABYLON.Color3) {
  42886. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  42887. }
  42888. else if (this.value instanceof BABYLON.Vector3) {
  42889. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  42890. }
  42891. else if (this.value instanceof BABYLON.Matrix) {
  42892. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  42893. }
  42894. else if (this.value instanceof BABYLON.Quaternion) {
  42895. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  42896. }
  42897. else {
  42898. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  42899. return;
  42900. }
  42901. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  42902. animation.setKeys(keys);
  42903. if (this.stopOtherAnimations) {
  42904. scene.stopAnimation(this._effectiveTarget);
  42905. }
  42906. var wrapper = function () {
  42907. _this.onInterpolationDoneObservable.notifyObservers(_this);
  42908. if (_this.onInterpolationDone) {
  42909. _this.onInterpolationDone();
  42910. }
  42911. };
  42912. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  42913. };
  42914. InterpolateValueAction.prototype.serialize = function (parent) {
  42915. return _super.prototype._serialize.call(this, {
  42916. name: "InterpolateValueAction",
  42917. properties: [
  42918. BABYLON.Action._GetTargetProperty(this._target),
  42919. { name: "propertyPath", value: this.propertyPath },
  42920. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42921. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  42922. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  42923. ]
  42924. }, parent);
  42925. };
  42926. return InterpolateValueAction;
  42927. }(BABYLON.Action));
  42928. BABYLON.InterpolateValueAction = InterpolateValueAction;
  42929. })(BABYLON || (BABYLON = {}));
  42930. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  42931. var BABYLON;
  42932. (function (BABYLON) {
  42933. var SwitchBooleanAction = /** @class */ (function (_super) {
  42934. __extends(SwitchBooleanAction, _super);
  42935. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  42936. var _this = _super.call(this, triggerOptions, condition) || this;
  42937. _this.propertyPath = propertyPath;
  42938. _this._target = _this._effectiveTarget = target;
  42939. return _this;
  42940. }
  42941. SwitchBooleanAction.prototype._prepare = function () {
  42942. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42943. this._property = this._getProperty(this.propertyPath);
  42944. };
  42945. SwitchBooleanAction.prototype.execute = function () {
  42946. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  42947. };
  42948. SwitchBooleanAction.prototype.serialize = function (parent) {
  42949. return _super.prototype._serialize.call(this, {
  42950. name: "SwitchBooleanAction",
  42951. properties: [
  42952. BABYLON.Action._GetTargetProperty(this._target),
  42953. { name: "propertyPath", value: this.propertyPath }
  42954. ]
  42955. }, parent);
  42956. };
  42957. return SwitchBooleanAction;
  42958. }(BABYLON.Action));
  42959. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  42960. var SetStateAction = /** @class */ (function (_super) {
  42961. __extends(SetStateAction, _super);
  42962. function SetStateAction(triggerOptions, target, value, condition) {
  42963. var _this = _super.call(this, triggerOptions, condition) || this;
  42964. _this.value = value;
  42965. _this._target = target;
  42966. return _this;
  42967. }
  42968. SetStateAction.prototype.execute = function () {
  42969. this._target.state = this.value;
  42970. };
  42971. SetStateAction.prototype.serialize = function (parent) {
  42972. return _super.prototype._serialize.call(this, {
  42973. name: "SetStateAction",
  42974. properties: [
  42975. BABYLON.Action._GetTargetProperty(this._target),
  42976. { name: "value", value: this.value }
  42977. ]
  42978. }, parent);
  42979. };
  42980. return SetStateAction;
  42981. }(BABYLON.Action));
  42982. BABYLON.SetStateAction = SetStateAction;
  42983. var SetValueAction = /** @class */ (function (_super) {
  42984. __extends(SetValueAction, _super);
  42985. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  42986. var _this = _super.call(this, triggerOptions, condition) || this;
  42987. _this.propertyPath = propertyPath;
  42988. _this.value = value;
  42989. _this._target = _this._effectiveTarget = target;
  42990. return _this;
  42991. }
  42992. SetValueAction.prototype._prepare = function () {
  42993. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42994. this._property = this._getProperty(this.propertyPath);
  42995. };
  42996. SetValueAction.prototype.execute = function () {
  42997. this._effectiveTarget[this._property] = this.value;
  42998. if (this._target.markAsDirty) {
  42999. this._target.markAsDirty(this._property);
  43000. }
  43001. };
  43002. SetValueAction.prototype.serialize = function (parent) {
  43003. return _super.prototype._serialize.call(this, {
  43004. name: "SetValueAction",
  43005. properties: [
  43006. BABYLON.Action._GetTargetProperty(this._target),
  43007. { name: "propertyPath", value: this.propertyPath },
  43008. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43009. ]
  43010. }, parent);
  43011. };
  43012. return SetValueAction;
  43013. }(BABYLON.Action));
  43014. BABYLON.SetValueAction = SetValueAction;
  43015. var IncrementValueAction = /** @class */ (function (_super) {
  43016. __extends(IncrementValueAction, _super);
  43017. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  43018. var _this = _super.call(this, triggerOptions, condition) || this;
  43019. _this.propertyPath = propertyPath;
  43020. _this.value = value;
  43021. _this._target = _this._effectiveTarget = target;
  43022. return _this;
  43023. }
  43024. IncrementValueAction.prototype._prepare = function () {
  43025. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43026. this._property = this._getProperty(this.propertyPath);
  43027. if (typeof this._effectiveTarget[this._property] !== "number") {
  43028. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  43029. }
  43030. };
  43031. IncrementValueAction.prototype.execute = function () {
  43032. this._effectiveTarget[this._property] += this.value;
  43033. if (this._target.markAsDirty) {
  43034. this._target.markAsDirty(this._property);
  43035. }
  43036. };
  43037. IncrementValueAction.prototype.serialize = function (parent) {
  43038. return _super.prototype._serialize.call(this, {
  43039. name: "IncrementValueAction",
  43040. properties: [
  43041. BABYLON.Action._GetTargetProperty(this._target),
  43042. { name: "propertyPath", value: this.propertyPath },
  43043. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43044. ]
  43045. }, parent);
  43046. };
  43047. return IncrementValueAction;
  43048. }(BABYLON.Action));
  43049. BABYLON.IncrementValueAction = IncrementValueAction;
  43050. var PlayAnimationAction = /** @class */ (function (_super) {
  43051. __extends(PlayAnimationAction, _super);
  43052. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  43053. var _this = _super.call(this, triggerOptions, condition) || this;
  43054. _this.from = from;
  43055. _this.to = to;
  43056. _this.loop = loop;
  43057. _this._target = target;
  43058. return _this;
  43059. }
  43060. PlayAnimationAction.prototype._prepare = function () {
  43061. };
  43062. PlayAnimationAction.prototype.execute = function () {
  43063. var scene = this._actionManager.getScene();
  43064. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  43065. };
  43066. PlayAnimationAction.prototype.serialize = function (parent) {
  43067. return _super.prototype._serialize.call(this, {
  43068. name: "PlayAnimationAction",
  43069. properties: [
  43070. BABYLON.Action._GetTargetProperty(this._target),
  43071. { name: "from", value: String(this.from) },
  43072. { name: "to", value: String(this.to) },
  43073. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  43074. ]
  43075. }, parent);
  43076. };
  43077. return PlayAnimationAction;
  43078. }(BABYLON.Action));
  43079. BABYLON.PlayAnimationAction = PlayAnimationAction;
  43080. var StopAnimationAction = /** @class */ (function (_super) {
  43081. __extends(StopAnimationAction, _super);
  43082. function StopAnimationAction(triggerOptions, target, condition) {
  43083. var _this = _super.call(this, triggerOptions, condition) || this;
  43084. _this._target = target;
  43085. return _this;
  43086. }
  43087. StopAnimationAction.prototype._prepare = function () {
  43088. };
  43089. StopAnimationAction.prototype.execute = function () {
  43090. var scene = this._actionManager.getScene();
  43091. scene.stopAnimation(this._target);
  43092. };
  43093. StopAnimationAction.prototype.serialize = function (parent) {
  43094. return _super.prototype._serialize.call(this, {
  43095. name: "StopAnimationAction",
  43096. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  43097. }, parent);
  43098. };
  43099. return StopAnimationAction;
  43100. }(BABYLON.Action));
  43101. BABYLON.StopAnimationAction = StopAnimationAction;
  43102. var DoNothingAction = /** @class */ (function (_super) {
  43103. __extends(DoNothingAction, _super);
  43104. function DoNothingAction(triggerOptions, condition) {
  43105. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  43106. return _super.call(this, triggerOptions, condition) || this;
  43107. }
  43108. DoNothingAction.prototype.execute = function () {
  43109. };
  43110. DoNothingAction.prototype.serialize = function (parent) {
  43111. return _super.prototype._serialize.call(this, {
  43112. name: "DoNothingAction",
  43113. properties: []
  43114. }, parent);
  43115. };
  43116. return DoNothingAction;
  43117. }(BABYLON.Action));
  43118. BABYLON.DoNothingAction = DoNothingAction;
  43119. var CombineAction = /** @class */ (function (_super) {
  43120. __extends(CombineAction, _super);
  43121. function CombineAction(triggerOptions, children, condition) {
  43122. var _this = _super.call(this, triggerOptions, condition) || this;
  43123. _this.children = children;
  43124. return _this;
  43125. }
  43126. CombineAction.prototype._prepare = function () {
  43127. for (var index = 0; index < this.children.length; index++) {
  43128. this.children[index]._actionManager = this._actionManager;
  43129. this.children[index]._prepare();
  43130. }
  43131. };
  43132. CombineAction.prototype.execute = function (evt) {
  43133. for (var index = 0; index < this.children.length; index++) {
  43134. this.children[index].execute(evt);
  43135. }
  43136. };
  43137. CombineAction.prototype.serialize = function (parent) {
  43138. var serializationObject = _super.prototype._serialize.call(this, {
  43139. name: "CombineAction",
  43140. properties: [],
  43141. combine: []
  43142. }, parent);
  43143. for (var i = 0; i < this.children.length; i++) {
  43144. serializationObject.combine.push(this.children[i].serialize(null));
  43145. }
  43146. return serializationObject;
  43147. };
  43148. return CombineAction;
  43149. }(BABYLON.Action));
  43150. BABYLON.CombineAction = CombineAction;
  43151. var ExecuteCodeAction = /** @class */ (function (_super) {
  43152. __extends(ExecuteCodeAction, _super);
  43153. function ExecuteCodeAction(triggerOptions, func, condition) {
  43154. var _this = _super.call(this, triggerOptions, condition) || this;
  43155. _this.func = func;
  43156. return _this;
  43157. }
  43158. ExecuteCodeAction.prototype.execute = function (evt) {
  43159. this.func(evt);
  43160. };
  43161. return ExecuteCodeAction;
  43162. }(BABYLON.Action));
  43163. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  43164. var SetParentAction = /** @class */ (function (_super) {
  43165. __extends(SetParentAction, _super);
  43166. function SetParentAction(triggerOptions, target, parent, condition) {
  43167. var _this = _super.call(this, triggerOptions, condition) || this;
  43168. _this._target = target;
  43169. _this._parent = parent;
  43170. return _this;
  43171. }
  43172. SetParentAction.prototype._prepare = function () {
  43173. };
  43174. SetParentAction.prototype.execute = function () {
  43175. if (this._target.parent === this._parent) {
  43176. return;
  43177. }
  43178. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  43179. invertParentWorldMatrix.invert();
  43180. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  43181. this._target.parent = this._parent;
  43182. };
  43183. SetParentAction.prototype.serialize = function (parent) {
  43184. return _super.prototype._serialize.call(this, {
  43185. name: "SetParentAction",
  43186. properties: [
  43187. BABYLON.Action._GetTargetProperty(this._target),
  43188. BABYLON.Action._GetTargetProperty(this._parent),
  43189. ]
  43190. }, parent);
  43191. };
  43192. return SetParentAction;
  43193. }(BABYLON.Action));
  43194. BABYLON.SetParentAction = SetParentAction;
  43195. var PlaySoundAction = /** @class */ (function (_super) {
  43196. __extends(PlaySoundAction, _super);
  43197. function PlaySoundAction(triggerOptions, sound, condition) {
  43198. var _this = _super.call(this, triggerOptions, condition) || this;
  43199. _this._sound = sound;
  43200. return _this;
  43201. }
  43202. PlaySoundAction.prototype._prepare = function () {
  43203. };
  43204. PlaySoundAction.prototype.execute = function () {
  43205. if (this._sound !== undefined)
  43206. this._sound.play();
  43207. };
  43208. PlaySoundAction.prototype.serialize = function (parent) {
  43209. return _super.prototype._serialize.call(this, {
  43210. name: "PlaySoundAction",
  43211. properties: [{ name: "sound", value: this._sound.name }]
  43212. }, parent);
  43213. };
  43214. return PlaySoundAction;
  43215. }(BABYLON.Action));
  43216. BABYLON.PlaySoundAction = PlaySoundAction;
  43217. var StopSoundAction = /** @class */ (function (_super) {
  43218. __extends(StopSoundAction, _super);
  43219. function StopSoundAction(triggerOptions, sound, condition) {
  43220. var _this = _super.call(this, triggerOptions, condition) || this;
  43221. _this._sound = sound;
  43222. return _this;
  43223. }
  43224. StopSoundAction.prototype._prepare = function () {
  43225. };
  43226. StopSoundAction.prototype.execute = function () {
  43227. if (this._sound !== undefined)
  43228. this._sound.stop();
  43229. };
  43230. StopSoundAction.prototype.serialize = function (parent) {
  43231. return _super.prototype._serialize.call(this, {
  43232. name: "StopSoundAction",
  43233. properties: [{ name: "sound", value: this._sound.name }]
  43234. }, parent);
  43235. };
  43236. return StopSoundAction;
  43237. }(BABYLON.Action));
  43238. BABYLON.StopSoundAction = StopSoundAction;
  43239. })(BABYLON || (BABYLON = {}));
  43240. //# sourceMappingURL=babylon.directActions.js.map
  43241. var BABYLON;
  43242. (function (BABYLON) {
  43243. var SpriteManager = /** @class */ (function () {
  43244. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  43245. if (epsilon === void 0) { epsilon = 0.01; }
  43246. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43247. this.name = name;
  43248. this.sprites = new Array();
  43249. this.renderingGroupId = 0;
  43250. this.layerMask = 0x0FFFFFFF;
  43251. this.fogEnabled = true;
  43252. this.isPickable = false;
  43253. /**
  43254. * An event triggered when the manager is disposed.
  43255. * @type {BABYLON.Observable}
  43256. */
  43257. this.onDisposeObservable = new BABYLON.Observable();
  43258. this._vertexBuffers = {};
  43259. this._capacity = capacity;
  43260. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  43261. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43262. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43263. if (cellSize.width && cellSize.height) {
  43264. this.cellWidth = cellSize.width;
  43265. this.cellHeight = cellSize.height;
  43266. }
  43267. else if (cellSize !== undefined) {
  43268. this.cellWidth = cellSize;
  43269. this.cellHeight = cellSize;
  43270. }
  43271. else {
  43272. return;
  43273. }
  43274. this._epsilon = epsilon;
  43275. this._scene = scene;
  43276. this._scene.spriteManagers.push(this);
  43277. var indices = [];
  43278. var index = 0;
  43279. for (var count = 0; count < capacity; count++) {
  43280. indices.push(index);
  43281. indices.push(index + 1);
  43282. indices.push(index + 2);
  43283. indices.push(index);
  43284. indices.push(index + 2);
  43285. indices.push(index + 3);
  43286. index += 4;
  43287. }
  43288. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  43289. // VBO
  43290. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  43291. this._vertexData = new Float32Array(capacity * 16 * 4);
  43292. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  43293. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  43294. var options = this._buffer.createVertexBuffer("options", 4, 4);
  43295. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  43296. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  43297. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  43298. this._vertexBuffers["options"] = options;
  43299. this._vertexBuffers["cellInfo"] = cellInfo;
  43300. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  43301. // Effects
  43302. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  43303. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  43304. }
  43305. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  43306. set: function (callback) {
  43307. if (this._onDisposeObserver) {
  43308. this.onDisposeObservable.remove(this._onDisposeObserver);
  43309. }
  43310. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  43311. },
  43312. enumerable: true,
  43313. configurable: true
  43314. });
  43315. Object.defineProperty(SpriteManager.prototype, "texture", {
  43316. get: function () {
  43317. return this._spriteTexture;
  43318. },
  43319. set: function (value) {
  43320. this._spriteTexture = value;
  43321. },
  43322. enumerable: true,
  43323. configurable: true
  43324. });
  43325. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  43326. var arrayOffset = index * 16;
  43327. if (offsetX === 0)
  43328. offsetX = this._epsilon;
  43329. else if (offsetX === 1)
  43330. offsetX = 1 - this._epsilon;
  43331. if (offsetY === 0)
  43332. offsetY = this._epsilon;
  43333. else if (offsetY === 1)
  43334. offsetY = 1 - this._epsilon;
  43335. this._vertexData[arrayOffset] = sprite.position.x;
  43336. this._vertexData[arrayOffset + 1] = sprite.position.y;
  43337. this._vertexData[arrayOffset + 2] = sprite.position.z;
  43338. this._vertexData[arrayOffset + 3] = sprite.angle;
  43339. this._vertexData[arrayOffset + 4] = sprite.width;
  43340. this._vertexData[arrayOffset + 5] = sprite.height;
  43341. this._vertexData[arrayOffset + 6] = offsetX;
  43342. this._vertexData[arrayOffset + 7] = offsetY;
  43343. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  43344. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  43345. var offset = (sprite.cellIndex / rowSize) >> 0;
  43346. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  43347. this._vertexData[arrayOffset + 11] = offset;
  43348. // Color
  43349. this._vertexData[arrayOffset + 12] = sprite.color.r;
  43350. this._vertexData[arrayOffset + 13] = sprite.color.g;
  43351. this._vertexData[arrayOffset + 14] = sprite.color.b;
  43352. this._vertexData[arrayOffset + 15] = sprite.color.a;
  43353. };
  43354. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  43355. var count = Math.min(this._capacity, this.sprites.length);
  43356. var min = BABYLON.Vector3.Zero();
  43357. var max = BABYLON.Vector3.Zero();
  43358. var distance = Number.MAX_VALUE;
  43359. var currentSprite = null;
  43360. var cameraSpacePosition = BABYLON.Vector3.Zero();
  43361. var cameraView = camera.getViewMatrix();
  43362. for (var index = 0; index < count; index++) {
  43363. var sprite = this.sprites[index];
  43364. if (!sprite) {
  43365. continue;
  43366. }
  43367. if (predicate) {
  43368. if (!predicate(sprite)) {
  43369. continue;
  43370. }
  43371. }
  43372. else if (!sprite.isPickable) {
  43373. continue;
  43374. }
  43375. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  43376. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  43377. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  43378. if (ray.intersectsBoxMinMax(min, max)) {
  43379. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  43380. if (distance > currentDistance) {
  43381. distance = currentDistance;
  43382. currentSprite = sprite;
  43383. if (fastCheck) {
  43384. break;
  43385. }
  43386. }
  43387. }
  43388. }
  43389. if (currentSprite) {
  43390. var result = new BABYLON.PickingInfo();
  43391. result.hit = true;
  43392. result.pickedSprite = currentSprite;
  43393. result.distance = distance;
  43394. return result;
  43395. }
  43396. return null;
  43397. };
  43398. SpriteManager.prototype.render = function () {
  43399. // Check
  43400. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  43401. return;
  43402. var engine = this._scene.getEngine();
  43403. var baseSize = this._spriteTexture.getBaseSize();
  43404. // Sprites
  43405. var deltaTime = engine.getDeltaTime();
  43406. var max = Math.min(this._capacity, this.sprites.length);
  43407. var rowSize = baseSize.width / this.cellWidth;
  43408. var offset = 0;
  43409. for (var index = 0; index < max; index++) {
  43410. var sprite = this.sprites[index];
  43411. if (!sprite) {
  43412. continue;
  43413. }
  43414. sprite._animate(deltaTime);
  43415. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  43416. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  43417. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  43418. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  43419. }
  43420. this._buffer.update(this._vertexData);
  43421. // Render
  43422. var effect = this._effectBase;
  43423. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  43424. effect = this._effectFog;
  43425. }
  43426. engine.enableEffect(effect);
  43427. var viewMatrix = this._scene.getViewMatrix();
  43428. effect.setTexture("diffuseSampler", this._spriteTexture);
  43429. effect.setMatrix("view", viewMatrix);
  43430. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  43431. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  43432. // Fog
  43433. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  43434. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  43435. effect.setColor3("vFogColor", this._scene.fogColor);
  43436. }
  43437. // VBOs
  43438. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  43439. // Draw order
  43440. engine.setDepthFunctionToLessOrEqual();
  43441. effect.setBool("alphaTest", true);
  43442. engine.setColorWrite(false);
  43443. engine.draw(true, 0, max * 6);
  43444. engine.setColorWrite(true);
  43445. effect.setBool("alphaTest", false);
  43446. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43447. engine.draw(true, 0, max * 6);
  43448. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  43449. };
  43450. SpriteManager.prototype.dispose = function () {
  43451. if (this._buffer) {
  43452. this._buffer.dispose();
  43453. this._buffer = null;
  43454. }
  43455. if (this._indexBuffer) {
  43456. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  43457. this._indexBuffer = null;
  43458. }
  43459. if (this._spriteTexture) {
  43460. this._spriteTexture.dispose();
  43461. this._spriteTexture = null;
  43462. }
  43463. // Remove from scene
  43464. var index = this._scene.spriteManagers.indexOf(this);
  43465. this._scene.spriteManagers.splice(index, 1);
  43466. // Callback
  43467. this.onDisposeObservable.notifyObservers(this);
  43468. this.onDisposeObservable.clear();
  43469. };
  43470. return SpriteManager;
  43471. }());
  43472. BABYLON.SpriteManager = SpriteManager;
  43473. })(BABYLON || (BABYLON = {}));
  43474. //# sourceMappingURL=babylon.spriteManager.js.map
  43475. var BABYLON;
  43476. (function (BABYLON) {
  43477. var Sprite = /** @class */ (function () {
  43478. function Sprite(name, manager) {
  43479. this.name = name;
  43480. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43481. this.width = 1.0;
  43482. this.height = 1.0;
  43483. this.angle = 0;
  43484. this.cellIndex = 0;
  43485. this.invertU = 0;
  43486. this.invertV = 0;
  43487. this.animations = new Array();
  43488. this.isPickable = false;
  43489. this._animationStarted = false;
  43490. this._loopAnimation = false;
  43491. this._fromIndex = 0;
  43492. this._toIndex = 0;
  43493. this._delay = 0;
  43494. this._direction = 1;
  43495. this._time = 0;
  43496. this._manager = manager;
  43497. this._manager.sprites.push(this);
  43498. this.position = BABYLON.Vector3.Zero();
  43499. }
  43500. Object.defineProperty(Sprite.prototype, "size", {
  43501. get: function () {
  43502. return this.width;
  43503. },
  43504. set: function (value) {
  43505. this.width = value;
  43506. this.height = value;
  43507. },
  43508. enumerable: true,
  43509. configurable: true
  43510. });
  43511. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  43512. this._fromIndex = from;
  43513. this._toIndex = to;
  43514. this._loopAnimation = loop;
  43515. this._delay = delay;
  43516. this._animationStarted = true;
  43517. this._direction = from < to ? 1 : -1;
  43518. this.cellIndex = from;
  43519. this._time = 0;
  43520. this._onAnimationEnd = onAnimationEnd;
  43521. };
  43522. Sprite.prototype.stopAnimation = function () {
  43523. this._animationStarted = false;
  43524. };
  43525. Sprite.prototype._animate = function (deltaTime) {
  43526. if (!this._animationStarted)
  43527. return;
  43528. this._time += deltaTime;
  43529. if (this._time > this._delay) {
  43530. this._time = this._time % this._delay;
  43531. this.cellIndex += this._direction;
  43532. if (this.cellIndex > this._toIndex) {
  43533. if (this._loopAnimation) {
  43534. this.cellIndex = this._fromIndex;
  43535. }
  43536. else {
  43537. this.cellIndex = this._toIndex;
  43538. this._animationStarted = false;
  43539. if (this._onAnimationEnd) {
  43540. this._onAnimationEnd();
  43541. }
  43542. if (this.disposeWhenFinishedAnimating) {
  43543. this.dispose();
  43544. }
  43545. }
  43546. }
  43547. }
  43548. };
  43549. Sprite.prototype.dispose = function () {
  43550. for (var i = 0; i < this._manager.sprites.length; i++) {
  43551. if (this._manager.sprites[i] == this) {
  43552. this._manager.sprites.splice(i, 1);
  43553. }
  43554. }
  43555. };
  43556. return Sprite;
  43557. }());
  43558. BABYLON.Sprite = Sprite;
  43559. })(BABYLON || (BABYLON = {}));
  43560. //# sourceMappingURL=babylon.sprite.js.map
  43561. var BABYLON;
  43562. (function (BABYLON) {
  43563. var IntersectionInfo = /** @class */ (function () {
  43564. function IntersectionInfo(bu, bv, distance) {
  43565. this.bu = bu;
  43566. this.bv = bv;
  43567. this.distance = distance;
  43568. this.faceId = 0;
  43569. this.subMeshId = 0;
  43570. }
  43571. return IntersectionInfo;
  43572. }());
  43573. BABYLON.IntersectionInfo = IntersectionInfo;
  43574. var PickingInfo = /** @class */ (function () {
  43575. function PickingInfo() {
  43576. this.hit = false;
  43577. this.distance = 0;
  43578. this.pickedPoint = null;
  43579. this.pickedMesh = null;
  43580. this.bu = 0;
  43581. this.bv = 0;
  43582. this.faceId = -1;
  43583. this.subMeshId = 0;
  43584. this.pickedSprite = null;
  43585. }
  43586. // Methods
  43587. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  43588. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  43589. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  43590. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43591. return null;
  43592. }
  43593. var indices = this.pickedMesh.getIndices();
  43594. if (!indices) {
  43595. return null;
  43596. }
  43597. var result;
  43598. if (useVerticesNormals) {
  43599. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43600. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  43601. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  43602. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  43603. normal0 = normal0.scale(this.bu);
  43604. normal1 = normal1.scale(this.bv);
  43605. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  43606. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  43607. }
  43608. else {
  43609. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43610. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  43611. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  43612. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  43613. var p1p2 = vertex1.subtract(vertex2);
  43614. var p3p2 = vertex3.subtract(vertex2);
  43615. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  43616. }
  43617. if (useWorldCoordinates) {
  43618. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  43619. }
  43620. return BABYLON.Vector3.Normalize(result);
  43621. };
  43622. PickingInfo.prototype.getTextureCoordinates = function () {
  43623. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43624. return null;
  43625. }
  43626. var indices = this.pickedMesh.getIndices();
  43627. if (!indices) {
  43628. return null;
  43629. }
  43630. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43631. if (!uvs) {
  43632. return null;
  43633. }
  43634. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  43635. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  43636. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  43637. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  43638. uv1 = uv1.scale(this.bu);
  43639. uv2 = uv2.scale(this.bv);
  43640. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  43641. };
  43642. return PickingInfo;
  43643. }());
  43644. BABYLON.PickingInfo = PickingInfo;
  43645. })(BABYLON || (BABYLON = {}));
  43646. //# sourceMappingURL=babylon.pickingInfo.js.map
  43647. var BABYLON;
  43648. (function (BABYLON) {
  43649. var Ray = /** @class */ (function () {
  43650. function Ray(origin, direction, length) {
  43651. if (length === void 0) { length = Number.MAX_VALUE; }
  43652. this.origin = origin;
  43653. this.direction = direction;
  43654. this.length = length;
  43655. }
  43656. // Methods
  43657. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  43658. var d = 0.0;
  43659. var maxValue = Number.MAX_VALUE;
  43660. var inv;
  43661. var min;
  43662. var max;
  43663. var temp;
  43664. if (Math.abs(this.direction.x) < 0.0000001) {
  43665. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  43666. return false;
  43667. }
  43668. }
  43669. else {
  43670. inv = 1.0 / this.direction.x;
  43671. min = (minimum.x - this.origin.x) * inv;
  43672. max = (maximum.x - this.origin.x) * inv;
  43673. if (max === -Infinity) {
  43674. max = Infinity;
  43675. }
  43676. if (min > max) {
  43677. temp = min;
  43678. min = max;
  43679. max = temp;
  43680. }
  43681. d = Math.max(min, d);
  43682. maxValue = Math.min(max, maxValue);
  43683. if (d > maxValue) {
  43684. return false;
  43685. }
  43686. }
  43687. if (Math.abs(this.direction.y) < 0.0000001) {
  43688. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  43689. return false;
  43690. }
  43691. }
  43692. else {
  43693. inv = 1.0 / this.direction.y;
  43694. min = (minimum.y - this.origin.y) * inv;
  43695. max = (maximum.y - this.origin.y) * inv;
  43696. if (max === -Infinity) {
  43697. max = Infinity;
  43698. }
  43699. if (min > max) {
  43700. temp = min;
  43701. min = max;
  43702. max = temp;
  43703. }
  43704. d = Math.max(min, d);
  43705. maxValue = Math.min(max, maxValue);
  43706. if (d > maxValue) {
  43707. return false;
  43708. }
  43709. }
  43710. if (Math.abs(this.direction.z) < 0.0000001) {
  43711. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  43712. return false;
  43713. }
  43714. }
  43715. else {
  43716. inv = 1.0 / this.direction.z;
  43717. min = (minimum.z - this.origin.z) * inv;
  43718. max = (maximum.z - this.origin.z) * inv;
  43719. if (max === -Infinity) {
  43720. max = Infinity;
  43721. }
  43722. if (min > max) {
  43723. temp = min;
  43724. min = max;
  43725. max = temp;
  43726. }
  43727. d = Math.max(min, d);
  43728. maxValue = Math.min(max, maxValue);
  43729. if (d > maxValue) {
  43730. return false;
  43731. }
  43732. }
  43733. return true;
  43734. };
  43735. Ray.prototype.intersectsBox = function (box) {
  43736. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  43737. };
  43738. Ray.prototype.intersectsSphere = function (sphere) {
  43739. var x = sphere.center.x - this.origin.x;
  43740. var y = sphere.center.y - this.origin.y;
  43741. var z = sphere.center.z - this.origin.z;
  43742. var pyth = (x * x) + (y * y) + (z * z);
  43743. var rr = sphere.radius * sphere.radius;
  43744. if (pyth <= rr) {
  43745. return true;
  43746. }
  43747. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  43748. if (dot < 0.0) {
  43749. return false;
  43750. }
  43751. var temp = pyth - (dot * dot);
  43752. return temp <= rr;
  43753. };
  43754. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  43755. if (!this._edge1) {
  43756. this._edge1 = BABYLON.Vector3.Zero();
  43757. this._edge2 = BABYLON.Vector3.Zero();
  43758. this._pvec = BABYLON.Vector3.Zero();
  43759. this._tvec = BABYLON.Vector3.Zero();
  43760. this._qvec = BABYLON.Vector3.Zero();
  43761. }
  43762. vertex1.subtractToRef(vertex0, this._edge1);
  43763. vertex2.subtractToRef(vertex0, this._edge2);
  43764. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  43765. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  43766. if (det === 0) {
  43767. return null;
  43768. }
  43769. var invdet = 1 / det;
  43770. this.origin.subtractToRef(vertex0, this._tvec);
  43771. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  43772. if (bu < 0 || bu > 1.0) {
  43773. return null;
  43774. }
  43775. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  43776. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  43777. if (bv < 0 || bu + bv > 1.0) {
  43778. return null;
  43779. }
  43780. //check if the distance is longer than the predefined length.
  43781. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  43782. if (distance > this.length) {
  43783. return null;
  43784. }
  43785. return new BABYLON.IntersectionInfo(bu, bv, distance);
  43786. };
  43787. Ray.prototype.intersectsPlane = function (plane) {
  43788. var distance;
  43789. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  43790. if (Math.abs(result1) < 9.99999997475243E-07) {
  43791. return null;
  43792. }
  43793. else {
  43794. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  43795. distance = (-plane.d - result2) / result1;
  43796. if (distance < 0.0) {
  43797. if (distance < -9.99999997475243E-07) {
  43798. return null;
  43799. }
  43800. else {
  43801. return 0;
  43802. }
  43803. }
  43804. return distance;
  43805. }
  43806. };
  43807. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  43808. var tm = BABYLON.Tmp.Matrix[0];
  43809. mesh.getWorldMatrix().invertToRef(tm);
  43810. if (this._tmpRay) {
  43811. Ray.TransformToRef(this, tm, this._tmpRay);
  43812. }
  43813. else {
  43814. this._tmpRay = Ray.Transform(this, tm);
  43815. }
  43816. return mesh.intersects(this._tmpRay, fastCheck);
  43817. };
  43818. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  43819. if (results) {
  43820. results.length = 0;
  43821. }
  43822. else {
  43823. results = [];
  43824. }
  43825. for (var i = 0; i < meshes.length; i++) {
  43826. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  43827. if (pickInfo.hit) {
  43828. results.push(pickInfo);
  43829. }
  43830. }
  43831. results.sort(this._comparePickingInfo);
  43832. return results;
  43833. };
  43834. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  43835. if (pickingInfoA.distance < pickingInfoB.distance) {
  43836. return -1;
  43837. }
  43838. else if (pickingInfoA.distance > pickingInfoB.distance) {
  43839. return 1;
  43840. }
  43841. else {
  43842. return 0;
  43843. }
  43844. };
  43845. /**
  43846. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  43847. * @param sega the first point of the segment to test the intersection against
  43848. * @param segb the second point of the segment to test the intersection against
  43849. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  43850. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  43851. */
  43852. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  43853. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  43854. var u = segb.subtract(sega);
  43855. var v = rsegb.subtract(this.origin);
  43856. var w = sega.subtract(this.origin);
  43857. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  43858. var b = BABYLON.Vector3.Dot(u, v);
  43859. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  43860. var d = BABYLON.Vector3.Dot(u, w);
  43861. var e = BABYLON.Vector3.Dot(v, w);
  43862. var D = a * c - b * b; // always >= 0
  43863. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  43864. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  43865. // compute the line parameters of the two closest points
  43866. if (D < Ray.smallnum) {
  43867. sN = 0.0; // force using point P0 on segment S1
  43868. sD = 1.0; // to prevent possible division by 0.0 later
  43869. tN = e;
  43870. tD = c;
  43871. }
  43872. else {
  43873. sN = (b * e - c * d);
  43874. tN = (a * e - b * d);
  43875. if (sN < 0.0) {
  43876. sN = 0.0;
  43877. tN = e;
  43878. tD = c;
  43879. }
  43880. else if (sN > sD) {
  43881. sN = sD;
  43882. tN = e + b;
  43883. tD = c;
  43884. }
  43885. }
  43886. if (tN < 0.0) {
  43887. tN = 0.0;
  43888. // recompute sc for this edge
  43889. if (-d < 0.0) {
  43890. sN = 0.0;
  43891. }
  43892. else if (-d > a)
  43893. sN = sD;
  43894. else {
  43895. sN = -d;
  43896. sD = a;
  43897. }
  43898. }
  43899. else if (tN > tD) {
  43900. tN = tD;
  43901. // recompute sc for this edge
  43902. if ((-d + b) < 0.0) {
  43903. sN = 0;
  43904. }
  43905. else if ((-d + b) > a) {
  43906. sN = sD;
  43907. }
  43908. else {
  43909. sN = (-d + b);
  43910. sD = a;
  43911. }
  43912. }
  43913. // finally do the division to get sc and tc
  43914. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  43915. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  43916. // get the difference of the two closest points
  43917. var qtc = v.multiplyByFloats(tc, tc, tc);
  43918. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  43919. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  43920. if (isIntersected) {
  43921. return qtc.length();
  43922. }
  43923. return -1;
  43924. };
  43925. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  43926. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  43927. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  43928. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  43929. this.direction.normalize();
  43930. return this;
  43931. };
  43932. // Statics
  43933. Ray.Zero = function () {
  43934. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  43935. };
  43936. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  43937. var result = Ray.Zero();
  43938. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  43939. };
  43940. /**
  43941. * 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
  43942. * transformed to the given world matrix.
  43943. * @param origin The origin point
  43944. * @param end The end point
  43945. * @param world a matrix to transform the ray to. Default is the identity matrix.
  43946. */
  43947. Ray.CreateNewFromTo = function (origin, end, world) {
  43948. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  43949. var direction = end.subtract(origin);
  43950. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  43951. direction.normalize();
  43952. return Ray.Transform(new Ray(origin, direction, length), world);
  43953. };
  43954. Ray.Transform = function (ray, matrix) {
  43955. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  43956. Ray.TransformToRef(ray, matrix, result);
  43957. return result;
  43958. };
  43959. Ray.TransformToRef = function (ray, matrix, result) {
  43960. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  43961. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  43962. result.length = ray.length;
  43963. var dir = result.direction;
  43964. var len = dir.length();
  43965. if (!(len === 0 || len === 1)) {
  43966. var num = 1.0 / len;
  43967. dir.x *= num;
  43968. dir.y *= num;
  43969. dir.z *= num;
  43970. result.length *= len;
  43971. }
  43972. };
  43973. Ray.smallnum = 0.00000001;
  43974. Ray.rayl = 10e8;
  43975. return Ray;
  43976. }());
  43977. BABYLON.Ray = Ray;
  43978. })(BABYLON || (BABYLON = {}));
  43979. //# sourceMappingURL=babylon.ray.js.map
  43980. var BABYLON;
  43981. (function (BABYLON) {
  43982. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  43983. if (boxMin.x > sphereCenter.x + sphereRadius)
  43984. return false;
  43985. if (sphereCenter.x - sphereRadius > boxMax.x)
  43986. return false;
  43987. if (boxMin.y > sphereCenter.y + sphereRadius)
  43988. return false;
  43989. if (sphereCenter.y - sphereRadius > boxMax.y)
  43990. return false;
  43991. if (boxMin.z > sphereCenter.z + sphereRadius)
  43992. return false;
  43993. if (sphereCenter.z - sphereRadius > boxMax.z)
  43994. return false;
  43995. return true;
  43996. };
  43997. var getLowestRoot = (function () {
  43998. var result = { root: 0, found: false };
  43999. return function (a, b, c, maxR) {
  44000. result.root = 0;
  44001. result.found = false;
  44002. var determinant = b * b - 4.0 * a * c;
  44003. if (determinant < 0)
  44004. return result;
  44005. var sqrtD = Math.sqrt(determinant);
  44006. var r1 = (-b - sqrtD) / (2.0 * a);
  44007. var r2 = (-b + sqrtD) / (2.0 * a);
  44008. if (r1 > r2) {
  44009. var temp = r2;
  44010. r2 = r1;
  44011. r1 = temp;
  44012. }
  44013. if (r1 > 0 && r1 < maxR) {
  44014. result.root = r1;
  44015. result.found = true;
  44016. return result;
  44017. }
  44018. if (r2 > 0 && r2 < maxR) {
  44019. result.root = r2;
  44020. result.found = true;
  44021. return result;
  44022. }
  44023. return result;
  44024. };
  44025. })();
  44026. var Collider = /** @class */ (function () {
  44027. function Collider() {
  44028. this.radius = BABYLON.Vector3.One();
  44029. this.retry = 0;
  44030. this.basePointWorld = BABYLON.Vector3.Zero();
  44031. this.velocityWorld = BABYLON.Vector3.Zero();
  44032. this.normalizedVelocity = BABYLON.Vector3.Zero();
  44033. this._collisionPoint = BABYLON.Vector3.Zero();
  44034. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  44035. this._tempVector = BABYLON.Vector3.Zero();
  44036. this._tempVector2 = BABYLON.Vector3.Zero();
  44037. this._tempVector3 = BABYLON.Vector3.Zero();
  44038. this._tempVector4 = BABYLON.Vector3.Zero();
  44039. this._edge = BABYLON.Vector3.Zero();
  44040. this._baseToVertex = BABYLON.Vector3.Zero();
  44041. this._destinationPoint = BABYLON.Vector3.Zero();
  44042. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  44043. this._displacementVector = BABYLON.Vector3.Zero();
  44044. this._collisionMask = -1;
  44045. }
  44046. Object.defineProperty(Collider.prototype, "collisionMask", {
  44047. get: function () {
  44048. return this._collisionMask;
  44049. },
  44050. set: function (mask) {
  44051. this._collisionMask = !isNaN(mask) ? mask : -1;
  44052. },
  44053. enumerable: true,
  44054. configurable: true
  44055. });
  44056. // Methods
  44057. Collider.prototype._initialize = function (source, dir, e) {
  44058. this.velocity = dir;
  44059. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  44060. this.basePoint = source;
  44061. source.multiplyToRef(this.radius, this.basePointWorld);
  44062. dir.multiplyToRef(this.radius, this.velocityWorld);
  44063. this.velocityWorldLength = this.velocityWorld.length();
  44064. this.epsilon = e;
  44065. this.collisionFound = false;
  44066. };
  44067. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  44068. pa.subtractToRef(point, this._tempVector);
  44069. pb.subtractToRef(point, this._tempVector2);
  44070. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  44071. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44072. if (d < 0)
  44073. return false;
  44074. pc.subtractToRef(point, this._tempVector3);
  44075. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  44076. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44077. if (d < 0)
  44078. return false;
  44079. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  44080. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44081. return d >= 0;
  44082. };
  44083. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  44084. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  44085. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  44086. if (distance > this.velocityWorldLength + max + sphereRadius) {
  44087. return false;
  44088. }
  44089. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  44090. return false;
  44091. return true;
  44092. };
  44093. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  44094. var t0;
  44095. var embeddedInPlane = false;
  44096. //defensive programming, actually not needed.
  44097. if (!trianglePlaneArray) {
  44098. trianglePlaneArray = [];
  44099. }
  44100. if (!trianglePlaneArray[faceIndex]) {
  44101. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  44102. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  44103. }
  44104. var trianglePlane = trianglePlaneArray[faceIndex];
  44105. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  44106. return;
  44107. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  44108. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  44109. if (normalDotVelocity == 0) {
  44110. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  44111. return;
  44112. embeddedInPlane = true;
  44113. t0 = 0;
  44114. }
  44115. else {
  44116. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44117. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44118. if (t0 > t1) {
  44119. var temp = t1;
  44120. t1 = t0;
  44121. t0 = temp;
  44122. }
  44123. if (t0 > 1.0 || t1 < 0.0)
  44124. return;
  44125. if (t0 < 0)
  44126. t0 = 0;
  44127. if (t0 > 1.0)
  44128. t0 = 1.0;
  44129. }
  44130. this._collisionPoint.copyFromFloats(0, 0, 0);
  44131. var found = false;
  44132. var t = 1.0;
  44133. if (!embeddedInPlane) {
  44134. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  44135. this.velocity.scaleToRef(t0, this._tempVector);
  44136. this._planeIntersectionPoint.addInPlace(this._tempVector);
  44137. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  44138. found = true;
  44139. t = t0;
  44140. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  44141. }
  44142. }
  44143. if (!found) {
  44144. var velocitySquaredLength = this.velocity.lengthSquared();
  44145. var a = velocitySquaredLength;
  44146. this.basePoint.subtractToRef(p1, this._tempVector);
  44147. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  44148. var c = this._tempVector.lengthSquared() - 1.0;
  44149. var lowestRoot = getLowestRoot(a, b, c, t);
  44150. if (lowestRoot.found) {
  44151. t = lowestRoot.root;
  44152. found = true;
  44153. this._collisionPoint.copyFrom(p1);
  44154. }
  44155. this.basePoint.subtractToRef(p2, this._tempVector);
  44156. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  44157. c = this._tempVector.lengthSquared() - 1.0;
  44158. lowestRoot = getLowestRoot(a, b, c, t);
  44159. if (lowestRoot.found) {
  44160. t = lowestRoot.root;
  44161. found = true;
  44162. this._collisionPoint.copyFrom(p2);
  44163. }
  44164. this.basePoint.subtractToRef(p3, this._tempVector);
  44165. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  44166. c = this._tempVector.lengthSquared() - 1.0;
  44167. lowestRoot = getLowestRoot(a, b, c, t);
  44168. if (lowestRoot.found) {
  44169. t = lowestRoot.root;
  44170. found = true;
  44171. this._collisionPoint.copyFrom(p3);
  44172. }
  44173. p2.subtractToRef(p1, this._edge);
  44174. p1.subtractToRef(this.basePoint, this._baseToVertex);
  44175. var edgeSquaredLength = this._edge.lengthSquared();
  44176. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44177. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44178. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44179. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44180. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44181. lowestRoot = getLowestRoot(a, b, c, t);
  44182. if (lowestRoot.found) {
  44183. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44184. if (f >= 0.0 && f <= 1.0) {
  44185. t = lowestRoot.root;
  44186. found = true;
  44187. this._edge.scaleInPlace(f);
  44188. p1.addToRef(this._edge, this._collisionPoint);
  44189. }
  44190. }
  44191. p3.subtractToRef(p2, this._edge);
  44192. p2.subtractToRef(this.basePoint, this._baseToVertex);
  44193. edgeSquaredLength = this._edge.lengthSquared();
  44194. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44195. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44196. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44197. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44198. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44199. lowestRoot = getLowestRoot(a, b, c, t);
  44200. if (lowestRoot.found) {
  44201. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44202. if (f >= 0.0 && f <= 1.0) {
  44203. t = lowestRoot.root;
  44204. found = true;
  44205. this._edge.scaleInPlace(f);
  44206. p2.addToRef(this._edge, this._collisionPoint);
  44207. }
  44208. }
  44209. p1.subtractToRef(p3, this._edge);
  44210. p3.subtractToRef(this.basePoint, this._baseToVertex);
  44211. edgeSquaredLength = this._edge.lengthSquared();
  44212. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44213. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44214. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44215. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44216. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44217. lowestRoot = getLowestRoot(a, b, c, t);
  44218. if (lowestRoot.found) {
  44219. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44220. if (f >= 0.0 && f <= 1.0) {
  44221. t = lowestRoot.root;
  44222. found = true;
  44223. this._edge.scaleInPlace(f);
  44224. p3.addToRef(this._edge, this._collisionPoint);
  44225. }
  44226. }
  44227. }
  44228. if (found) {
  44229. var distToCollision = t * this.velocity.length();
  44230. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  44231. if (!this.intersectionPoint) {
  44232. this.intersectionPoint = this._collisionPoint.clone();
  44233. }
  44234. else {
  44235. this.intersectionPoint.copyFrom(this._collisionPoint);
  44236. }
  44237. this.nearestDistance = distToCollision;
  44238. this.collisionFound = true;
  44239. }
  44240. }
  44241. };
  44242. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  44243. for (var i = indexStart; i < indexEnd; i += 3) {
  44244. var p1 = pts[indices[i] - decal];
  44245. var p2 = pts[indices[i + 1] - decal];
  44246. var p3 = pts[indices[i + 2] - decal];
  44247. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  44248. }
  44249. };
  44250. Collider.prototype._getResponse = function (pos, vel) {
  44251. pos.addToRef(vel, this._destinationPoint);
  44252. vel.scaleInPlace((this.nearestDistance / vel.length()));
  44253. this.basePoint.addToRef(vel, pos);
  44254. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  44255. this._slidePlaneNormal.normalize();
  44256. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  44257. pos.addInPlace(this._displacementVector);
  44258. this.intersectionPoint.addInPlace(this._displacementVector);
  44259. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  44260. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  44261. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  44262. };
  44263. return Collider;
  44264. }());
  44265. BABYLON.Collider = Collider;
  44266. })(BABYLON || (BABYLON = {}));
  44267. //# sourceMappingURL=babylon.collider.js.map
  44268. var BABYLON;
  44269. (function (BABYLON) {
  44270. //WebWorker code will be inserted to this variable.
  44271. BABYLON.CollisionWorker = "";
  44272. var WorkerTaskType;
  44273. (function (WorkerTaskType) {
  44274. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  44275. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  44276. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  44277. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  44278. var WorkerReplyType;
  44279. (function (WorkerReplyType) {
  44280. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  44281. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  44282. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  44283. var CollisionCoordinatorWorker = /** @class */ (function () {
  44284. function CollisionCoordinatorWorker() {
  44285. var _this = this;
  44286. this._scaledPosition = BABYLON.Vector3.Zero();
  44287. this._scaledVelocity = BABYLON.Vector3.Zero();
  44288. this.onMeshUpdated = function (transformNode) {
  44289. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  44290. };
  44291. this.onGeometryUpdated = function (geometry) {
  44292. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  44293. };
  44294. this._afterRender = function () {
  44295. if (!_this._init)
  44296. return;
  44297. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  44298. return;
  44299. }
  44300. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  44301. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  44302. if (_this._runningUpdated > 4) {
  44303. return;
  44304. }
  44305. ++_this._runningUpdated;
  44306. var payload = {
  44307. updatedMeshes: _this._addUpdateMeshesList,
  44308. updatedGeometries: _this._addUpdateGeometriesList,
  44309. removedGeometries: _this._toRemoveGeometryArray,
  44310. removedMeshes: _this._toRemoveMeshesArray
  44311. };
  44312. var message = {
  44313. payload: payload,
  44314. taskType: WorkerTaskType.UPDATE
  44315. };
  44316. var serializable = [];
  44317. for (var id in payload.updatedGeometries) {
  44318. if (payload.updatedGeometries.hasOwnProperty(id)) {
  44319. //prepare transferables
  44320. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  44321. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  44322. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  44323. }
  44324. }
  44325. _this._worker.postMessage(message, serializable);
  44326. _this._addUpdateMeshesList = {};
  44327. _this._addUpdateGeometriesList = {};
  44328. _this._toRemoveGeometryArray = [];
  44329. _this._toRemoveMeshesArray = [];
  44330. };
  44331. this._onMessageFromWorker = function (e) {
  44332. var returnData = e.data;
  44333. if (returnData.error != WorkerReplyType.SUCCESS) {
  44334. //TODO what errors can be returned from the worker?
  44335. BABYLON.Tools.Warn("error returned from worker!");
  44336. return;
  44337. }
  44338. switch (returnData.taskType) {
  44339. case WorkerTaskType.INIT:
  44340. _this._init = true;
  44341. //Update the worked with ALL of the scene's current state
  44342. _this._scene.meshes.forEach(function (mesh) {
  44343. _this.onMeshAdded(mesh);
  44344. });
  44345. _this._scene.getGeometries().forEach(function (geometry) {
  44346. _this.onGeometryAdded(geometry);
  44347. });
  44348. break;
  44349. case WorkerTaskType.UPDATE:
  44350. _this._runningUpdated--;
  44351. break;
  44352. case WorkerTaskType.COLLIDE:
  44353. var returnPayload = returnData.payload;
  44354. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  44355. return;
  44356. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  44357. if (callback) {
  44358. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  44359. if (mesh) {
  44360. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  44361. }
  44362. }
  44363. //cleanup
  44364. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  44365. break;
  44366. }
  44367. };
  44368. this._collisionsCallbackArray = [];
  44369. this._init = false;
  44370. this._runningUpdated = 0;
  44371. this._addUpdateMeshesList = {};
  44372. this._addUpdateGeometriesList = {};
  44373. this._toRemoveGeometryArray = [];
  44374. this._toRemoveMeshesArray = [];
  44375. }
  44376. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  44377. if (!this._init)
  44378. return;
  44379. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  44380. return;
  44381. position.divideToRef(collider.radius, this._scaledPosition);
  44382. displacement.divideToRef(collider.radius, this._scaledVelocity);
  44383. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  44384. var payload = {
  44385. collider: {
  44386. position: this._scaledPosition.asArray(),
  44387. velocity: this._scaledVelocity.asArray(),
  44388. radius: collider.radius.asArray()
  44389. },
  44390. collisionId: collisionIndex,
  44391. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  44392. maximumRetry: maximumRetry
  44393. };
  44394. var message = {
  44395. payload: payload,
  44396. taskType: WorkerTaskType.COLLIDE
  44397. };
  44398. this._worker.postMessage(message);
  44399. };
  44400. CollisionCoordinatorWorker.prototype.init = function (scene) {
  44401. this._scene = scene;
  44402. this._scene.registerAfterRender(this._afterRender);
  44403. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  44404. this._worker = new Worker(workerUrl);
  44405. this._worker.onmessage = this._onMessageFromWorker;
  44406. var message = {
  44407. payload: {},
  44408. taskType: WorkerTaskType.INIT
  44409. };
  44410. this._worker.postMessage(message);
  44411. };
  44412. CollisionCoordinatorWorker.prototype.destroy = function () {
  44413. this._scene.unregisterAfterRender(this._afterRender);
  44414. this._worker.terminate();
  44415. };
  44416. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  44417. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  44418. this.onMeshUpdated(mesh);
  44419. };
  44420. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  44421. this._toRemoveMeshesArray.push(mesh.uniqueId);
  44422. };
  44423. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  44424. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  44425. geometry.onGeometryUpdated = this.onGeometryUpdated;
  44426. this.onGeometryUpdated(geometry);
  44427. };
  44428. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  44429. this._toRemoveGeometryArray.push(geometry.id);
  44430. };
  44431. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  44432. var submeshes = [];
  44433. if (mesh.subMeshes) {
  44434. submeshes = mesh.subMeshes.map(function (sm, idx) {
  44435. var boundingInfo = sm.getBoundingInfo();
  44436. return {
  44437. position: idx,
  44438. verticesStart: sm.verticesStart,
  44439. verticesCount: sm.verticesCount,
  44440. indexStart: sm.indexStart,
  44441. indexCount: sm.indexCount,
  44442. hasMaterial: !!sm.getMaterial(),
  44443. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  44444. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  44445. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  44446. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  44447. };
  44448. });
  44449. }
  44450. var geometryId = null;
  44451. if (mesh instanceof BABYLON.Mesh) {
  44452. var geometry = mesh.geometry;
  44453. geometryId = geometry ? geometry.id : null;
  44454. }
  44455. else if (mesh instanceof BABYLON.InstancedMesh) {
  44456. var geometry = mesh.sourceMesh.geometry;
  44457. geometryId = geometry ? geometry.id : null;
  44458. }
  44459. var boundingInfo = mesh.getBoundingInfo();
  44460. return {
  44461. uniqueId: mesh.uniqueId,
  44462. id: mesh.id,
  44463. name: mesh.name,
  44464. geometryId: geometryId,
  44465. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  44466. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  44467. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  44468. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  44469. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  44470. subMeshes: submeshes,
  44471. checkCollisions: mesh.checkCollisions
  44472. };
  44473. };
  44474. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  44475. return {
  44476. id: geometry.id,
  44477. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  44478. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  44479. indices: new Uint32Array(geometry.getIndices() || []),
  44480. };
  44481. };
  44482. return CollisionCoordinatorWorker;
  44483. }());
  44484. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  44485. var CollisionCoordinatorLegacy = /** @class */ (function () {
  44486. function CollisionCoordinatorLegacy() {
  44487. this._scaledPosition = BABYLON.Vector3.Zero();
  44488. this._scaledVelocity = BABYLON.Vector3.Zero();
  44489. this._finalPosition = BABYLON.Vector3.Zero();
  44490. }
  44491. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  44492. position.divideToRef(collider.radius, this._scaledPosition);
  44493. displacement.divideToRef(collider.radius, this._scaledVelocity);
  44494. collider.collidedMesh = null;
  44495. collider.retry = 0;
  44496. collider.initialVelocity = this._scaledVelocity;
  44497. collider.initialPosition = this._scaledPosition;
  44498. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  44499. this._finalPosition.multiplyInPlace(collider.radius);
  44500. //run the callback
  44501. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  44502. };
  44503. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  44504. this._scene = scene;
  44505. };
  44506. CollisionCoordinatorLegacy.prototype.destroy = function () {
  44507. //Legacy need no destruction method.
  44508. };
  44509. //No update in legacy mode
  44510. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  44511. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  44512. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  44513. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  44514. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  44515. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  44516. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  44517. if (excludedMesh === void 0) { excludedMesh = null; }
  44518. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  44519. if (collider.retry >= maximumRetry) {
  44520. finalPosition.copyFrom(position);
  44521. return;
  44522. }
  44523. // Check if this is a mesh else camera or -1
  44524. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  44525. collider._initialize(position, velocity, closeDistance);
  44526. // Check all meshes
  44527. for (var index = 0; index < this._scene.meshes.length; index++) {
  44528. var mesh = this._scene.meshes[index];
  44529. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  44530. mesh._checkCollision(collider);
  44531. }
  44532. }
  44533. if (!collider.collisionFound) {
  44534. position.addToRef(velocity, finalPosition);
  44535. return;
  44536. }
  44537. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  44538. collider._getResponse(position, velocity);
  44539. }
  44540. if (velocity.length() <= closeDistance) {
  44541. finalPosition.copyFrom(position);
  44542. return;
  44543. }
  44544. collider.retry++;
  44545. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  44546. };
  44547. return CollisionCoordinatorLegacy;
  44548. }());
  44549. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  44550. })(BABYLON || (BABYLON = {}));
  44551. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  44552. var BABYLON;
  44553. (function (BABYLON) {
  44554. var Particle = /** @class */ (function () {
  44555. function Particle(particleSystem) {
  44556. this.particleSystem = particleSystem;
  44557. this.position = BABYLON.Vector3.Zero();
  44558. this.direction = BABYLON.Vector3.Zero();
  44559. this.color = new BABYLON.Color4(0, 0, 0, 0);
  44560. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  44561. this.lifeTime = 1.0;
  44562. this.age = 0;
  44563. this.size = 0;
  44564. this.angle = 0;
  44565. this.angularSpeed = 0;
  44566. this._currentFrameCounter = 0;
  44567. this.cellIndex = 0;
  44568. if (!this.particleSystem.isAnimationSheetEnabled) {
  44569. return;
  44570. }
  44571. this.cellIndex = this.particleSystem.startSpriteCellID;
  44572. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  44573. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  44574. }
  44575. else {
  44576. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  44577. }
  44578. }
  44579. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  44580. // (ageOffset / scaledUpdateSpeed) / available cells
  44581. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  44582. this._currentFrameCounter += scaledUpdateSpeed;
  44583. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  44584. this._currentFrameCounter = 0;
  44585. this.cellIndex++;
  44586. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  44587. this.cellIndex = this.particleSystem.endSpriteCellID;
  44588. }
  44589. }
  44590. };
  44591. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  44592. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  44593. this.cellIndex++;
  44594. this._currentFrameCounter = 0;
  44595. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  44596. if (this.particleSystem.spriteCellLoop) {
  44597. this.cellIndex = this.particleSystem.startSpriteCellID;
  44598. }
  44599. else {
  44600. this.cellIndex = this.particleSystem.endSpriteCellID;
  44601. }
  44602. }
  44603. }
  44604. else {
  44605. this._currentFrameCounter++;
  44606. }
  44607. };
  44608. Particle.prototype.copyTo = function (other) {
  44609. other.position.copyFrom(this.position);
  44610. other.direction.copyFrom(this.direction);
  44611. other.color.copyFrom(this.color);
  44612. other.colorStep.copyFrom(this.colorStep);
  44613. other.lifeTime = this.lifeTime;
  44614. other.age = this.age;
  44615. other.size = this.size;
  44616. other.angle = this.angle;
  44617. other.angularSpeed = this.angularSpeed;
  44618. other.particleSystem = this.particleSystem;
  44619. other.cellIndex = this.cellIndex;
  44620. };
  44621. return Particle;
  44622. }());
  44623. BABYLON.Particle = Particle;
  44624. })(BABYLON || (BABYLON = {}));
  44625. //# sourceMappingURL=babylon.particle.js.map
  44626. var BABYLON;
  44627. (function (BABYLON) {
  44628. var randomNumber = function (min, max) {
  44629. if (min === max) {
  44630. return (min);
  44631. }
  44632. var random = Math.random();
  44633. return ((random * (max - min)) + min);
  44634. };
  44635. var ParticleSystem = /** @class */ (function () {
  44636. // end of sheet animation
  44637. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  44638. if (customEffect === void 0) { customEffect = null; }
  44639. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  44640. if (epsilon === void 0) { epsilon = 0.01; }
  44641. var _this = this;
  44642. this.name = name;
  44643. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  44644. // Members
  44645. this.animations = [];
  44646. this.renderingGroupId = 0;
  44647. this.emitter = null;
  44648. this.emitRate = 10;
  44649. this.manualEmitCount = -1;
  44650. this.updateSpeed = 0.01;
  44651. this.targetStopDuration = 0;
  44652. this.disposeOnStop = false;
  44653. this.minEmitPower = 1;
  44654. this.maxEmitPower = 1;
  44655. this.minLifeTime = 1;
  44656. this.maxLifeTime = 1;
  44657. this.minSize = 1;
  44658. this.maxSize = 1;
  44659. this.minAngularSpeed = 0;
  44660. this.maxAngularSpeed = 0;
  44661. this.layerMask = 0x0FFFFFFF;
  44662. this.customShader = null;
  44663. this.preventAutoStart = false;
  44664. /**
  44665. * An event triggered when the system is disposed.
  44666. * @type {BABYLON.Observable}
  44667. */
  44668. this.onDisposeObservable = new BABYLON.Observable();
  44669. this.onAnimationEnd = null;
  44670. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  44671. this.forceDepthWrite = false;
  44672. this.gravity = BABYLON.Vector3.Zero();
  44673. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  44674. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  44675. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  44676. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44677. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44678. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44679. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  44680. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44681. this.particles = new Array();
  44682. this._stockParticles = new Array();
  44683. this._newPartsExcess = 0;
  44684. this._vertexBuffers = {};
  44685. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  44686. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  44687. this._scaledDirection = BABYLON.Vector3.Zero();
  44688. this._scaledGravity = BABYLON.Vector3.Zero();
  44689. this._currentRenderId = -1;
  44690. this._started = false;
  44691. this._stopped = false;
  44692. this._actualFrame = 0;
  44693. // sheet animation
  44694. this.startSpriteCellID = 0;
  44695. this.endSpriteCellID = 0;
  44696. this.spriteCellLoop = true;
  44697. this.spriteCellChangeSpeed = 0;
  44698. this.spriteCellWidth = 0;
  44699. this.spriteCellHeight = 0;
  44700. this._vertexBufferSize = 11;
  44701. this.appendParticleVertexes = null;
  44702. this.id = name;
  44703. this._capacity = capacity;
  44704. this._epsilon = epsilon;
  44705. if (_isAnimationSheetEnabled) {
  44706. this._vertexBufferSize = 12;
  44707. }
  44708. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44709. this._customEffect = customEffect;
  44710. scene.particleSystems.push(this);
  44711. this._createIndexBuffer();
  44712. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  44713. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  44714. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  44715. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  44716. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  44717. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  44718. if (this._isAnimationSheetEnabled) {
  44719. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  44720. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  44721. }
  44722. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44723. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44724. this._vertexBuffers["options"] = options;
  44725. // Default behaviors
  44726. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  44727. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  44728. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  44729. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  44730. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  44731. };
  44732. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  44733. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  44734. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  44735. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  44736. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  44737. };
  44738. this.updateFunction = function (particles) {
  44739. for (var index = 0; index < particles.length; index++) {
  44740. var particle = particles[index];
  44741. particle.age += _this._scaledUpdateSpeed;
  44742. if (particle.age >= particle.lifeTime) {
  44743. _this.recycleParticle(particle);
  44744. index--;
  44745. continue;
  44746. }
  44747. else {
  44748. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  44749. particle.color.addInPlace(_this._scaledColorStep);
  44750. if (particle.color.a < 0)
  44751. particle.color.a = 0;
  44752. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  44753. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  44754. particle.position.addInPlace(_this._scaledDirection);
  44755. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  44756. particle.direction.addInPlace(_this._scaledGravity);
  44757. if (_this._isAnimationSheetEnabled) {
  44758. particle.updateCellIndex(_this._scaledUpdateSpeed);
  44759. }
  44760. }
  44761. }
  44762. };
  44763. }
  44764. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  44765. set: function (callback) {
  44766. if (this._onDisposeObserver) {
  44767. this.onDisposeObservable.remove(this._onDisposeObserver);
  44768. }
  44769. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44770. },
  44771. enumerable: true,
  44772. configurable: true
  44773. });
  44774. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  44775. get: function () {
  44776. return this._isAnimationSheetEnabled;
  44777. },
  44778. enumerable: true,
  44779. configurable: true
  44780. });
  44781. ParticleSystem.prototype._createIndexBuffer = function () {
  44782. var indices = [];
  44783. var index = 0;
  44784. for (var count = 0; count < this._capacity; count++) {
  44785. indices.push(index);
  44786. indices.push(index + 1);
  44787. indices.push(index + 2);
  44788. indices.push(index);
  44789. indices.push(index + 2);
  44790. indices.push(index + 3);
  44791. index += 4;
  44792. }
  44793. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  44794. };
  44795. ParticleSystem.prototype.recycleParticle = function (particle) {
  44796. var lastParticle = this.particles.pop();
  44797. if (lastParticle !== particle) {
  44798. lastParticle.copyTo(particle);
  44799. this._stockParticles.push(lastParticle);
  44800. }
  44801. };
  44802. ParticleSystem.prototype.getCapacity = function () {
  44803. return this._capacity;
  44804. };
  44805. ParticleSystem.prototype.isAlive = function () {
  44806. return this._alive;
  44807. };
  44808. ParticleSystem.prototype.isStarted = function () {
  44809. return this._started;
  44810. };
  44811. ParticleSystem.prototype.start = function () {
  44812. this._started = true;
  44813. this._stopped = false;
  44814. this._actualFrame = 0;
  44815. };
  44816. ParticleSystem.prototype.stop = function () {
  44817. this._stopped = true;
  44818. };
  44819. // animation sheet
  44820. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  44821. var offset = index * this._vertexBufferSize;
  44822. this._vertexData[offset] = particle.position.x;
  44823. this._vertexData[offset + 1] = particle.position.y;
  44824. this._vertexData[offset + 2] = particle.position.z;
  44825. this._vertexData[offset + 3] = particle.color.r;
  44826. this._vertexData[offset + 4] = particle.color.g;
  44827. this._vertexData[offset + 5] = particle.color.b;
  44828. this._vertexData[offset + 6] = particle.color.a;
  44829. this._vertexData[offset + 7] = particle.angle;
  44830. this._vertexData[offset + 8] = particle.size;
  44831. this._vertexData[offset + 9] = offsetX;
  44832. this._vertexData[offset + 10] = offsetY;
  44833. };
  44834. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  44835. if (offsetX === 0)
  44836. offsetX = this._epsilon;
  44837. else if (offsetX === 1)
  44838. offsetX = 1 - this._epsilon;
  44839. if (offsetY === 0)
  44840. offsetY = this._epsilon;
  44841. else if (offsetY === 1)
  44842. offsetY = 1 - this._epsilon;
  44843. var offset = index * this._vertexBufferSize;
  44844. this._vertexData[offset] = particle.position.x;
  44845. this._vertexData[offset + 1] = particle.position.y;
  44846. this._vertexData[offset + 2] = particle.position.z;
  44847. this._vertexData[offset + 3] = particle.color.r;
  44848. this._vertexData[offset + 4] = particle.color.g;
  44849. this._vertexData[offset + 5] = particle.color.b;
  44850. this._vertexData[offset + 6] = particle.color.a;
  44851. this._vertexData[offset + 7] = particle.angle;
  44852. this._vertexData[offset + 8] = particle.size;
  44853. this._vertexData[offset + 9] = offsetX;
  44854. this._vertexData[offset + 10] = offsetY;
  44855. this._vertexData[offset + 11] = particle.cellIndex;
  44856. };
  44857. ParticleSystem.prototype._update = function (newParticles) {
  44858. // Update current
  44859. this._alive = this.particles.length > 0;
  44860. this.updateFunction(this.particles);
  44861. // Add new ones
  44862. var worldMatrix;
  44863. if (this.emitter.position) {
  44864. var emitterMesh = this.emitter;
  44865. worldMatrix = emitterMesh.getWorldMatrix();
  44866. }
  44867. else {
  44868. var emitterPosition = this.emitter;
  44869. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  44870. }
  44871. var particle;
  44872. for (var index = 0; index < newParticles; index++) {
  44873. if (this.particles.length === this._capacity) {
  44874. break;
  44875. }
  44876. if (this._stockParticles.length !== 0) {
  44877. particle = this._stockParticles.pop();
  44878. particle.age = 0;
  44879. particle.cellIndex = this.startSpriteCellID;
  44880. }
  44881. else {
  44882. particle = new BABYLON.Particle(this);
  44883. }
  44884. this.particles.push(particle);
  44885. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  44886. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  44887. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  44888. particle.size = randomNumber(this.minSize, this.maxSize);
  44889. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  44890. this.startPositionFunction(worldMatrix, particle.position, particle);
  44891. var step = randomNumber(0, 1.0);
  44892. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  44893. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  44894. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  44895. }
  44896. };
  44897. ParticleSystem.prototype._getEffect = function () {
  44898. if (this._customEffect) {
  44899. return this._customEffect;
  44900. }
  44901. ;
  44902. var defines = [];
  44903. if (this._scene.clipPlane) {
  44904. defines.push("#define CLIPPLANE");
  44905. }
  44906. if (this._isAnimationSheetEnabled) {
  44907. defines.push("#define ANIMATESHEET");
  44908. }
  44909. // Effect
  44910. var join = defines.join("\n");
  44911. if (this._cachedDefines !== join) {
  44912. this._cachedDefines = join;
  44913. var attributesNamesOrOptions;
  44914. var effectCreationOption;
  44915. if (this._isAnimationSheetEnabled) {
  44916. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  44917. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  44918. }
  44919. else {
  44920. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  44921. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  44922. }
  44923. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  44924. }
  44925. return this._effect;
  44926. };
  44927. ParticleSystem.prototype.animate = function () {
  44928. if (!this._started)
  44929. return;
  44930. var effect = this._getEffect();
  44931. // Check
  44932. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  44933. return;
  44934. if (this._currentRenderId === this._scene.getRenderId()) {
  44935. return;
  44936. }
  44937. this._currentRenderId = this._scene.getRenderId();
  44938. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  44939. // determine the number of particles we need to create
  44940. var newParticles;
  44941. if (this.manualEmitCount > -1) {
  44942. newParticles = this.manualEmitCount;
  44943. this._newPartsExcess = 0;
  44944. this.manualEmitCount = 0;
  44945. }
  44946. else {
  44947. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  44948. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  44949. }
  44950. if (this._newPartsExcess > 1.0) {
  44951. newParticles += this._newPartsExcess >> 0;
  44952. this._newPartsExcess -= this._newPartsExcess >> 0;
  44953. }
  44954. this._alive = false;
  44955. if (!this._stopped) {
  44956. this._actualFrame += this._scaledUpdateSpeed;
  44957. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  44958. this.stop();
  44959. }
  44960. else {
  44961. newParticles = 0;
  44962. }
  44963. this._update(newParticles);
  44964. // Stopped?
  44965. if (this._stopped) {
  44966. if (!this._alive) {
  44967. this._started = false;
  44968. if (this.onAnimationEnd) {
  44969. this.onAnimationEnd();
  44970. }
  44971. if (this.disposeOnStop) {
  44972. this._scene._toBeDisposed.push(this);
  44973. }
  44974. }
  44975. }
  44976. // Animation sheet
  44977. if (this._isAnimationSheetEnabled) {
  44978. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  44979. }
  44980. else {
  44981. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  44982. }
  44983. // Update VBO
  44984. var offset = 0;
  44985. for (var index = 0; index < this.particles.length; index++) {
  44986. var particle = this.particles[index];
  44987. this.appendParticleVertexes(offset, particle);
  44988. offset += 4;
  44989. }
  44990. if (this._vertexBuffer) {
  44991. this._vertexBuffer.update(this._vertexData);
  44992. }
  44993. };
  44994. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  44995. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  44996. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  44997. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  44998. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  44999. };
  45000. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  45001. this._appendParticleVertex(offset++, particle, 0, 0);
  45002. this._appendParticleVertex(offset++, particle, 1, 0);
  45003. this._appendParticleVertex(offset++, particle, 1, 1);
  45004. this._appendParticleVertex(offset++, particle, 0, 1);
  45005. };
  45006. ParticleSystem.prototype.rebuild = function () {
  45007. this._createIndexBuffer();
  45008. if (this._vertexBuffer) {
  45009. this._vertexBuffer._rebuild();
  45010. }
  45011. };
  45012. ParticleSystem.prototype.render = function () {
  45013. var effect = this._getEffect();
  45014. // Check
  45015. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  45016. return 0;
  45017. var engine = this._scene.getEngine();
  45018. // Render
  45019. engine.enableEffect(effect);
  45020. engine.setState(false);
  45021. var viewMatrix = this._scene.getViewMatrix();
  45022. effect.setTexture("diffuseSampler", this.particleTexture);
  45023. effect.setMatrix("view", viewMatrix);
  45024. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  45025. if (this._isAnimationSheetEnabled) {
  45026. var baseSize = this.particleTexture.getBaseSize();
  45027. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  45028. }
  45029. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  45030. if (this._scene.clipPlane) {
  45031. var clipPlane = this._scene.clipPlane;
  45032. var invView = viewMatrix.clone();
  45033. invView.invert();
  45034. effect.setMatrix("invView", invView);
  45035. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  45036. }
  45037. // VBOs
  45038. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  45039. // Draw order
  45040. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  45041. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  45042. }
  45043. else {
  45044. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  45045. }
  45046. if (this.forceDepthWrite) {
  45047. engine.setDepthWrite(true);
  45048. }
  45049. engine.draw(true, 0, this.particles.length * 6);
  45050. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  45051. return this.particles.length;
  45052. };
  45053. ParticleSystem.prototype.dispose = function () {
  45054. if (this._vertexBuffer) {
  45055. this._vertexBuffer.dispose();
  45056. this._vertexBuffer = null;
  45057. }
  45058. if (this._indexBuffer) {
  45059. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45060. this._indexBuffer = null;
  45061. }
  45062. if (this.particleTexture) {
  45063. this.particleTexture.dispose();
  45064. this.particleTexture = null;
  45065. }
  45066. // Remove from scene
  45067. var index = this._scene.particleSystems.indexOf(this);
  45068. if (index > -1) {
  45069. this._scene.particleSystems.splice(index, 1);
  45070. }
  45071. // Callback
  45072. this.onDisposeObservable.notifyObservers(this);
  45073. this.onDisposeObservable.clear();
  45074. };
  45075. // Clone
  45076. ParticleSystem.prototype.clone = function (name, newEmitter) {
  45077. var custom = null;
  45078. var program = null;
  45079. if (this.customShader != null) {
  45080. program = this.customShader;
  45081. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45082. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45083. }
  45084. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  45085. result.customShader = program;
  45086. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  45087. if (newEmitter === undefined) {
  45088. newEmitter = this.emitter;
  45089. }
  45090. result.emitter = newEmitter;
  45091. if (this.particleTexture) {
  45092. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  45093. }
  45094. if (!this.preventAutoStart) {
  45095. result.start();
  45096. }
  45097. return result;
  45098. };
  45099. ParticleSystem.prototype.serialize = function () {
  45100. var serializationObject = {};
  45101. serializationObject.name = this.name;
  45102. serializationObject.id = this.id;
  45103. // Emitter
  45104. if (this.emitter.position) {
  45105. var emitterMesh = this.emitter;
  45106. serializationObject.emitterId = emitterMesh.id;
  45107. }
  45108. else {
  45109. var emitterPosition = this.emitter;
  45110. serializationObject.emitter = emitterPosition.asArray();
  45111. }
  45112. serializationObject.capacity = this.getCapacity();
  45113. if (this.particleTexture) {
  45114. serializationObject.textureName = this.particleTexture.name;
  45115. }
  45116. // Animations
  45117. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  45118. // Particle system
  45119. serializationObject.minAngularSpeed = this.minAngularSpeed;
  45120. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  45121. serializationObject.minSize = this.minSize;
  45122. serializationObject.maxSize = this.maxSize;
  45123. serializationObject.minEmitPower = this.minEmitPower;
  45124. serializationObject.maxEmitPower = this.maxEmitPower;
  45125. serializationObject.minLifeTime = this.minLifeTime;
  45126. serializationObject.maxLifeTime = this.maxLifeTime;
  45127. serializationObject.emitRate = this.emitRate;
  45128. serializationObject.minEmitBox = this.minEmitBox.asArray();
  45129. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  45130. serializationObject.gravity = this.gravity.asArray();
  45131. serializationObject.direction1 = this.direction1.asArray();
  45132. serializationObject.direction2 = this.direction2.asArray();
  45133. serializationObject.color1 = this.color1.asArray();
  45134. serializationObject.color2 = this.color2.asArray();
  45135. serializationObject.colorDead = this.colorDead.asArray();
  45136. serializationObject.updateSpeed = this.updateSpeed;
  45137. serializationObject.targetStopDuration = this.targetStopDuration;
  45138. serializationObject.textureMask = this.textureMask.asArray();
  45139. serializationObject.blendMode = this.blendMode;
  45140. serializationObject.customShader = this.customShader;
  45141. serializationObject.preventAutoStart = this.preventAutoStart;
  45142. return serializationObject;
  45143. };
  45144. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  45145. var name = parsedParticleSystem.name;
  45146. var custom = null;
  45147. var program = null;
  45148. if (parsedParticleSystem.customShader) {
  45149. program = parsedParticleSystem.customShader;
  45150. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45151. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45152. }
  45153. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  45154. particleSystem.customShader = program;
  45155. if (parsedParticleSystem.id) {
  45156. particleSystem.id = parsedParticleSystem.id;
  45157. }
  45158. // Auto start
  45159. if (parsedParticleSystem.preventAutoStart) {
  45160. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  45161. }
  45162. // Texture
  45163. if (parsedParticleSystem.textureName) {
  45164. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  45165. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  45166. }
  45167. // Emitter
  45168. if (parsedParticleSystem.emitterId) {
  45169. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  45170. }
  45171. else {
  45172. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  45173. }
  45174. // Animations
  45175. if (parsedParticleSystem.animations) {
  45176. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  45177. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  45178. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45179. }
  45180. }
  45181. if (parsedParticleSystem.autoAnimate) {
  45182. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  45183. }
  45184. // Particle system
  45185. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  45186. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  45187. particleSystem.minSize = parsedParticleSystem.minSize;
  45188. particleSystem.maxSize = parsedParticleSystem.maxSize;
  45189. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  45190. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  45191. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  45192. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  45193. particleSystem.emitRate = parsedParticleSystem.emitRate;
  45194. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  45195. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  45196. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  45197. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  45198. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  45199. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  45200. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  45201. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  45202. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  45203. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  45204. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  45205. particleSystem.blendMode = parsedParticleSystem.blendMode;
  45206. if (!particleSystem.preventAutoStart) {
  45207. particleSystem.start();
  45208. }
  45209. return particleSystem;
  45210. };
  45211. // Statics
  45212. ParticleSystem.BLENDMODE_ONEONE = 0;
  45213. ParticleSystem.BLENDMODE_STANDARD = 1;
  45214. return ParticleSystem;
  45215. }());
  45216. BABYLON.ParticleSystem = ParticleSystem;
  45217. })(BABYLON || (BABYLON = {}));
  45218. //# sourceMappingURL=babylon.particleSystem.js.map
  45219. var BABYLON;
  45220. (function (BABYLON) {
  45221. var SolidParticle = /** @class */ (function () {
  45222. /**
  45223. * Creates a Solid Particle object.
  45224. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  45225. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  45226. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  45227. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  45228. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  45229. * `shapeId` (integer) is the model shape identifier in the SPS.
  45230. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  45231. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  45232. */
  45233. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  45234. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  45235. this.idx = 0; // particle global index
  45236. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  45237. this.position = BABYLON.Vector3.Zero(); // position
  45238. this.rotation = BABYLON.Vector3.Zero(); // rotation
  45239. this.scaling = BABYLON.Vector3.One(); // scaling
  45240. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  45241. this.velocity = BABYLON.Vector3.Zero(); // velocity
  45242. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  45243. this.alive = true; // alive
  45244. this.isVisible = true; // visibility
  45245. this._pos = 0; // index of this particle in the global "positions" array
  45246. this._ind = 0; // index of this particle in the global "indices" array
  45247. this.shapeId = 0; // model shape id
  45248. this.idxInShape = 0; // index of the particle in its shape id
  45249. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  45250. this.idx = particleIndex;
  45251. this._pos = positionIndex;
  45252. this._ind = indiceIndex;
  45253. this._model = model;
  45254. this.shapeId = shapeId;
  45255. this.idxInShape = idxInShape;
  45256. this._sps = sps;
  45257. if (modelBoundingInfo) {
  45258. this._modelBoundingInfo = modelBoundingInfo;
  45259. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  45260. }
  45261. }
  45262. Object.defineProperty(SolidParticle.prototype, "scale", {
  45263. /**
  45264. * legacy support, changed scale to scaling
  45265. */
  45266. get: function () {
  45267. return this.scaling;
  45268. },
  45269. set: function (scale) {
  45270. this.scaling = scale;
  45271. },
  45272. enumerable: true,
  45273. configurable: true
  45274. });
  45275. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  45276. /**
  45277. * legacy support, changed quaternion to rotationQuaternion
  45278. */
  45279. get: function () {
  45280. return this.rotationQuaternion;
  45281. },
  45282. set: function (q) {
  45283. this.rotationQuaternion = q;
  45284. },
  45285. enumerable: true,
  45286. configurable: true
  45287. });
  45288. /**
  45289. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  45290. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  45291. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  45292. */
  45293. SolidParticle.prototype.intersectsMesh = function (target) {
  45294. if (!this._boundingInfo || !target._boundingInfo) {
  45295. return false;
  45296. }
  45297. if (this._sps._bSphereOnly) {
  45298. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  45299. }
  45300. return this._boundingInfo.intersects(target._boundingInfo, false);
  45301. };
  45302. return SolidParticle;
  45303. }());
  45304. BABYLON.SolidParticle = SolidParticle;
  45305. var ModelShape = /** @class */ (function () {
  45306. /**
  45307. * 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.
  45308. * SPS internal tool, don't use it manually.
  45309. */
  45310. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  45311. this._indicesLength = 0; // length of the shape in the model indices array
  45312. this.shapeID = id;
  45313. this._shape = shape;
  45314. this._indicesLength = indicesLength;
  45315. this._shapeUV = shapeUV;
  45316. this._positionFunction = posFunction;
  45317. this._vertexFunction = vtxFunction;
  45318. }
  45319. return ModelShape;
  45320. }());
  45321. BABYLON.ModelShape = ModelShape;
  45322. var DepthSortedParticle = /** @class */ (function () {
  45323. function DepthSortedParticle() {
  45324. this.ind = 0; // index of the particle in the "indices" array
  45325. this.indicesLength = 0; // length of the particle shape in the "indices" array
  45326. this.sqDistance = 0.0; // squared distance from the particle to the camera
  45327. }
  45328. return DepthSortedParticle;
  45329. }());
  45330. BABYLON.DepthSortedParticle = DepthSortedParticle;
  45331. })(BABYLON || (BABYLON = {}));
  45332. //# sourceMappingURL=babylon.solidParticle.js.map
  45333. var BABYLON;
  45334. (function (BABYLON) {
  45335. /**
  45336. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  45337. */
  45338. var SolidParticleSystem = /** @class */ (function () {
  45339. /**
  45340. * Creates a SPS (Solid Particle System) object.
  45341. * `name` (String) is the SPS name, this will be the underlying mesh name.
  45342. * `scene` (Scene) is the scene in which the SPS is added.
  45343. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  45344. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  45345. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  45346. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  45347. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  45348. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  45349. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  45350. */
  45351. function SolidParticleSystem(name, scene, options) {
  45352. // public members
  45353. /**
  45354. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  45355. * Example : var p = SPS.particles[i];
  45356. */
  45357. this.particles = new Array();
  45358. /**
  45359. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  45360. */
  45361. this.nbParticles = 0;
  45362. /**
  45363. * If the particles must ever face the camera (default false). Useful for planar particles.
  45364. */
  45365. this.billboard = false;
  45366. /**
  45367. * Recompute normals when adding a shape
  45368. */
  45369. this.recomputeNormals = true;
  45370. /**
  45371. * This a counter ofr your own usage. It's not set by any SPS functions.
  45372. */
  45373. this.counter = 0;
  45374. /**
  45375. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  45376. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  45377. */
  45378. this.vars = {};
  45379. this._positions = new Array();
  45380. this._indices = new Array();
  45381. this._normals = new Array();
  45382. this._colors = new Array();
  45383. this._uvs = new Array();
  45384. this._index = 0; // indices index
  45385. this._updatable = true;
  45386. this._pickable = false;
  45387. this._isVisibilityBoxLocked = false;
  45388. this._alwaysVisible = false;
  45389. this._depthSort = false;
  45390. this._shapeCounter = 0;
  45391. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  45392. this._color = new BABYLON.Color4(0, 0, 0, 0);
  45393. this._computeParticleColor = true;
  45394. this._computeParticleTexture = true;
  45395. this._computeParticleRotation = true;
  45396. this._computeParticleVertex = false;
  45397. this._computeBoundingBox = false;
  45398. this._depthSortParticles = true;
  45399. this._cam_axisZ = BABYLON.Vector3.Zero();
  45400. this._cam_axisY = BABYLON.Vector3.Zero();
  45401. this._cam_axisX = BABYLON.Vector3.Zero();
  45402. this._axisZ = BABYLON.Axis.Z;
  45403. this._camDir = BABYLON.Vector3.Zero();
  45404. this._camInvertedPosition = BABYLON.Vector3.Zero();
  45405. this._rotMatrix = new BABYLON.Matrix();
  45406. this._invertMatrix = new BABYLON.Matrix();
  45407. this._rotated = BABYLON.Vector3.Zero();
  45408. this._quaternion = new BABYLON.Quaternion();
  45409. this._vertex = BABYLON.Vector3.Zero();
  45410. this._normal = BABYLON.Vector3.Zero();
  45411. this._yaw = 0.0;
  45412. this._pitch = 0.0;
  45413. this._roll = 0.0;
  45414. this._halfroll = 0.0;
  45415. this._halfpitch = 0.0;
  45416. this._halfyaw = 0.0;
  45417. this._sinRoll = 0.0;
  45418. this._cosRoll = 0.0;
  45419. this._sinPitch = 0.0;
  45420. this._cosPitch = 0.0;
  45421. this._sinYaw = 0.0;
  45422. this._cosYaw = 0.0;
  45423. this._mustUnrotateFixedNormals = false;
  45424. this._minimum = BABYLON.Tmp.Vector3[0];
  45425. this._maximum = BABYLON.Tmp.Vector3[1];
  45426. this._minBbox = BABYLON.Tmp.Vector3[4];
  45427. this._maxBbox = BABYLON.Tmp.Vector3[5];
  45428. this._particlesIntersect = false;
  45429. this._depthSortFunction = function (p1, p2) {
  45430. return (p2.sqDistance - p1.sqDistance);
  45431. };
  45432. this._needs32Bits = false;
  45433. this._bSphereOnly = false;
  45434. this._bSphereRadiusFactor = 1.0;
  45435. this.name = name;
  45436. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45437. this._camera = scene.activeCamera;
  45438. this._pickable = options ? options.isPickable : false;
  45439. this._depthSort = options ? options.enableDepthSort : false;
  45440. this._particlesIntersect = options ? options.particleIntersection : false;
  45441. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  45442. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  45443. if (options && options.updatable) {
  45444. this._updatable = options.updatable;
  45445. }
  45446. else {
  45447. this._updatable = true;
  45448. }
  45449. if (this._pickable) {
  45450. this.pickedParticles = [];
  45451. }
  45452. if (this._depthSort) {
  45453. this.depthSortedParticles = [];
  45454. }
  45455. }
  45456. /**
  45457. * Builds the SPS underlying mesh. Returns a standard Mesh.
  45458. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  45459. */
  45460. SolidParticleSystem.prototype.buildMesh = function () {
  45461. if (this.nbParticles === 0) {
  45462. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  45463. this.addShape(triangle, 1);
  45464. triangle.dispose();
  45465. }
  45466. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  45467. this._positions32 = new Float32Array(this._positions);
  45468. this._uvs32 = new Float32Array(this._uvs);
  45469. this._colors32 = new Float32Array(this._colors);
  45470. if (this.recomputeNormals) {
  45471. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  45472. }
  45473. this._normals32 = new Float32Array(this._normals);
  45474. this._fixedNormal32 = new Float32Array(this._normals);
  45475. if (this._mustUnrotateFixedNormals) {
  45476. this._unrotateFixedNormals();
  45477. }
  45478. var vertexData = new BABYLON.VertexData();
  45479. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  45480. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  45481. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  45482. if (this._uvs32) {
  45483. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  45484. ;
  45485. }
  45486. if (this._colors32) {
  45487. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  45488. }
  45489. var mesh = new BABYLON.Mesh(this.name, this._scene);
  45490. vertexData.applyToMesh(mesh, this._updatable);
  45491. this.mesh = mesh;
  45492. this.mesh.isPickable = this._pickable;
  45493. // free memory
  45494. if (!this._depthSort) {
  45495. this._indices = null;
  45496. }
  45497. this._positions = null;
  45498. this._normals = null;
  45499. this._uvs = null;
  45500. this._colors = null;
  45501. if (!this._updatable) {
  45502. this.particles.length = 0;
  45503. }
  45504. return mesh;
  45505. };
  45506. /**
  45507. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  45508. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  45509. * Thus the particles generated from `digest()` have their property `position` set yet.
  45510. * `mesh` ( Mesh ) is the mesh to be digested
  45511. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  45512. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  45513. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  45514. */
  45515. SolidParticleSystem.prototype.digest = function (mesh, options) {
  45516. var size = (options && options.facetNb) || 1;
  45517. var number = (options && options.number) || 0;
  45518. var delta = (options && options.delta) || 0;
  45519. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45520. var meshInd = mesh.getIndices();
  45521. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45522. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45523. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45524. var f = 0; // facet counter
  45525. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  45526. // compute size from number
  45527. if (number) {
  45528. number = (number > totalFacets) ? totalFacets : number;
  45529. size = Math.round(totalFacets / number);
  45530. delta = 0;
  45531. }
  45532. else {
  45533. size = (size > totalFacets) ? totalFacets : size;
  45534. }
  45535. var facetPos = []; // submesh positions
  45536. var facetInd = []; // submesh indices
  45537. var facetUV = []; // submesh UV
  45538. var facetCol = []; // submesh colors
  45539. var barycenter = BABYLON.Tmp.Vector3[0];
  45540. var sizeO = size;
  45541. while (f < totalFacets) {
  45542. size = sizeO + Math.floor((1 + delta) * Math.random());
  45543. if (f > totalFacets - size) {
  45544. size = totalFacets - f;
  45545. }
  45546. // reset temp arrays
  45547. facetPos.length = 0;
  45548. facetInd.length = 0;
  45549. facetUV.length = 0;
  45550. facetCol.length = 0;
  45551. // iterate over "size" facets
  45552. var fi = 0;
  45553. for (var j = f * 3; j < (f + size) * 3; j++) {
  45554. facetInd.push(fi);
  45555. var i = meshInd[j];
  45556. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  45557. if (meshUV) {
  45558. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  45559. }
  45560. if (meshCol) {
  45561. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  45562. }
  45563. fi++;
  45564. }
  45565. // create a model shape for each single particle
  45566. var idx = this.nbParticles;
  45567. var shape = this._posToShape(facetPos);
  45568. var shapeUV = this._uvsToShapeUV(facetUV);
  45569. // compute the barycenter of the shape
  45570. var v;
  45571. for (v = 0; v < shape.length; v++) {
  45572. barycenter.addInPlace(shape[v]);
  45573. }
  45574. barycenter.scaleInPlace(1 / shape.length);
  45575. // shift the shape from its barycenter to the origin
  45576. for (v = 0; v < shape.length; v++) {
  45577. shape[v].subtractInPlace(barycenter);
  45578. }
  45579. var bInfo;
  45580. if (this._particlesIntersect) {
  45581. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  45582. }
  45583. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  45584. // add the particle in the SPS
  45585. var currentPos = this._positions.length;
  45586. var currentInd = this._indices.length;
  45587. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  45588. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  45589. // initialize the particle position
  45590. this.particles[this.nbParticles].position.addInPlace(barycenter);
  45591. this._index += shape.length;
  45592. idx++;
  45593. this.nbParticles++;
  45594. this._shapeCounter++;
  45595. f += size;
  45596. }
  45597. return this;
  45598. };
  45599. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  45600. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  45601. var index = 0;
  45602. var idx = 0;
  45603. for (var p = 0; p < this.particles.length; p++) {
  45604. this._particle = this.particles[p];
  45605. this._shape = this._particle._model._shape;
  45606. if (this._particle.rotationQuaternion) {
  45607. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45608. }
  45609. else {
  45610. this._yaw = this._particle.rotation.y;
  45611. this._pitch = this._particle.rotation.x;
  45612. this._roll = this._particle.rotation.z;
  45613. this._quaternionRotationYPR();
  45614. }
  45615. this._quaternionToRotationMatrix();
  45616. this._rotMatrix.invertToRef(this._invertMatrix);
  45617. for (var pt = 0; pt < this._shape.length; pt++) {
  45618. idx = index + pt * 3;
  45619. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  45620. this._fixedNormal32[idx] = this._normal.x;
  45621. this._fixedNormal32[idx + 1] = this._normal.y;
  45622. this._fixedNormal32[idx + 2] = this._normal.z;
  45623. }
  45624. index = idx + 3;
  45625. }
  45626. };
  45627. //reset copy
  45628. SolidParticleSystem.prototype._resetCopy = function () {
  45629. this._copy.position.x = 0;
  45630. this._copy.position.y = 0;
  45631. this._copy.position.z = 0;
  45632. this._copy.rotation.x = 0;
  45633. this._copy.rotation.y = 0;
  45634. this._copy.rotation.z = 0;
  45635. this._copy.rotationQuaternion = null;
  45636. this._copy.scaling.x = 1.0;
  45637. this._copy.scaling.y = 1.0;
  45638. this._copy.scaling.z = 1.0;
  45639. this._copy.uvs.x = 0;
  45640. this._copy.uvs.y = 0;
  45641. this._copy.uvs.z = 1.0;
  45642. this._copy.uvs.w = 1.0;
  45643. this._copy.color = null;
  45644. };
  45645. // _meshBuilder : inserts the shape model in the global SPS mesh
  45646. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  45647. var i;
  45648. var u = 0;
  45649. var c = 0;
  45650. var n = 0;
  45651. this._resetCopy();
  45652. if (options && options.positionFunction) {
  45653. options.positionFunction(this._copy, idx, idxInShape);
  45654. this._mustUnrotateFixedNormals = true;
  45655. }
  45656. if (this._copy.rotationQuaternion) {
  45657. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45658. }
  45659. else {
  45660. this._yaw = this._copy.rotation.y;
  45661. this._pitch = this._copy.rotation.x;
  45662. this._roll = this._copy.rotation.z;
  45663. this._quaternionRotationYPR();
  45664. }
  45665. this._quaternionToRotationMatrix();
  45666. for (i = 0; i < shape.length; i++) {
  45667. this._vertex.x = shape[i].x;
  45668. this._vertex.y = shape[i].y;
  45669. this._vertex.z = shape[i].z;
  45670. if (options && options.vertexFunction) {
  45671. options.vertexFunction(this._copy, this._vertex, i);
  45672. }
  45673. this._vertex.x *= this._copy.scaling.x;
  45674. this._vertex.y *= this._copy.scaling.y;
  45675. this._vertex.z *= this._copy.scaling.z;
  45676. this._vertex.x += this._copy.pivot.x;
  45677. this._vertex.y += this._copy.pivot.y;
  45678. this._vertex.z += this._copy.pivot.z;
  45679. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45680. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  45681. if (meshUV) {
  45682. 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);
  45683. u += 2;
  45684. }
  45685. if (this._copy.color) {
  45686. this._color = this._copy.color;
  45687. }
  45688. else if (meshCol && meshCol[c] !== undefined) {
  45689. this._color.r = meshCol[c];
  45690. this._color.g = meshCol[c + 1];
  45691. this._color.b = meshCol[c + 2];
  45692. this._color.a = meshCol[c + 3];
  45693. }
  45694. else {
  45695. this._color.r = 1.0;
  45696. this._color.g = 1.0;
  45697. this._color.b = 1.0;
  45698. this._color.a = 1.0;
  45699. }
  45700. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  45701. c += 4;
  45702. if (!this.recomputeNormals && meshNor) {
  45703. this._normal.x = meshNor[n];
  45704. this._normal.y = meshNor[n + 1];
  45705. this._normal.z = meshNor[n + 2];
  45706. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  45707. normals.push(this._normal.x, this._normal.y, this._normal.z);
  45708. n += 3;
  45709. }
  45710. }
  45711. for (i = 0; i < meshInd.length; i++) {
  45712. var current_ind = p + meshInd[i];
  45713. indices.push(current_ind);
  45714. if (current_ind > 65535) {
  45715. this._needs32Bits = true;
  45716. }
  45717. }
  45718. if (this._pickable) {
  45719. var nbfaces = meshInd.length / 3;
  45720. for (i = 0; i < nbfaces; i++) {
  45721. this.pickedParticles.push({ idx: idx, faceId: i });
  45722. }
  45723. }
  45724. if (this._depthSort) {
  45725. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  45726. }
  45727. return this._copy;
  45728. };
  45729. // returns a shape array from positions array
  45730. SolidParticleSystem.prototype._posToShape = function (positions) {
  45731. var shape = [];
  45732. for (var i = 0; i < positions.length; i += 3) {
  45733. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  45734. }
  45735. return shape;
  45736. };
  45737. // returns a shapeUV array from a Vector4 uvs
  45738. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  45739. var shapeUV = [];
  45740. if (uvs) {
  45741. for (var i = 0; i < uvs.length; i++)
  45742. shapeUV.push(uvs[i]);
  45743. }
  45744. return shapeUV;
  45745. };
  45746. // adds a new particle object in the particles array
  45747. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  45748. if (bInfo === void 0) { bInfo = null; }
  45749. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  45750. this.particles.push(sp);
  45751. return sp;
  45752. };
  45753. /**
  45754. * Adds some particles to the SPS from the model shape. Returns the shape id.
  45755. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  45756. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  45757. * `nb` (positive integer) the number of particles to be created from this model
  45758. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  45759. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  45760. */
  45761. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  45762. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45763. var meshInd = mesh.getIndices();
  45764. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45765. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45766. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45767. var bbInfo;
  45768. if (this._particlesIntersect) {
  45769. bbInfo = mesh.getBoundingInfo();
  45770. }
  45771. var shape = this._posToShape(meshPos);
  45772. var shapeUV = this._uvsToShapeUV(meshUV);
  45773. var posfunc = options ? options.positionFunction : null;
  45774. var vtxfunc = options ? options.vertexFunction : null;
  45775. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  45776. // particles
  45777. var sp;
  45778. var currentCopy;
  45779. var idx = this.nbParticles;
  45780. for (var i = 0; i < nb; i++) {
  45781. var currentPos = this._positions.length;
  45782. var currentInd = this._indices.length;
  45783. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  45784. if (this._updatable) {
  45785. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  45786. sp.position.copyFrom(currentCopy.position);
  45787. sp.rotation.copyFrom(currentCopy.rotation);
  45788. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  45789. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  45790. }
  45791. if (currentCopy.color && sp.color) {
  45792. sp.color.copyFrom(currentCopy.color);
  45793. }
  45794. sp.scaling.copyFrom(currentCopy.scaling);
  45795. sp.uvs.copyFrom(currentCopy.uvs);
  45796. }
  45797. this._index += shape.length;
  45798. idx++;
  45799. }
  45800. this.nbParticles += nb;
  45801. this._shapeCounter++;
  45802. return this._shapeCounter - 1;
  45803. };
  45804. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  45805. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  45806. this._resetCopy();
  45807. if (particle._model._positionFunction) {
  45808. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  45809. }
  45810. if (this._copy.rotationQuaternion) {
  45811. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45812. }
  45813. else {
  45814. this._yaw = this._copy.rotation.y;
  45815. this._pitch = this._copy.rotation.x;
  45816. this._roll = this._copy.rotation.z;
  45817. this._quaternionRotationYPR();
  45818. }
  45819. this._quaternionToRotationMatrix();
  45820. this._shape = particle._model._shape;
  45821. for (var pt = 0; pt < this._shape.length; pt++) {
  45822. this._vertex.x = this._shape[pt].x;
  45823. this._vertex.y = this._shape[pt].y;
  45824. this._vertex.z = this._shape[pt].z;
  45825. if (particle._model._vertexFunction) {
  45826. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  45827. }
  45828. this._vertex.x *= this._copy.scaling.x;
  45829. this._vertex.y *= this._copy.scaling.y;
  45830. this._vertex.z *= this._copy.scaling.z;
  45831. this._vertex.x += this._copy.pivot.x;
  45832. this._vertex.y += this._copy.pivot.y;
  45833. this._vertex.z += this._copy.pivot.z;
  45834. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45835. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  45836. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  45837. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  45838. }
  45839. particle.position.x = 0.0;
  45840. particle.position.y = 0.0;
  45841. particle.position.z = 0.0;
  45842. particle.rotation.x = 0.0;
  45843. particle.rotation.y = 0.0;
  45844. particle.rotation.z = 0.0;
  45845. particle.rotationQuaternion = null;
  45846. particle.scaling.x = 1.0;
  45847. particle.scaling.y = 1.0;
  45848. particle.scaling.z = 1.0;
  45849. };
  45850. /**
  45851. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  45852. * Returns the SPS.
  45853. */
  45854. SolidParticleSystem.prototype.rebuildMesh = function () {
  45855. for (var p = 0; p < this.particles.length; p++) {
  45856. this._rebuildParticle(this.particles[p]);
  45857. }
  45858. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45859. return this;
  45860. };
  45861. /**
  45862. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  45863. * This method calls `updateParticle()` for each particle of the SPS.
  45864. * For an animated SPS, it is usually called within the render loop.
  45865. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  45866. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  45867. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  45868. * Returns the SPS.
  45869. */
  45870. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  45871. if (start === void 0) { start = 0; }
  45872. if (end === void 0) { end = this.nbParticles - 1; }
  45873. if (update === void 0) { update = true; }
  45874. if (!this._updatable) {
  45875. return this;
  45876. }
  45877. // custom beforeUpdate
  45878. this.beforeUpdateParticles(start, end, update);
  45879. this._cam_axisX.x = 1.0;
  45880. this._cam_axisX.y = 0.0;
  45881. this._cam_axisX.z = 0.0;
  45882. this._cam_axisY.x = 0.0;
  45883. this._cam_axisY.y = 1.0;
  45884. this._cam_axisY.z = 0.0;
  45885. this._cam_axisZ.x = 0.0;
  45886. this._cam_axisZ.y = 0.0;
  45887. this._cam_axisZ.z = 1.0;
  45888. // cases when the World Matrix is to be computed first
  45889. if (this.billboard || this._depthSort) {
  45890. this.mesh.computeWorldMatrix(true);
  45891. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  45892. }
  45893. // if the particles will always face the camera
  45894. if (this.billboard) {
  45895. // compute the camera position and un-rotate it by the current mesh rotation
  45896. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  45897. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  45898. this._cam_axisZ.normalize();
  45899. // same for camera up vector extracted from the cam view matrix
  45900. var view = this._camera.getViewMatrix(true);
  45901. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  45902. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  45903. this._cam_axisY.normalize();
  45904. this._cam_axisX.normalize();
  45905. }
  45906. // if depthSort, compute the camera global position in the mesh local system
  45907. if (this._depthSort) {
  45908. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  45909. }
  45910. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  45911. var idx = 0; // current position index in the global array positions32
  45912. var index = 0; // position start index in the global array positions32 of the current particle
  45913. var colidx = 0; // current color index in the global array colors32
  45914. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  45915. var uvidx = 0; // current uv index in the global array uvs32
  45916. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  45917. var pt = 0; // current index in the particle model shape
  45918. if (this.mesh.isFacetDataEnabled) {
  45919. this._computeBoundingBox = true;
  45920. }
  45921. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  45922. if (this._computeBoundingBox) {
  45923. if (start == 0 && end == this.nbParticles - 1) {
  45924. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  45925. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  45926. }
  45927. else {
  45928. if (this.mesh._boundingInfo) {
  45929. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  45930. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  45931. }
  45932. }
  45933. }
  45934. // particle loop
  45935. index = this.particles[start]._pos;
  45936. var vpos = (index / 3) | 0;
  45937. colorIndex = vpos * 4;
  45938. uvIndex = vpos * 2;
  45939. for (var p = start; p <= end; p++) {
  45940. this._particle = this.particles[p];
  45941. this._shape = this._particle._model._shape;
  45942. this._shapeUV = this._particle._model._shapeUV;
  45943. // call to custom user function to update the particle properties
  45944. this.updateParticle(this._particle);
  45945. // camera-particle distance for depth sorting
  45946. if (this._depthSort && this._depthSortParticles) {
  45947. var dsp = this.depthSortedParticles[p];
  45948. dsp.ind = this._particle._ind;
  45949. dsp.indicesLength = this._particle._model._indicesLength;
  45950. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  45951. }
  45952. // skip the computations for inactive or already invisible particles
  45953. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  45954. // increment indexes for the next particle
  45955. pt = this._shape.length;
  45956. index += pt * 3;
  45957. colorIndex += pt * 4;
  45958. uvIndex += pt * 2;
  45959. continue;
  45960. }
  45961. if (this._particle.isVisible) {
  45962. this._particle._stillInvisible = false; // un-mark permanent invisibility
  45963. // particle rotation matrix
  45964. if (this.billboard) {
  45965. this._particle.rotation.x = 0.0;
  45966. this._particle.rotation.y = 0.0;
  45967. }
  45968. if (this._computeParticleRotation || this.billboard) {
  45969. if (this._particle.rotationQuaternion) {
  45970. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45971. }
  45972. else {
  45973. this._yaw = this._particle.rotation.y;
  45974. this._pitch = this._particle.rotation.x;
  45975. this._roll = this._particle.rotation.z;
  45976. this._quaternionRotationYPR();
  45977. }
  45978. this._quaternionToRotationMatrix();
  45979. }
  45980. // particle vertex loop
  45981. for (pt = 0; pt < this._shape.length; pt++) {
  45982. idx = index + pt * 3;
  45983. colidx = colorIndex + pt * 4;
  45984. uvidx = uvIndex + pt * 2;
  45985. this._vertex.x = this._shape[pt].x;
  45986. this._vertex.y = this._shape[pt].y;
  45987. this._vertex.z = this._shape[pt].z;
  45988. if (this._computeParticleVertex) {
  45989. this.updateParticleVertex(this._particle, this._vertex, pt);
  45990. }
  45991. // positions
  45992. this._vertex.x *= this._particle.scaling.x;
  45993. this._vertex.y *= this._particle.scaling.y;
  45994. this._vertex.z *= this._particle.scaling.z;
  45995. this._vertex.x += this._particle.pivot.x;
  45996. this._vertex.y += this._particle.pivot.y;
  45997. this._vertex.z += this._particle.pivot.z;
  45998. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45999. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46000. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46001. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  46002. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  46003. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  46004. if (this._computeBoundingBox) {
  46005. if (this._positions32[idx] < this._minimum.x) {
  46006. this._minimum.x = this._positions32[idx];
  46007. }
  46008. if (this._positions32[idx] > this._maximum.x) {
  46009. this._maximum.x = this._positions32[idx];
  46010. }
  46011. if (this._positions32[idx + 1] < this._minimum.y) {
  46012. this._minimum.y = this._positions32[idx + 1];
  46013. }
  46014. if (this._positions32[idx + 1] > this._maximum.y) {
  46015. this._maximum.y = this._positions32[idx + 1];
  46016. }
  46017. if (this._positions32[idx + 2] < this._minimum.z) {
  46018. this._minimum.z = this._positions32[idx + 2];
  46019. }
  46020. if (this._positions32[idx + 2] > this._maximum.z) {
  46021. this._maximum.z = this._positions32[idx + 2];
  46022. }
  46023. }
  46024. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  46025. if (!this._computeParticleVertex) {
  46026. this._normal.x = this._fixedNormal32[idx];
  46027. this._normal.y = this._fixedNormal32[idx + 1];
  46028. this._normal.z = this._fixedNormal32[idx + 2];
  46029. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  46030. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  46031. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  46032. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  46033. 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;
  46034. 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;
  46035. }
  46036. if (this._computeParticleColor && this._particle.color) {
  46037. this._colors32[colidx] = this._particle.color.r;
  46038. this._colors32[colidx + 1] = this._particle.color.g;
  46039. this._colors32[colidx + 2] = this._particle.color.b;
  46040. this._colors32[colidx + 3] = this._particle.color.a;
  46041. }
  46042. if (this._computeParticleTexture) {
  46043. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46044. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46045. }
  46046. }
  46047. }
  46048. else {
  46049. this._particle._stillInvisible = true; // mark the particle as invisible
  46050. for (pt = 0; pt < this._shape.length; pt++) {
  46051. idx = index + pt * 3;
  46052. colidx = colorIndex + pt * 4;
  46053. uvidx = uvIndex + pt * 2;
  46054. this._positions32[idx] = 0.0;
  46055. this._positions32[idx + 1] = 0.0;
  46056. this._positions32[idx + 2] = 0.0;
  46057. this._normals32[idx] = 0.0;
  46058. this._normals32[idx + 1] = 0.0;
  46059. this._normals32[idx + 2] = 0.0;
  46060. if (this._computeParticleColor && this._particle.color) {
  46061. this._colors32[colidx] = this._particle.color.r;
  46062. this._colors32[colidx + 1] = this._particle.color.g;
  46063. this._colors32[colidx + 2] = this._particle.color.b;
  46064. this._colors32[colidx + 3] = this._particle.color.a;
  46065. }
  46066. if (this._computeParticleTexture) {
  46067. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46068. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46069. }
  46070. }
  46071. }
  46072. // if the particle intersections must be computed : update the bbInfo
  46073. if (this._particlesIntersect) {
  46074. var bInfo = this._particle._boundingInfo;
  46075. var bBox = bInfo.boundingBox;
  46076. var bSphere = bInfo.boundingSphere;
  46077. if (!this._bSphereOnly) {
  46078. // place, scale and rotate the particle bbox within the SPS local system, then update it
  46079. for (var b = 0; b < bBox.vectors.length; b++) {
  46080. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  46081. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  46082. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  46083. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  46084. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46085. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46086. 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;
  46087. 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;
  46088. 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;
  46089. }
  46090. bBox._update(this.mesh._worldMatrix);
  46091. }
  46092. // place and scale the particle bouding sphere in the SPS local system, then update it
  46093. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  46094. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  46095. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  46096. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  46097. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  46098. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  46099. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  46100. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  46101. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  46102. 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));
  46103. bSphere._update(this.mesh._worldMatrix);
  46104. }
  46105. // increment indexes for the next particle
  46106. index = idx + 3;
  46107. colorIndex = colidx + 4;
  46108. uvIndex = uvidx + 2;
  46109. }
  46110. // if the VBO must be updated
  46111. if (update) {
  46112. if (this._computeParticleColor) {
  46113. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  46114. }
  46115. if (this._computeParticleTexture) {
  46116. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  46117. }
  46118. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  46119. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  46120. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  46121. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  46122. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  46123. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  46124. for (var i = 0; i < this._normals32.length; i++) {
  46125. this._fixedNormal32[i] = this._normals32[i];
  46126. }
  46127. }
  46128. if (!this.mesh.areNormalsFrozen) {
  46129. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  46130. }
  46131. }
  46132. if (this._depthSort && this._depthSortParticles) {
  46133. this.depthSortedParticles.sort(this._depthSortFunction);
  46134. var dspl = this.depthSortedParticles.length;
  46135. var sorted = 0;
  46136. var lind = 0;
  46137. var sind = 0;
  46138. var sid = 0;
  46139. for (sorted = 0; sorted < dspl; sorted++) {
  46140. lind = this.depthSortedParticles[sorted].indicesLength;
  46141. sind = this.depthSortedParticles[sorted].ind;
  46142. for (var i = 0; i < lind; i++) {
  46143. this._indices32[sid] = this._indices[sind + i];
  46144. sid++;
  46145. }
  46146. }
  46147. this.mesh.updateIndices(this._indices32);
  46148. }
  46149. }
  46150. if (this._computeBoundingBox) {
  46151. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  46152. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  46153. }
  46154. this.afterUpdateParticles(start, end, update);
  46155. return this;
  46156. };
  46157. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  46158. this._halfroll = this._roll * 0.5;
  46159. this._halfpitch = this._pitch * 0.5;
  46160. this._halfyaw = this._yaw * 0.5;
  46161. this._sinRoll = Math.sin(this._halfroll);
  46162. this._cosRoll = Math.cos(this._halfroll);
  46163. this._sinPitch = Math.sin(this._halfpitch);
  46164. this._cosPitch = Math.cos(this._halfpitch);
  46165. this._sinYaw = Math.sin(this._halfyaw);
  46166. this._cosYaw = Math.cos(this._halfyaw);
  46167. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  46168. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  46169. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  46170. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  46171. };
  46172. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  46173. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  46174. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  46175. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  46176. this._rotMatrix.m[3] = 0;
  46177. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  46178. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  46179. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  46180. this._rotMatrix.m[7] = 0;
  46181. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  46182. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  46183. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  46184. this._rotMatrix.m[11] = 0;
  46185. this._rotMatrix.m[12] = 0;
  46186. this._rotMatrix.m[13] = 0;
  46187. this._rotMatrix.m[14] = 0;
  46188. this._rotMatrix.m[15] = 1.0;
  46189. };
  46190. /**
  46191. * Disposes the SPS.
  46192. * Returns nothing.
  46193. */
  46194. SolidParticleSystem.prototype.dispose = function () {
  46195. this.mesh.dispose();
  46196. this.vars = null;
  46197. // drop references to internal big arrays for the GC
  46198. this._positions = null;
  46199. this._indices = null;
  46200. this._normals = null;
  46201. this._uvs = null;
  46202. this._colors = null;
  46203. this._indices32 = null;
  46204. this._positions32 = null;
  46205. this._normals32 = null;
  46206. this._fixedNormal32 = null;
  46207. this._uvs32 = null;
  46208. this._colors32 = null;
  46209. this.pickedParticles = null;
  46210. };
  46211. /**
  46212. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  46213. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46214. * Returns the SPS.
  46215. */
  46216. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  46217. if (!this._isVisibilityBoxLocked) {
  46218. this.mesh.refreshBoundingInfo();
  46219. }
  46220. return this;
  46221. };
  46222. /**
  46223. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  46224. * @param size the size (float) of the visibility box
  46225. * note : this doesn't lock the SPS mesh bounding box.
  46226. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46227. */
  46228. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  46229. var vis = size / 2;
  46230. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  46231. };
  46232. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  46233. // getter and setter
  46234. get: function () {
  46235. return this._alwaysVisible;
  46236. },
  46237. /**
  46238. * Sets the SPS as always visible or not
  46239. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46240. */
  46241. set: function (val) {
  46242. this._alwaysVisible = val;
  46243. this.mesh.alwaysSelectAsActiveMesh = val;
  46244. },
  46245. enumerable: true,
  46246. configurable: true
  46247. });
  46248. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  46249. get: function () {
  46250. return this._isVisibilityBoxLocked;
  46251. },
  46252. /**
  46253. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  46254. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46255. */
  46256. set: function (val) {
  46257. this._isVisibilityBoxLocked = val;
  46258. var boundingInfo = this.mesh.getBoundingInfo();
  46259. boundingInfo.isLocked = val;
  46260. },
  46261. enumerable: true,
  46262. configurable: true
  46263. });
  46264. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  46265. // getters
  46266. get: function () {
  46267. return this._computeParticleRotation;
  46268. },
  46269. // Optimizer setters
  46270. /**
  46271. * Tells to `setParticles()` to compute the particle rotations or not.
  46272. * Default value : true. The SPS is faster when it's set to false.
  46273. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  46274. */
  46275. set: function (val) {
  46276. this._computeParticleRotation = val;
  46277. },
  46278. enumerable: true,
  46279. configurable: true
  46280. });
  46281. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  46282. get: function () {
  46283. return this._computeParticleColor;
  46284. },
  46285. /**
  46286. * Tells to `setParticles()` to compute the particle colors or not.
  46287. * Default value : true. The SPS is faster when it's set to false.
  46288. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  46289. */
  46290. set: function (val) {
  46291. this._computeParticleColor = val;
  46292. },
  46293. enumerable: true,
  46294. configurable: true
  46295. });
  46296. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  46297. get: function () {
  46298. return this._computeParticleTexture;
  46299. },
  46300. /**
  46301. * Tells to `setParticles()` to compute the particle textures or not.
  46302. * Default value : true. The SPS is faster when it's set to false.
  46303. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  46304. */
  46305. set: function (val) {
  46306. this._computeParticleTexture = val;
  46307. },
  46308. enumerable: true,
  46309. configurable: true
  46310. });
  46311. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  46312. get: function () {
  46313. return this._computeParticleVertex;
  46314. },
  46315. /**
  46316. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  46317. * Default value : false. The SPS is faster when it's set to false.
  46318. * Note : the particle custom vertex positions aren't stored values.
  46319. */
  46320. set: function (val) {
  46321. this._computeParticleVertex = val;
  46322. },
  46323. enumerable: true,
  46324. configurable: true
  46325. });
  46326. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  46327. get: function () {
  46328. return this._computeBoundingBox;
  46329. },
  46330. /**
  46331. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  46332. */
  46333. set: function (val) {
  46334. this._computeBoundingBox = val;
  46335. },
  46336. enumerable: true,
  46337. configurable: true
  46338. });
  46339. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  46340. get: function () {
  46341. return this._depthSortParticles;
  46342. },
  46343. /**
  46344. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  46345. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  46346. * Default : `true`
  46347. */
  46348. set: function (val) {
  46349. this._depthSortParticles = val;
  46350. },
  46351. enumerable: true,
  46352. configurable: true
  46353. });
  46354. // =======================================================================
  46355. // Particle behavior logic
  46356. // these following methods may be overwritten by the user to fit his needs
  46357. /**
  46358. * This function does nothing. It may be overwritten to set all the particle first values.
  46359. * The SPS doesn't call this function, you may have to call it by your own.
  46360. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46361. */
  46362. SolidParticleSystem.prototype.initParticles = function () {
  46363. };
  46364. /**
  46365. * This function does nothing. It may be overwritten to recycle a particle.
  46366. * The SPS doesn't call this function, you may have to call it by your own.
  46367. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46368. */
  46369. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  46370. return particle;
  46371. };
  46372. /**
  46373. * Updates a particle : this function should be overwritten by the user.
  46374. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  46375. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46376. * ex : just set a particle position or velocity and recycle conditions
  46377. */
  46378. SolidParticleSystem.prototype.updateParticle = function (particle) {
  46379. return particle;
  46380. };
  46381. /**
  46382. * Updates a vertex of a particle : it can be overwritten by the user.
  46383. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  46384. * @param particle the current particle
  46385. * @param vertex the current index of the current particle
  46386. * @param pt the index of the current vertex in the particle shape
  46387. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  46388. * ex : just set a vertex particle position
  46389. */
  46390. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  46391. return vertex;
  46392. };
  46393. /**
  46394. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  46395. * This does nothing and may be overwritten by the user.
  46396. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46397. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46398. * @param update the boolean update value actually passed to setParticles()
  46399. */
  46400. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  46401. };
  46402. /**
  46403. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  46404. * This will be passed three parameters.
  46405. * This does nothing and may be overwritten by the user.
  46406. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46407. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46408. * @param update the boolean update value actually passed to setParticles()
  46409. */
  46410. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  46411. };
  46412. return SolidParticleSystem;
  46413. }());
  46414. BABYLON.SolidParticleSystem = SolidParticleSystem;
  46415. })(BABYLON || (BABYLON = {}));
  46416. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  46417. var BABYLON;
  46418. (function (BABYLON) {
  46419. var GroundMesh = /** @class */ (function (_super) {
  46420. __extends(GroundMesh, _super);
  46421. function GroundMesh(name, scene) {
  46422. var _this = _super.call(this, name, scene) || this;
  46423. _this.generateOctree = false;
  46424. return _this;
  46425. }
  46426. GroundMesh.prototype.getClassName = function () {
  46427. return "GroundMesh";
  46428. };
  46429. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  46430. get: function () {
  46431. return Math.min(this._subdivisionsX, this._subdivisionsY);
  46432. },
  46433. enumerable: true,
  46434. configurable: true
  46435. });
  46436. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  46437. get: function () {
  46438. return this._subdivisionsX;
  46439. },
  46440. enumerable: true,
  46441. configurable: true
  46442. });
  46443. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  46444. get: function () {
  46445. return this._subdivisionsY;
  46446. },
  46447. enumerable: true,
  46448. configurable: true
  46449. });
  46450. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  46451. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  46452. this._subdivisionsX = chunksCount;
  46453. this._subdivisionsY = chunksCount;
  46454. this.subdivide(chunksCount);
  46455. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  46456. };
  46457. /**
  46458. * Returns a height (y) value in the Worl system :
  46459. * the ground altitude at the coordinates (x, z) expressed in the World system.
  46460. * Returns the ground y position if (x, z) are outside the ground surface.
  46461. */
  46462. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  46463. var world = this.getWorldMatrix();
  46464. var invMat = BABYLON.Tmp.Matrix[5];
  46465. world.invertToRef(invMat);
  46466. var tmpVect = BABYLON.Tmp.Vector3[8];
  46467. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  46468. x = tmpVect.x;
  46469. z = tmpVect.z;
  46470. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  46471. return this.position.y;
  46472. }
  46473. if (!this._heightQuads || this._heightQuads.length == 0) {
  46474. this._initHeightQuads();
  46475. this._computeHeightQuads();
  46476. }
  46477. var facet = this._getFacetAt(x, z);
  46478. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  46479. // return y in the World system
  46480. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  46481. return tmpVect.y;
  46482. };
  46483. /**
  46484. * Returns a normalized vector (Vector3) orthogonal to the ground
  46485. * at the ground coordinates (x, z) expressed in the World system.
  46486. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  46487. */
  46488. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  46489. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  46490. this.getNormalAtCoordinatesToRef(x, z, normal);
  46491. return normal;
  46492. };
  46493. /**
  46494. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  46495. * at the ground coordinates (x, z) expressed in the World system.
  46496. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  46497. * Returns the GroundMesh.
  46498. */
  46499. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  46500. var world = this.getWorldMatrix();
  46501. var tmpMat = BABYLON.Tmp.Matrix[5];
  46502. world.invertToRef(tmpMat);
  46503. var tmpVect = BABYLON.Tmp.Vector3[8];
  46504. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  46505. x = tmpVect.x;
  46506. z = tmpVect.z;
  46507. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  46508. return this;
  46509. }
  46510. if (!this._heightQuads || this._heightQuads.length == 0) {
  46511. this._initHeightQuads();
  46512. this._computeHeightQuads();
  46513. }
  46514. var facet = this._getFacetAt(x, z);
  46515. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  46516. return this;
  46517. };
  46518. /**
  46519. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  46520. * if the ground has been updated.
  46521. * This can be used in the render loop.
  46522. * Returns the GroundMesh.
  46523. */
  46524. GroundMesh.prototype.updateCoordinateHeights = function () {
  46525. if (!this._heightQuads || this._heightQuads.length == 0) {
  46526. this._initHeightQuads();
  46527. }
  46528. this._computeHeightQuads();
  46529. return this;
  46530. };
  46531. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  46532. GroundMesh.prototype._getFacetAt = function (x, z) {
  46533. // retrieve col and row from x, z coordinates in the ground local system
  46534. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  46535. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  46536. var quad = this._heightQuads[row * this._subdivisionsX + col];
  46537. var facet;
  46538. if (z < quad.slope.x * x + quad.slope.y) {
  46539. facet = quad.facet1;
  46540. }
  46541. else {
  46542. facet = quad.facet2;
  46543. }
  46544. return facet;
  46545. };
  46546. // Creates and populates the heightMap array with "facet" elements :
  46547. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  46548. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  46549. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  46550. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  46551. // Returns the GroundMesh.
  46552. GroundMesh.prototype._initHeightQuads = function () {
  46553. var subdivisionsX = this._subdivisionsX;
  46554. var subdivisionsY = this._subdivisionsY;
  46555. this._heightQuads = new Array();
  46556. for (var row = 0; row < subdivisionsY; row++) {
  46557. for (var col = 0; col < subdivisionsX; col++) {
  46558. 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) };
  46559. this._heightQuads[row * subdivisionsX + col] = quad;
  46560. }
  46561. }
  46562. return this;
  46563. };
  46564. // Compute each quad element values and update the the heightMap array :
  46565. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  46566. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  46567. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  46568. // Returns the GroundMesh.
  46569. GroundMesh.prototype._computeHeightQuads = function () {
  46570. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46571. if (!positions) {
  46572. return this;
  46573. }
  46574. var v1 = BABYLON.Tmp.Vector3[3];
  46575. var v2 = BABYLON.Tmp.Vector3[2];
  46576. var v3 = BABYLON.Tmp.Vector3[1];
  46577. var v4 = BABYLON.Tmp.Vector3[0];
  46578. var v1v2 = BABYLON.Tmp.Vector3[4];
  46579. var v1v3 = BABYLON.Tmp.Vector3[5];
  46580. var v1v4 = BABYLON.Tmp.Vector3[6];
  46581. var norm1 = BABYLON.Tmp.Vector3[7];
  46582. var norm2 = BABYLON.Tmp.Vector3[8];
  46583. var i = 0;
  46584. var j = 0;
  46585. var k = 0;
  46586. var cd = 0; // 2D slope coefficient : z = cd * x + h
  46587. var h = 0;
  46588. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  46589. var d2 = 0;
  46590. var subdivisionsX = this._subdivisionsX;
  46591. var subdivisionsY = this._subdivisionsY;
  46592. for (var row = 0; row < subdivisionsY; row++) {
  46593. for (var col = 0; col < subdivisionsX; col++) {
  46594. i = col * 3;
  46595. j = row * (subdivisionsX + 1) * 3;
  46596. k = (row + 1) * (subdivisionsX + 1) * 3;
  46597. v1.x = positions[j + i];
  46598. v1.y = positions[j + i + 1];
  46599. v1.z = positions[j + i + 2];
  46600. v2.x = positions[j + i + 3];
  46601. v2.y = positions[j + i + 4];
  46602. v2.z = positions[j + i + 5];
  46603. v3.x = positions[k + i];
  46604. v3.y = positions[k + i + 1];
  46605. v3.z = positions[k + i + 2];
  46606. v4.x = positions[k + i + 3];
  46607. v4.y = positions[k + i + 4];
  46608. v4.z = positions[k + i + 5];
  46609. // 2D slope V1V4
  46610. cd = (v4.z - v1.z) / (v4.x - v1.x);
  46611. h = v1.z - cd * v1.x; // v1 belongs to the slope
  46612. // facet equations :
  46613. // we compute each facet normal vector
  46614. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  46615. // we compute the value d by applying the equation to v1 which belongs to the plane
  46616. // then we store the facet equation in a Vector4
  46617. v2.subtractToRef(v1, v1v2);
  46618. v3.subtractToRef(v1, v1v3);
  46619. v4.subtractToRef(v1, v1v4);
  46620. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  46621. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  46622. norm1.normalize();
  46623. norm2.normalize();
  46624. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  46625. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  46626. var quad = this._heightQuads[row * subdivisionsX + col];
  46627. quad.slope.copyFromFloats(cd, h);
  46628. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  46629. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  46630. }
  46631. }
  46632. return this;
  46633. };
  46634. GroundMesh.prototype.serialize = function (serializationObject) {
  46635. _super.prototype.serialize.call(this, serializationObject);
  46636. serializationObject.subdivisionsX = this._subdivisionsX;
  46637. serializationObject.subdivisionsY = this._subdivisionsY;
  46638. serializationObject.minX = this._minX;
  46639. serializationObject.maxX = this._maxX;
  46640. serializationObject.minZ = this._minZ;
  46641. serializationObject.maxZ = this._maxZ;
  46642. serializationObject.width = this._width;
  46643. serializationObject.height = this._height;
  46644. };
  46645. GroundMesh.Parse = function (parsedMesh, scene) {
  46646. var result = new GroundMesh(parsedMesh.name, scene);
  46647. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  46648. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  46649. result._minX = parsedMesh.minX;
  46650. result._maxX = parsedMesh.maxX;
  46651. result._minZ = parsedMesh.minZ;
  46652. result._maxZ = parsedMesh.maxZ;
  46653. result._width = parsedMesh.width;
  46654. result._height = parsedMesh.height;
  46655. return result;
  46656. };
  46657. return GroundMesh;
  46658. }(BABYLON.Mesh));
  46659. BABYLON.GroundMesh = GroundMesh;
  46660. })(BABYLON || (BABYLON = {}));
  46661. //# sourceMappingURL=babylon.groundMesh.js.map
  46662. var BABYLON;
  46663. (function (BABYLON) {
  46664. /**
  46665. * Creates an instance based on a source mesh.
  46666. */
  46667. var InstancedMesh = /** @class */ (function (_super) {
  46668. __extends(InstancedMesh, _super);
  46669. function InstancedMesh(name, source) {
  46670. var _this = _super.call(this, name, source.getScene()) || this;
  46671. source.instances.push(_this);
  46672. _this._sourceMesh = source;
  46673. _this.position.copyFrom(source.position);
  46674. _this.rotation.copyFrom(source.rotation);
  46675. _this.scaling.copyFrom(source.scaling);
  46676. if (source.rotationQuaternion) {
  46677. _this.rotationQuaternion = source.rotationQuaternion.clone();
  46678. }
  46679. _this.infiniteDistance = source.infiniteDistance;
  46680. _this.setPivotMatrix(source.getPivotMatrix());
  46681. _this.refreshBoundingInfo();
  46682. _this._syncSubMeshes();
  46683. return _this;
  46684. }
  46685. /**
  46686. * Returns the string "InstancedMesh".
  46687. */
  46688. InstancedMesh.prototype.getClassName = function () {
  46689. return "InstancedMesh";
  46690. };
  46691. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  46692. // Methods
  46693. get: function () {
  46694. return this._sourceMesh.receiveShadows;
  46695. },
  46696. enumerable: true,
  46697. configurable: true
  46698. });
  46699. Object.defineProperty(InstancedMesh.prototype, "material", {
  46700. get: function () {
  46701. return this._sourceMesh.material;
  46702. },
  46703. enumerable: true,
  46704. configurable: true
  46705. });
  46706. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  46707. get: function () {
  46708. return this._sourceMesh.visibility;
  46709. },
  46710. enumerable: true,
  46711. configurable: true
  46712. });
  46713. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  46714. get: function () {
  46715. return this._sourceMesh.skeleton;
  46716. },
  46717. enumerable: true,
  46718. configurable: true
  46719. });
  46720. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  46721. get: function () {
  46722. return this._sourceMesh.renderingGroupId;
  46723. },
  46724. enumerable: true,
  46725. configurable: true
  46726. });
  46727. /**
  46728. * Returns the total number of vertices (integer).
  46729. */
  46730. InstancedMesh.prototype.getTotalVertices = function () {
  46731. return this._sourceMesh.getTotalVertices();
  46732. };
  46733. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  46734. get: function () {
  46735. return this._sourceMesh;
  46736. },
  46737. enumerable: true,
  46738. configurable: true
  46739. });
  46740. /**
  46741. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  46742. */
  46743. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  46744. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  46745. };
  46746. /**
  46747. * Sets the vertex data of the mesh geometry for the requested `kind`.
  46748. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  46749. * The `data` are either a numeric array either a Float32Array.
  46750. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  46751. * 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).
  46752. * Note that a new underlying VertexBuffer object is created each call.
  46753. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  46754. *
  46755. * Possible `kind` values :
  46756. * - BABYLON.VertexBuffer.PositionKind
  46757. * - BABYLON.VertexBuffer.UVKind
  46758. * - BABYLON.VertexBuffer.UV2Kind
  46759. * - BABYLON.VertexBuffer.UV3Kind
  46760. * - BABYLON.VertexBuffer.UV4Kind
  46761. * - BABYLON.VertexBuffer.UV5Kind
  46762. * - BABYLON.VertexBuffer.UV6Kind
  46763. * - BABYLON.VertexBuffer.ColorKind
  46764. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46765. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46766. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46767. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46768. *
  46769. * Returns the Mesh.
  46770. */
  46771. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  46772. if (this.sourceMesh) {
  46773. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  46774. }
  46775. return this.sourceMesh;
  46776. };
  46777. /**
  46778. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  46779. * If the mesh has no geometry, it is simply returned as it is.
  46780. * The `data` are either a numeric array either a Float32Array.
  46781. * No new underlying VertexBuffer object is created.
  46782. * 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.
  46783. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  46784. *
  46785. * Possible `kind` values :
  46786. * - BABYLON.VertexBuffer.PositionKind
  46787. * - BABYLON.VertexBuffer.UVKind
  46788. * - BABYLON.VertexBuffer.UV2Kind
  46789. * - BABYLON.VertexBuffer.UV3Kind
  46790. * - BABYLON.VertexBuffer.UV4Kind
  46791. * - BABYLON.VertexBuffer.UV5Kind
  46792. * - BABYLON.VertexBuffer.UV6Kind
  46793. * - BABYLON.VertexBuffer.ColorKind
  46794. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46795. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46796. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46797. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46798. *
  46799. * Returns the Mesh.
  46800. */
  46801. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  46802. if (this.sourceMesh) {
  46803. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  46804. }
  46805. return this.sourceMesh;
  46806. };
  46807. /**
  46808. * Sets the mesh indices.
  46809. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  46810. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  46811. * This method creates a new index buffer each call.
  46812. * Returns the Mesh.
  46813. */
  46814. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  46815. if (totalVertices === void 0) { totalVertices = null; }
  46816. if (this.sourceMesh) {
  46817. this.sourceMesh.setIndices(indices, totalVertices);
  46818. }
  46819. return this.sourceMesh;
  46820. };
  46821. /**
  46822. * Boolean : True if the mesh owns the requested kind of data.
  46823. */
  46824. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  46825. return this._sourceMesh.isVerticesDataPresent(kind);
  46826. };
  46827. /**
  46828. * Returns an array of indices (IndicesArray).
  46829. */
  46830. InstancedMesh.prototype.getIndices = function () {
  46831. return this._sourceMesh.getIndices();
  46832. };
  46833. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  46834. get: function () {
  46835. return this._sourceMesh._positions;
  46836. },
  46837. enumerable: true,
  46838. configurable: true
  46839. });
  46840. /**
  46841. * Sets a new updated BoundingInfo to the mesh.
  46842. * Returns the mesh.
  46843. */
  46844. InstancedMesh.prototype.refreshBoundingInfo = function () {
  46845. var meshBB = this._sourceMesh.getBoundingInfo();
  46846. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  46847. this._updateBoundingInfo();
  46848. return this;
  46849. };
  46850. InstancedMesh.prototype._preActivate = function () {
  46851. if (this._currentLOD) {
  46852. this._currentLOD._preActivate();
  46853. }
  46854. return this;
  46855. };
  46856. InstancedMesh.prototype._activate = function (renderId) {
  46857. if (this._currentLOD) {
  46858. this._currentLOD._registerInstanceForRenderId(this, renderId);
  46859. }
  46860. return this;
  46861. };
  46862. /**
  46863. * Returns the current associated LOD AbstractMesh.
  46864. */
  46865. InstancedMesh.prototype.getLOD = function (camera) {
  46866. if (!camera) {
  46867. return this;
  46868. }
  46869. var boundingInfo = this.getBoundingInfo();
  46870. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  46871. if (this._currentLOD === this.sourceMesh) {
  46872. return this;
  46873. }
  46874. return this._currentLOD;
  46875. };
  46876. InstancedMesh.prototype._syncSubMeshes = function () {
  46877. this.releaseSubMeshes();
  46878. if (this._sourceMesh.subMeshes) {
  46879. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  46880. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  46881. }
  46882. }
  46883. return this;
  46884. };
  46885. InstancedMesh.prototype._generatePointsArray = function () {
  46886. return this._sourceMesh._generatePointsArray();
  46887. };
  46888. /**
  46889. * Creates a new InstancedMesh from the current mesh.
  46890. * - name (string) : the cloned mesh name
  46891. * - newParent (optional Node) : the optional Node to parent the clone to.
  46892. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  46893. *
  46894. * Returns the clone.
  46895. */
  46896. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46897. var result = this._sourceMesh.createInstance(name);
  46898. // Deep copy
  46899. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  46900. // Bounding info
  46901. this.refreshBoundingInfo();
  46902. // Parent
  46903. if (newParent) {
  46904. result.parent = newParent;
  46905. }
  46906. if (!doNotCloneChildren) {
  46907. // Children
  46908. for (var index = 0; index < this.getScene().meshes.length; index++) {
  46909. var mesh = this.getScene().meshes[index];
  46910. if (mesh.parent === this) {
  46911. mesh.clone(mesh.name, result);
  46912. }
  46913. }
  46914. }
  46915. result.computeWorldMatrix(true);
  46916. return result;
  46917. };
  46918. /**
  46919. * Disposes the InstancedMesh.
  46920. * Returns nothing.
  46921. */
  46922. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  46923. // Remove from mesh
  46924. var index = this._sourceMesh.instances.indexOf(this);
  46925. this._sourceMesh.instances.splice(index, 1);
  46926. _super.prototype.dispose.call(this, doNotRecurse);
  46927. };
  46928. return InstancedMesh;
  46929. }(BABYLON.AbstractMesh));
  46930. BABYLON.InstancedMesh = InstancedMesh;
  46931. })(BABYLON || (BABYLON = {}));
  46932. //# sourceMappingURL=babylon.instancedMesh.js.map
  46933. var BABYLON;
  46934. (function (BABYLON) {
  46935. var LinesMesh = /** @class */ (function (_super) {
  46936. __extends(LinesMesh, _super);
  46937. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  46938. if (scene === void 0) { scene = null; }
  46939. if (parent === void 0) { parent = null; }
  46940. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  46941. _this.useVertexColor = useVertexColor;
  46942. _this.useVertexAlpha = useVertexAlpha;
  46943. _this.color = new BABYLON.Color3(1, 1, 1);
  46944. _this.alpha = 1;
  46945. if (source) {
  46946. _this.color = source.color.clone();
  46947. _this.alpha = source.alpha;
  46948. _this.useVertexColor = source.useVertexColor;
  46949. _this.useVertexAlpha = source.useVertexAlpha;
  46950. }
  46951. _this._intersectionThreshold = 0.1;
  46952. var defines = [];
  46953. var options = {
  46954. attributes: [BABYLON.VertexBuffer.PositionKind],
  46955. uniforms: ["world", "viewProjection"],
  46956. needAlphaBlending: false,
  46957. defines: defines
  46958. };
  46959. if (!useVertexColor) {
  46960. options.uniforms.push("color");
  46961. }
  46962. else {
  46963. options.needAlphaBlending = (useVertexAlpha) ? true : false;
  46964. options.defines.push("#define VERTEXCOLOR");
  46965. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  46966. }
  46967. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  46968. return _this;
  46969. }
  46970. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  46971. /**
  46972. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46973. * This margin is expressed in world space coordinates, so its value may vary.
  46974. * Default value is 0.1
  46975. * @returns the intersection Threshold value.
  46976. */
  46977. get: function () {
  46978. return this._intersectionThreshold;
  46979. },
  46980. /**
  46981. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46982. * This margin is expressed in world space coordinates, so its value may vary.
  46983. * @param value the new threshold to apply
  46984. */
  46985. set: function (value) {
  46986. if (this._intersectionThreshold === value) {
  46987. return;
  46988. }
  46989. this._intersectionThreshold = value;
  46990. if (this.geometry) {
  46991. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  46992. }
  46993. },
  46994. enumerable: true,
  46995. configurable: true
  46996. });
  46997. /**
  46998. * Returns the string "LineMesh"
  46999. */
  47000. LinesMesh.prototype.getClassName = function () {
  47001. return "LinesMesh";
  47002. };
  47003. Object.defineProperty(LinesMesh.prototype, "material", {
  47004. get: function () {
  47005. return this._colorShader;
  47006. },
  47007. set: function (value) {
  47008. // Do nothing
  47009. },
  47010. enumerable: true,
  47011. configurable: true
  47012. });
  47013. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  47014. get: function () {
  47015. return false;
  47016. },
  47017. enumerable: true,
  47018. configurable: true
  47019. });
  47020. LinesMesh.prototype.createInstance = function (name) {
  47021. throw new Error("LinesMeshes do not support createInstance.");
  47022. };
  47023. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  47024. if (!this._geometry) {
  47025. return this;
  47026. }
  47027. // VBOs
  47028. this._geometry._bind(this._colorShader.getEffect());
  47029. // Color
  47030. if (!this.useVertexColor) {
  47031. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  47032. }
  47033. return this;
  47034. };
  47035. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  47036. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  47037. return this;
  47038. }
  47039. var engine = this.getScene().getEngine();
  47040. // Draw order
  47041. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  47042. return this;
  47043. };
  47044. LinesMesh.prototype.dispose = function (doNotRecurse) {
  47045. this._colorShader.dispose();
  47046. _super.prototype.dispose.call(this, doNotRecurse);
  47047. };
  47048. /**
  47049. * Returns a new LineMesh object cloned from the current one.
  47050. */
  47051. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  47052. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  47053. };
  47054. return LinesMesh;
  47055. }(BABYLON.Mesh));
  47056. BABYLON.LinesMesh = LinesMesh;
  47057. })(BABYLON || (BABYLON = {}));
  47058. //# sourceMappingURL=babylon.linesMesh.js.map
  47059. var BABYLON;
  47060. (function (BABYLON) {
  47061. var ShaderMaterial = /** @class */ (function (_super) {
  47062. __extends(ShaderMaterial, _super);
  47063. function ShaderMaterial(name, scene, shaderPath, options) {
  47064. var _this = _super.call(this, name, scene) || this;
  47065. _this._textures = {};
  47066. _this._textureArrays = {};
  47067. _this._floats = {};
  47068. _this._floatsArrays = {};
  47069. _this._colors3 = {};
  47070. _this._colors3Arrays = {};
  47071. _this._colors4 = {};
  47072. _this._vectors2 = {};
  47073. _this._vectors3 = {};
  47074. _this._vectors4 = {};
  47075. _this._matrices = {};
  47076. _this._matrices3x3 = {};
  47077. _this._matrices2x2 = {};
  47078. _this._vectors3Arrays = {};
  47079. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  47080. _this._shaderPath = shaderPath;
  47081. options.needAlphaBlending = options.needAlphaBlending || false;
  47082. options.needAlphaTesting = options.needAlphaTesting || false;
  47083. options.attributes = options.attributes || ["position", "normal", "uv"];
  47084. options.uniforms = options.uniforms || ["worldViewProjection"];
  47085. options.uniformBuffers = options.uniformBuffers || [];
  47086. options.samplers = options.samplers || [];
  47087. options.defines = options.defines || [];
  47088. _this._options = options;
  47089. return _this;
  47090. }
  47091. ShaderMaterial.prototype.getClassName = function () {
  47092. return "ShaderMaterial";
  47093. };
  47094. ShaderMaterial.prototype.needAlphaBlending = function () {
  47095. return this._options.needAlphaBlending;
  47096. };
  47097. ShaderMaterial.prototype.needAlphaTesting = function () {
  47098. return this._options.needAlphaTesting;
  47099. };
  47100. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  47101. if (this._options.uniforms.indexOf(uniformName) === -1) {
  47102. this._options.uniforms.push(uniformName);
  47103. }
  47104. };
  47105. ShaderMaterial.prototype.setTexture = function (name, texture) {
  47106. if (this._options.samplers.indexOf(name) === -1) {
  47107. this._options.samplers.push(name);
  47108. }
  47109. this._textures[name] = texture;
  47110. return this;
  47111. };
  47112. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  47113. if (this._options.samplers.indexOf(name) === -1) {
  47114. this._options.samplers.push(name);
  47115. }
  47116. this._checkUniform(name);
  47117. this._textureArrays[name] = textures;
  47118. return this;
  47119. };
  47120. ShaderMaterial.prototype.setFloat = function (name, value) {
  47121. this._checkUniform(name);
  47122. this._floats[name] = value;
  47123. return this;
  47124. };
  47125. ShaderMaterial.prototype.setFloats = function (name, value) {
  47126. this._checkUniform(name);
  47127. this._floatsArrays[name] = value;
  47128. return this;
  47129. };
  47130. ShaderMaterial.prototype.setColor3 = function (name, value) {
  47131. this._checkUniform(name);
  47132. this._colors3[name] = value;
  47133. return this;
  47134. };
  47135. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  47136. this._checkUniform(name);
  47137. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  47138. color.toArray(arr, arr.length);
  47139. return arr;
  47140. }, []);
  47141. return this;
  47142. };
  47143. ShaderMaterial.prototype.setColor4 = function (name, value) {
  47144. this._checkUniform(name);
  47145. this._colors4[name] = value;
  47146. return this;
  47147. };
  47148. ShaderMaterial.prototype.setVector2 = function (name, value) {
  47149. this._checkUniform(name);
  47150. this._vectors2[name] = value;
  47151. return this;
  47152. };
  47153. ShaderMaterial.prototype.setVector3 = function (name, value) {
  47154. this._checkUniform(name);
  47155. this._vectors3[name] = value;
  47156. return this;
  47157. };
  47158. ShaderMaterial.prototype.setVector4 = function (name, value) {
  47159. this._checkUniform(name);
  47160. this._vectors4[name] = value;
  47161. return this;
  47162. };
  47163. ShaderMaterial.prototype.setMatrix = function (name, value) {
  47164. this._checkUniform(name);
  47165. this._matrices[name] = value;
  47166. return this;
  47167. };
  47168. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  47169. this._checkUniform(name);
  47170. this._matrices3x3[name] = value;
  47171. return this;
  47172. };
  47173. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  47174. this._checkUniform(name);
  47175. this._matrices2x2[name] = value;
  47176. return this;
  47177. };
  47178. ShaderMaterial.prototype.setArray3 = function (name, value) {
  47179. this._checkUniform(name);
  47180. this._vectors3Arrays[name] = value;
  47181. return this;
  47182. };
  47183. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  47184. if (!mesh) {
  47185. return true;
  47186. }
  47187. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  47188. return false;
  47189. }
  47190. return false;
  47191. };
  47192. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  47193. var scene = this.getScene();
  47194. var engine = scene.getEngine();
  47195. if (!this.checkReadyOnEveryCall) {
  47196. if (this._renderId === scene.getRenderId()) {
  47197. if (this._checkCache(scene, mesh, useInstances)) {
  47198. return true;
  47199. }
  47200. }
  47201. }
  47202. // Instances
  47203. var defines = [];
  47204. var attribs = [];
  47205. var fallbacks = new BABYLON.EffectFallbacks();
  47206. if (useInstances) {
  47207. defines.push("#define INSTANCES");
  47208. }
  47209. for (var index = 0; index < this._options.defines.length; index++) {
  47210. defines.push(this._options.defines[index]);
  47211. }
  47212. for (var index = 0; index < this._options.attributes.length; index++) {
  47213. attribs.push(this._options.attributes[index]);
  47214. }
  47215. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  47216. attribs.push(BABYLON.VertexBuffer.ColorKind);
  47217. defines.push("#define VERTEXCOLOR");
  47218. }
  47219. // Bones
  47220. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  47221. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47222. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47223. if (mesh.numBoneInfluencers > 4) {
  47224. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47225. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47226. }
  47227. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47228. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47229. fallbacks.addCPUSkinningFallback(0, mesh);
  47230. if (this._options.uniforms.indexOf("mBones") === -1) {
  47231. this._options.uniforms.push("mBones");
  47232. }
  47233. }
  47234. else {
  47235. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47236. }
  47237. // Textures
  47238. for (var name in this._textures) {
  47239. if (!this._textures[name].isReady()) {
  47240. return false;
  47241. }
  47242. }
  47243. // Alpha test
  47244. if (engine.getAlphaTesting()) {
  47245. defines.push("#define ALPHATEST");
  47246. }
  47247. var previousEffect = this._effect;
  47248. var join = defines.join("\n");
  47249. this._effect = engine.createEffect(this._shaderPath, {
  47250. attributes: attribs,
  47251. uniformsNames: this._options.uniforms,
  47252. uniformBuffersNames: this._options.uniformBuffers,
  47253. samplers: this._options.samplers,
  47254. defines: join,
  47255. fallbacks: fallbacks,
  47256. onCompiled: this.onCompiled,
  47257. onError: this.onError
  47258. }, engine);
  47259. if (!this._effect.isReady()) {
  47260. return false;
  47261. }
  47262. if (previousEffect !== this._effect) {
  47263. scene.resetCachedMaterial();
  47264. }
  47265. this._renderId = scene.getRenderId();
  47266. return true;
  47267. };
  47268. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  47269. var scene = this.getScene();
  47270. if (!this._effect) {
  47271. return;
  47272. }
  47273. if (this._options.uniforms.indexOf("world") !== -1) {
  47274. this._effect.setMatrix("world", world);
  47275. }
  47276. if (this._options.uniforms.indexOf("worldView") !== -1) {
  47277. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  47278. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  47279. }
  47280. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  47281. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  47282. }
  47283. };
  47284. ShaderMaterial.prototype.bind = function (world, mesh) {
  47285. // Std values
  47286. this.bindOnlyWorldMatrix(world);
  47287. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  47288. if (this._options.uniforms.indexOf("view") !== -1) {
  47289. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  47290. }
  47291. if (this._options.uniforms.indexOf("projection") !== -1) {
  47292. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  47293. }
  47294. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  47295. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  47296. }
  47297. // Bones
  47298. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  47299. var name;
  47300. // Texture
  47301. for (name in this._textures) {
  47302. this._effect.setTexture(name, this._textures[name]);
  47303. }
  47304. // Texture arrays
  47305. for (name in this._textureArrays) {
  47306. this._effect.setTextureArray(name, this._textureArrays[name]);
  47307. }
  47308. // Float
  47309. for (name in this._floats) {
  47310. this._effect.setFloat(name, this._floats[name]);
  47311. }
  47312. // Float s
  47313. for (name in this._floatsArrays) {
  47314. this._effect.setArray(name, this._floatsArrays[name]);
  47315. }
  47316. // Color3
  47317. for (name in this._colors3) {
  47318. this._effect.setColor3(name, this._colors3[name]);
  47319. }
  47320. for (name in this._colors3Arrays) {
  47321. this._effect.setArray3(name, this._colors3Arrays[name]);
  47322. }
  47323. // Color4
  47324. for (name in this._colors4) {
  47325. var color = this._colors4[name];
  47326. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  47327. }
  47328. // Vector2
  47329. for (name in this._vectors2) {
  47330. this._effect.setVector2(name, this._vectors2[name]);
  47331. }
  47332. // Vector3
  47333. for (name in this._vectors3) {
  47334. this._effect.setVector3(name, this._vectors3[name]);
  47335. }
  47336. // Vector4
  47337. for (name in this._vectors4) {
  47338. this._effect.setVector4(name, this._vectors4[name]);
  47339. }
  47340. // Matrix
  47341. for (name in this._matrices) {
  47342. this._effect.setMatrix(name, this._matrices[name]);
  47343. }
  47344. // Matrix 3x3
  47345. for (name in this._matrices3x3) {
  47346. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  47347. }
  47348. // Matrix 2x2
  47349. for (name in this._matrices2x2) {
  47350. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  47351. }
  47352. // Vector3Array
  47353. for (name in this._vectors3Arrays) {
  47354. this._effect.setArray3(name, this._vectors3Arrays[name]);
  47355. }
  47356. }
  47357. this._afterBind(mesh);
  47358. };
  47359. ShaderMaterial.prototype.getActiveTextures = function () {
  47360. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47361. for (var name in this._textures) {
  47362. activeTextures.push(this._textures[name]);
  47363. }
  47364. for (var name in this._textureArrays) {
  47365. var array = this._textureArrays[name];
  47366. for (var index = 0; index < array.length; index++) {
  47367. activeTextures.push(array[index]);
  47368. }
  47369. }
  47370. return activeTextures;
  47371. };
  47372. ShaderMaterial.prototype.hasTexture = function (texture) {
  47373. if (_super.prototype.hasTexture.call(this, texture)) {
  47374. return true;
  47375. }
  47376. for (var name in this._textures) {
  47377. if (this._textures[name] === texture) {
  47378. return true;
  47379. }
  47380. }
  47381. for (var name in this._textureArrays) {
  47382. var array = this._textureArrays[name];
  47383. for (var index = 0; index < array.length; index++) {
  47384. if (array[index] === texture) {
  47385. return true;
  47386. }
  47387. }
  47388. }
  47389. return false;
  47390. };
  47391. ShaderMaterial.prototype.clone = function (name) {
  47392. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  47393. return newShaderMaterial;
  47394. };
  47395. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  47396. if (forceDisposeTextures) {
  47397. var name;
  47398. for (name in this._textures) {
  47399. this._textures[name].dispose();
  47400. }
  47401. for (name in this._textureArrays) {
  47402. var array = this._textureArrays[name];
  47403. for (var index = 0; index < array.length; index++) {
  47404. array[index].dispose();
  47405. }
  47406. }
  47407. }
  47408. this._textures = {};
  47409. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  47410. };
  47411. ShaderMaterial.prototype.serialize = function () {
  47412. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47413. serializationObject.customType = "BABYLON.ShaderMaterial";
  47414. serializationObject.options = this._options;
  47415. serializationObject.shaderPath = this._shaderPath;
  47416. var name;
  47417. // Texture
  47418. serializationObject.textures = {};
  47419. for (name in this._textures) {
  47420. serializationObject.textures[name] = this._textures[name].serialize();
  47421. }
  47422. // Texture arrays
  47423. serializationObject.textureArrays = {};
  47424. for (name in this._textureArrays) {
  47425. serializationObject.textureArrays[name] = [];
  47426. var array = this._textureArrays[name];
  47427. for (var index = 0; index < array.length; index++) {
  47428. serializationObject.textureArrays[name].push(array[index].serialize());
  47429. }
  47430. }
  47431. // Float
  47432. serializationObject.floats = {};
  47433. for (name in this._floats) {
  47434. serializationObject.floats[name] = this._floats[name];
  47435. }
  47436. // Float s
  47437. serializationObject.FloatArrays = {};
  47438. for (name in this._floatsArrays) {
  47439. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  47440. }
  47441. // Color3
  47442. serializationObject.colors3 = {};
  47443. for (name in this._colors3) {
  47444. serializationObject.colors3[name] = this._colors3[name].asArray();
  47445. }
  47446. // Color3 array
  47447. serializationObject.colors3Arrays = {};
  47448. for (name in this._colors3Arrays) {
  47449. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  47450. }
  47451. // Color4
  47452. serializationObject.colors4 = {};
  47453. for (name in this._colors4) {
  47454. serializationObject.colors4[name] = this._colors4[name].asArray();
  47455. }
  47456. // Vector2
  47457. serializationObject.vectors2 = {};
  47458. for (name in this._vectors2) {
  47459. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  47460. }
  47461. // Vector3
  47462. serializationObject.vectors3 = {};
  47463. for (name in this._vectors3) {
  47464. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  47465. }
  47466. // Vector4
  47467. serializationObject.vectors4 = {};
  47468. for (name in this._vectors4) {
  47469. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  47470. }
  47471. // Matrix
  47472. serializationObject.matrices = {};
  47473. for (name in this._matrices) {
  47474. serializationObject.matrices[name] = this._matrices[name].asArray();
  47475. }
  47476. // Matrix 3x3
  47477. serializationObject.matrices3x3 = {};
  47478. for (name in this._matrices3x3) {
  47479. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  47480. }
  47481. // Matrix 2x2
  47482. serializationObject.matrices2x2 = {};
  47483. for (name in this._matrices2x2) {
  47484. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  47485. }
  47486. // Vector3Array
  47487. serializationObject.vectors3Arrays = {};
  47488. for (name in this._vectors3Arrays) {
  47489. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  47490. }
  47491. return serializationObject;
  47492. };
  47493. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  47494. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  47495. var name;
  47496. // Texture
  47497. for (name in source.textures) {
  47498. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  47499. }
  47500. // Texture arrays
  47501. for (name in source.textureArrays) {
  47502. var array = source.textureArrays[name];
  47503. var textureArray = new Array();
  47504. for (var index = 0; index < array.length; index++) {
  47505. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  47506. }
  47507. material.setTextureArray(name, textureArray);
  47508. }
  47509. // Float
  47510. for (name in source.floats) {
  47511. material.setFloat(name, source.floats[name]);
  47512. }
  47513. // Float s
  47514. for (name in source.floatsArrays) {
  47515. material.setFloats(name, source.floatsArrays[name]);
  47516. }
  47517. // Color3
  47518. for (name in source.colors3) {
  47519. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  47520. }
  47521. // Color3 arrays
  47522. for (name in source.colors3Arrays) {
  47523. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  47524. if (i % 3 === 0) {
  47525. arr.push([num]);
  47526. }
  47527. else {
  47528. arr[arr.length - 1].push(num);
  47529. }
  47530. return arr;
  47531. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  47532. material.setColor3Array(name, colors);
  47533. }
  47534. // Color4
  47535. for (name in source.colors4) {
  47536. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  47537. }
  47538. // Vector2
  47539. for (name in source.vectors2) {
  47540. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  47541. }
  47542. // Vector3
  47543. for (name in source.vectors3) {
  47544. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  47545. }
  47546. // Vector4
  47547. for (name in source.vectors4) {
  47548. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  47549. }
  47550. // Matrix
  47551. for (name in source.matrices) {
  47552. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  47553. }
  47554. // Matrix 3x3
  47555. for (name in source.matrices3x3) {
  47556. material.setMatrix3x3(name, source.matrices3x3[name]);
  47557. }
  47558. // Matrix 2x2
  47559. for (name in source.matrices2x2) {
  47560. material.setMatrix2x2(name, source.matrices2x2[name]);
  47561. }
  47562. // Vector3Array
  47563. for (name in source.vectors3Arrays) {
  47564. material.setArray3(name, source.vectors3Arrays[name]);
  47565. }
  47566. return material;
  47567. };
  47568. return ShaderMaterial;
  47569. }(BABYLON.Material));
  47570. BABYLON.ShaderMaterial = ShaderMaterial;
  47571. })(BABYLON || (BABYLON = {}));
  47572. //# sourceMappingURL=babylon.shaderMaterial.js.map
  47573. var BABYLON;
  47574. (function (BABYLON) {
  47575. var MeshBuilder = /** @class */ (function () {
  47576. function MeshBuilder() {
  47577. }
  47578. MeshBuilder.updateSideOrientation = function (orientation) {
  47579. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  47580. return BABYLON.Mesh.DOUBLESIDE;
  47581. }
  47582. if (orientation === undefined || orientation === null) {
  47583. return BABYLON.Mesh.FRONTSIDE;
  47584. }
  47585. return orientation;
  47586. };
  47587. /**
  47588. * Creates a box mesh.
  47589. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  47590. * The parameter `size` sets the size (float) of each box side (default 1).
  47591. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  47592. * 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).
  47593. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47594. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47595. * 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).
  47596. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47597. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47598. */
  47599. MeshBuilder.CreateBox = function (name, options, scene) {
  47600. if (scene === void 0) { scene = null; }
  47601. var box = new BABYLON.Mesh(name, scene);
  47602. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47603. box._originalBuilderSideOrientation = options.sideOrientation;
  47604. var vertexData = BABYLON.VertexData.CreateBox(options);
  47605. vertexData.applyToMesh(box, options.updatable);
  47606. return box;
  47607. };
  47608. /**
  47609. * Creates a sphere mesh.
  47610. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  47611. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  47612. * 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`).
  47613. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  47614. * 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
  47615. * 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).
  47616. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47617. * 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).
  47618. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47619. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47620. */
  47621. MeshBuilder.CreateSphere = function (name, options, scene) {
  47622. var sphere = new BABYLON.Mesh(name, scene);
  47623. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47624. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47625. var vertexData = BABYLON.VertexData.CreateSphere(options);
  47626. vertexData.applyToMesh(sphere, options.updatable);
  47627. return sphere;
  47628. };
  47629. /**
  47630. * Creates a plane polygonal mesh. By default, this is a disc.
  47631. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  47632. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  47633. * 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.
  47634. * 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
  47635. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47636. * 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).
  47637. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47638. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47639. */
  47640. MeshBuilder.CreateDisc = function (name, options, scene) {
  47641. if (scene === void 0) { scene = null; }
  47642. var disc = new BABYLON.Mesh(name, scene);
  47643. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47644. disc._originalBuilderSideOrientation = options.sideOrientation;
  47645. var vertexData = BABYLON.VertexData.CreateDisc(options);
  47646. vertexData.applyToMesh(disc, options.updatable);
  47647. return disc;
  47648. };
  47649. /**
  47650. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  47651. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  47652. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  47653. * 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`).
  47654. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  47655. * 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.
  47656. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47657. * 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).
  47658. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47659. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47660. */
  47661. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  47662. var sphere = new BABYLON.Mesh(name, scene);
  47663. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47664. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47665. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  47666. vertexData.applyToMesh(sphere, options.updatable);
  47667. return sphere;
  47668. };
  47669. ;
  47670. /**
  47671. * Creates a ribbon mesh.
  47672. * 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.
  47673. *
  47674. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  47675. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  47676. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  47677. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  47678. * 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.
  47679. * 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.
  47680. * 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
  47681. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47682. * 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).
  47683. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47684. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47685. * 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.
  47686. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  47687. * 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
  47688. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  47689. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  47690. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47691. */
  47692. MeshBuilder.CreateRibbon = function (name, options, scene) {
  47693. if (scene === void 0) { scene = null; }
  47694. var pathArray = options.pathArray;
  47695. var closeArray = options.closeArray;
  47696. var closePath = options.closePath;
  47697. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47698. var instance = options.instance;
  47699. var updatable = options.updatable;
  47700. if (instance) {
  47701. // positionFunction : ribbon case
  47702. // only pathArray and sideOrientation parameters are taken into account for positions update
  47703. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  47704. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  47705. var positionFunction = function (positions) {
  47706. var minlg = pathArray[0].length;
  47707. var i = 0;
  47708. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  47709. for (var si = 1; si <= ns; si++) {
  47710. for (var p = 0; p < pathArray.length; p++) {
  47711. var path = pathArray[p];
  47712. var l = path.length;
  47713. minlg = (minlg < l) ? minlg : l;
  47714. var j = 0;
  47715. while (j < minlg) {
  47716. positions[i] = path[j].x;
  47717. positions[i + 1] = path[j].y;
  47718. positions[i + 2] = path[j].z;
  47719. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  47720. BABYLON.Tmp.Vector3[0].x = path[j].x;
  47721. }
  47722. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  47723. BABYLON.Tmp.Vector3[1].x = path[j].x;
  47724. }
  47725. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  47726. BABYLON.Tmp.Vector3[0].y = path[j].y;
  47727. }
  47728. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  47729. BABYLON.Tmp.Vector3[1].y = path[j].y;
  47730. }
  47731. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  47732. BABYLON.Tmp.Vector3[0].z = path[j].z;
  47733. }
  47734. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  47735. BABYLON.Tmp.Vector3[1].z = path[j].z;
  47736. }
  47737. j++;
  47738. i += 3;
  47739. }
  47740. if (instance._closePath) {
  47741. positions[i] = path[0].x;
  47742. positions[i + 1] = path[0].y;
  47743. positions[i + 2] = path[0].z;
  47744. i += 3;
  47745. }
  47746. }
  47747. }
  47748. };
  47749. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47750. positionFunction(positions);
  47751. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  47752. instance._boundingInfo.update(instance._worldMatrix);
  47753. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  47754. if (options.colors) {
  47755. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47756. for (var c = 0; c < options.colors.length; c++) {
  47757. colors[c * 4] = options.colors[c].r;
  47758. colors[c * 4 + 1] = options.colors[c].g;
  47759. colors[c * 4 + 2] = options.colors[c].b;
  47760. colors[c * 4 + 3] = options.colors[c].a;
  47761. }
  47762. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  47763. }
  47764. if (options.uvs) {
  47765. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47766. for (var i = 0; i < options.uvs.length; i++) {
  47767. uvs[i * 2] = options.uvs[i].x;
  47768. uvs[i * 2 + 1] = options.uvs[i].y;
  47769. }
  47770. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  47771. }
  47772. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  47773. var indices = instance.getIndices();
  47774. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47775. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  47776. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  47777. if (instance._closePath) {
  47778. var indexFirst = 0;
  47779. var indexLast = 0;
  47780. for (var p = 0; p < pathArray.length; p++) {
  47781. indexFirst = instance._idx[p] * 3;
  47782. if (p + 1 < pathArray.length) {
  47783. indexLast = (instance._idx[p + 1] - 1) * 3;
  47784. }
  47785. else {
  47786. indexLast = normals.length - 3;
  47787. }
  47788. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  47789. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  47790. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  47791. normals[indexLast] = normals[indexFirst];
  47792. normals[indexLast + 1] = normals[indexFirst + 1];
  47793. normals[indexLast + 2] = normals[indexFirst + 2];
  47794. }
  47795. }
  47796. if (!(instance.areNormalsFrozen)) {
  47797. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  47798. }
  47799. }
  47800. return instance;
  47801. }
  47802. else {
  47803. var ribbon = new BABYLON.Mesh(name, scene);
  47804. ribbon._originalBuilderSideOrientation = sideOrientation;
  47805. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  47806. if (closePath) {
  47807. ribbon._idx = vertexData._idx;
  47808. }
  47809. ribbon._closePath = closePath;
  47810. ribbon._closeArray = closeArray;
  47811. vertexData.applyToMesh(ribbon, updatable);
  47812. return ribbon;
  47813. }
  47814. };
  47815. /**
  47816. * Creates a cylinder or a cone mesh.
  47817. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  47818. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  47819. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  47820. * 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.
  47821. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  47822. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  47823. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  47824. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  47825. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  47826. * 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).
  47827. * 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
  47828. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  47829. * 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
  47830. * 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.
  47831. * If `enclose` is false, a ring surface is one element.
  47832. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  47833. * 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
  47834. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47835. * 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).
  47836. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47837. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47838. */
  47839. MeshBuilder.CreateCylinder = function (name, options, scene) {
  47840. var cylinder = new BABYLON.Mesh(name, scene);
  47841. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47842. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  47843. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  47844. vertexData.applyToMesh(cylinder, options.updatable);
  47845. return cylinder;
  47846. };
  47847. /**
  47848. * Creates a torus mesh.
  47849. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  47850. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  47851. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  47852. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  47853. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47854. * 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).
  47855. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47856. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47857. */
  47858. MeshBuilder.CreateTorus = function (name, options, scene) {
  47859. var torus = new BABYLON.Mesh(name, scene);
  47860. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47861. torus._originalBuilderSideOrientation = options.sideOrientation;
  47862. var vertexData = BABYLON.VertexData.CreateTorus(options);
  47863. vertexData.applyToMesh(torus, options.updatable);
  47864. return torus;
  47865. };
  47866. /**
  47867. * Creates a torus knot mesh.
  47868. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  47869. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  47870. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  47871. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  47872. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  47873. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47874. * 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).
  47875. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47876. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47877. */
  47878. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  47879. var torusKnot = new BABYLON.Mesh(name, scene);
  47880. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47881. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  47882. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  47883. vertexData.applyToMesh(torusKnot, options.updatable);
  47884. return torusKnot;
  47885. };
  47886. /**
  47887. * Creates a line system mesh.
  47888. * A line system is a pool of many lines gathered in a single mesh.
  47889. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  47890. * 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.
  47891. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  47892. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  47893. * 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
  47894. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  47895. * The optional parameter `useVertexAlpha' is to be set to `true` (default `false`) when the alpha value from the former `Color4` array must be used.
  47896. * 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
  47897. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  47898. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47899. */
  47900. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  47901. var instance = options.instance;
  47902. var lines = options.lines;
  47903. var colors = options.colors;
  47904. if (instance) {
  47905. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47906. var vertexColor;
  47907. var lineColors;
  47908. if (colors) {
  47909. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47910. }
  47911. var i = 0;
  47912. var c = 0;
  47913. for (var l = 0; l < lines.length; l++) {
  47914. var points = lines[l];
  47915. for (var p = 0; p < points.length; p++) {
  47916. positions[i] = points[p].x;
  47917. positions[i + 1] = points[p].y;
  47918. positions[i + 2] = points[p].z;
  47919. if (colors && vertexColor) {
  47920. lineColors = colors[l];
  47921. vertexColor[c] = lineColors[p].r;
  47922. vertexColor[c + 1] = lineColors[p].g;
  47923. vertexColor[c + 2] = lineColors[p].b;
  47924. vertexColor[c + 3] = lineColors[p].a;
  47925. c += 4;
  47926. }
  47927. i += 3;
  47928. }
  47929. }
  47930. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  47931. if (colors && vertexColor) {
  47932. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  47933. }
  47934. return instance;
  47935. }
  47936. // line system creation
  47937. var useVertexColor = (colors) ? true : false;
  47938. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  47939. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  47940. vertexData.applyToMesh(lineSystem, options.updatable);
  47941. return lineSystem;
  47942. };
  47943. /**
  47944. * Creates a line mesh.
  47945. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  47946. * 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.
  47947. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47948. * The parameter `points` is an array successive Vector3.
  47949. * 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
  47950. * The optional parameter `colors` is an array of successive Color4, one per line point.
  47951. * The optional parameter `useVertexAlpha' is to be set to `true` (default `false`) when the alpha value from the former `Color4` array must be used.
  47952. * When updating an instance, remember that only point positions can change, not the number of points.
  47953. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47954. */
  47955. MeshBuilder.CreateLines = function (name, options, scene) {
  47956. if (scene === void 0) { scene = null; }
  47957. var colors = (options.colors) ? [options.colors] : null;
  47958. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  47959. return lines;
  47960. };
  47961. /**
  47962. * Creates a dashed line mesh.
  47963. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  47964. * 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.
  47965. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47966. * The parameter `points` is an array successive Vector3.
  47967. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  47968. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  47969. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  47970. * 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
  47971. * When updating an instance, remember that only point positions can change, not the number of points.
  47972. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47973. */
  47974. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  47975. if (scene === void 0) { scene = null; }
  47976. var points = options.points;
  47977. var instance = options.instance;
  47978. var gapSize = options.gapSize || 1;
  47979. var dashSize = options.dashSize || 3;
  47980. if (instance) {
  47981. var positionFunction = function (positions) {
  47982. var curvect = BABYLON.Vector3.Zero();
  47983. var nbSeg = positions.length / 6;
  47984. var lg = 0;
  47985. var nb = 0;
  47986. var shft = 0;
  47987. var dashshft = 0;
  47988. var curshft = 0;
  47989. var p = 0;
  47990. var i = 0;
  47991. var j = 0;
  47992. for (i = 0; i < points.length - 1; i++) {
  47993. points[i + 1].subtractToRef(points[i], curvect);
  47994. lg += curvect.length();
  47995. }
  47996. shft = lg / nbSeg;
  47997. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  47998. for (i = 0; i < points.length - 1; i++) {
  47999. points[i + 1].subtractToRef(points[i], curvect);
  48000. nb = Math.floor(curvect.length() / shft);
  48001. curvect.normalize();
  48002. j = 0;
  48003. while (j < nb && p < positions.length) {
  48004. curshft = shft * j;
  48005. positions[p] = points[i].x + curshft * curvect.x;
  48006. positions[p + 1] = points[i].y + curshft * curvect.y;
  48007. positions[p + 2] = points[i].z + curshft * curvect.z;
  48008. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  48009. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  48010. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  48011. p += 6;
  48012. j++;
  48013. }
  48014. }
  48015. while (p < positions.length) {
  48016. positions[p] = points[i].x;
  48017. positions[p + 1] = points[i].y;
  48018. positions[p + 2] = points[i].z;
  48019. p += 3;
  48020. }
  48021. };
  48022. instance.updateMeshPositions(positionFunction, false);
  48023. return instance;
  48024. }
  48025. // dashed lines creation
  48026. var dashedLines = new BABYLON.LinesMesh(name, scene);
  48027. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  48028. vertexData.applyToMesh(dashedLines, options.updatable);
  48029. dashedLines.dashSize = dashSize;
  48030. dashedLines.gapSize = gapSize;
  48031. return dashedLines;
  48032. };
  48033. /**
  48034. * Creates an extruded shape mesh.
  48035. * 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.
  48036. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  48037. *
  48038. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48039. * 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
  48040. * extruded along the Z axis.
  48041. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48042. * 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.
  48043. * The parameter `scale` (float, default 1) is the value to scale the shape.
  48044. * 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
  48045. * 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
  48046. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48047. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48048. * 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).
  48049. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48050. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48051. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48052. */
  48053. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  48054. if (scene === void 0) { scene = null; }
  48055. var path = options.path;
  48056. var shape = options.shape;
  48057. var scale = options.scale || 1;
  48058. var rotation = options.rotation || 0;
  48059. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48060. var updatable = options.updatable;
  48061. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48062. var instance = options.instance || null;
  48063. var invertUV = options.invertUV || false;
  48064. 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);
  48065. };
  48066. /**
  48067. * Creates an custom extruded shape mesh.
  48068. * 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.
  48069. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  48070. *
  48071. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48072. * 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
  48073. * extruded along the Z axis.
  48074. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48075. * 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
  48076. * and the distance of this point from the begining of the path :
  48077. * ```javascript
  48078. * var rotationFunction = function(i, distance) {
  48079. * // do things
  48080. * return rotationValue; }
  48081. * ```
  48082. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  48083. * 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
  48084. * and the distance of this point from the begining of the path :
  48085. * ```javascript
  48086. * var scaleFunction = function(i, distance) {
  48087. * // do things
  48088. * return scaleValue;}
  48089. * ```
  48090. * It must returns a float value that will be the scale value applied to the shape on each path point.
  48091. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  48092. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  48093. * 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
  48094. * 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
  48095. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48096. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48097. * 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).
  48098. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48099. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48100. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48101. */
  48102. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  48103. var path = options.path;
  48104. var shape = options.shape;
  48105. var scaleFunction = options.scaleFunction || (function () { return 1; });
  48106. var rotationFunction = options.rotationFunction || (function () { return 0; });
  48107. var ribbonCloseArray = options.ribbonCloseArray || false;
  48108. var ribbonClosePath = options.ribbonClosePath || false;
  48109. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48110. var updatable = options.updatable;
  48111. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48112. var instance = options.instance;
  48113. var invertUV = options.invertUV || false;
  48114. 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);
  48115. };
  48116. /**
  48117. * Creates lathe mesh.
  48118. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  48119. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  48120. *
  48121. * 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
  48122. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  48123. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  48124. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  48125. * 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.
  48126. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  48127. * 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
  48128. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48129. * 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).
  48130. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48131. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48132. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48133. */
  48134. MeshBuilder.CreateLathe = function (name, options, scene) {
  48135. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  48136. var closed = (options.closed === undefined) ? true : options.closed;
  48137. var shape = options.shape;
  48138. var radius = options.radius || 1;
  48139. var tessellation = options.tessellation || 64;
  48140. var updatable = options.updatable;
  48141. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48142. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48143. var pi2 = Math.PI * 2;
  48144. var paths = new Array();
  48145. var invertUV = options.invertUV || false;
  48146. var i = 0;
  48147. var p = 0;
  48148. var step = pi2 / tessellation * arc;
  48149. var rotated;
  48150. var path = new Array();
  48151. ;
  48152. for (i = 0; i <= tessellation; i++) {
  48153. var path = [];
  48154. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  48155. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  48156. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  48157. }
  48158. for (p = 0; p < shape.length; p++) {
  48159. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  48160. path.push(rotated);
  48161. }
  48162. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  48163. 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));
  48164. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  48165. }
  48166. paths.push(path);
  48167. }
  48168. // lathe ribbon
  48169. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48170. return lathe;
  48171. };
  48172. /**
  48173. * Creates a plane mesh.
  48174. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48175. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  48176. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  48177. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  48178. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48179. * 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).
  48180. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48181. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48182. */
  48183. MeshBuilder.CreatePlane = function (name, options, scene) {
  48184. var plane = new BABYLON.Mesh(name, scene);
  48185. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48186. plane._originalBuilderSideOrientation = options.sideOrientation;
  48187. var vertexData = BABYLON.VertexData.CreatePlane(options);
  48188. vertexData.applyToMesh(plane, options.updatable);
  48189. if (options.sourcePlane) {
  48190. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  48191. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  48192. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  48193. plane.rotate(vectorProduct, product);
  48194. }
  48195. return plane;
  48196. };
  48197. /**
  48198. * Creates a ground mesh.
  48199. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48200. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  48201. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  48202. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48203. */
  48204. MeshBuilder.CreateGround = function (name, options, scene) {
  48205. var ground = new BABYLON.GroundMesh(name, scene);
  48206. ground._setReady(false);
  48207. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  48208. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  48209. ground._width = options.width || 1;
  48210. ground._height = options.height || 1;
  48211. ground._maxX = ground._width / 2;
  48212. ground._maxZ = ground._height / 2;
  48213. ground._minX = -ground._maxX;
  48214. ground._minZ = -ground._maxZ;
  48215. var vertexData = BABYLON.VertexData.CreateGround(options);
  48216. vertexData.applyToMesh(ground, options.updatable);
  48217. ground._setReady(true);
  48218. return ground;
  48219. };
  48220. /**
  48221. * Creates a tiled ground mesh.
  48222. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  48223. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  48224. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  48225. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  48226. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  48227. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  48228. * numbers of subdivisions on the ground width and height of each tile.
  48229. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48230. */
  48231. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  48232. var tiledGround = new BABYLON.Mesh(name, scene);
  48233. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  48234. vertexData.applyToMesh(tiledGround, options.updatable);
  48235. return tiledGround;
  48236. };
  48237. /**
  48238. * Creates a ground mesh from a height map.
  48239. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  48240. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  48241. * The parameter `url` sets the URL of the height map image resource.
  48242. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  48243. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  48244. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  48245. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  48246. * 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.
  48247. * 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).
  48248. * This function is passed the newly built mesh :
  48249. * ```javascript
  48250. * function(mesh) { // do things
  48251. * return; }
  48252. * ```
  48253. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48254. */
  48255. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  48256. var width = options.width || 10.0;
  48257. var height = options.height || 10.0;
  48258. var subdivisions = options.subdivisions || 1 | 0;
  48259. var minHeight = options.minHeight || 0.0;
  48260. var maxHeight = options.maxHeight || 1.0;
  48261. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  48262. var updatable = options.updatable;
  48263. var onReady = options.onReady;
  48264. var ground = new BABYLON.GroundMesh(name, scene);
  48265. ground._subdivisionsX = subdivisions;
  48266. ground._subdivisionsY = subdivisions;
  48267. ground._width = width;
  48268. ground._height = height;
  48269. ground._maxX = ground._width / 2.0;
  48270. ground._maxZ = ground._height / 2.0;
  48271. ground._minX = -ground._maxX;
  48272. ground._minZ = -ground._maxZ;
  48273. ground._setReady(false);
  48274. var onload = function (img) {
  48275. // Getting height map data
  48276. var canvas = document.createElement("canvas");
  48277. var context = canvas.getContext("2d");
  48278. if (!context) {
  48279. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  48280. }
  48281. var bufferWidth = img.width;
  48282. var bufferHeight = img.height;
  48283. canvas.width = bufferWidth;
  48284. canvas.height = bufferHeight;
  48285. context.drawImage(img, 0, 0);
  48286. // Create VertexData from map data
  48287. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  48288. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  48289. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  48290. width: width, height: height,
  48291. subdivisions: subdivisions,
  48292. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  48293. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  48294. });
  48295. vertexData.applyToMesh(ground, updatable);
  48296. ground._setReady(true);
  48297. //execute ready callback, if set
  48298. if (onReady) {
  48299. onReady(ground);
  48300. }
  48301. };
  48302. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  48303. return ground;
  48304. };
  48305. /**
  48306. * Creates a polygon mesh.
  48307. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  48308. * 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.
  48309. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48310. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48311. * 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).
  48312. * Remember you can only change the shape positions, not their number when updating a polygon.
  48313. */
  48314. MeshBuilder.CreatePolygon = function (name, options, scene) {
  48315. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48316. var shape = options.shape;
  48317. var holes = options.holes || [];
  48318. var depth = options.depth || 0;
  48319. var contours = [];
  48320. var hole = [];
  48321. for (var i = 0; i < shape.length; i++) {
  48322. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  48323. }
  48324. var epsilon = 0.00000001;
  48325. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  48326. contours.pop();
  48327. }
  48328. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  48329. for (var hNb = 0; hNb < holes.length; hNb++) {
  48330. hole = [];
  48331. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  48332. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  48333. }
  48334. polygonTriangulation.addHole(hole);
  48335. }
  48336. var polygon = polygonTriangulation.build(options.updatable, depth);
  48337. polygon._originalBuilderSideOrientation = options.sideOrientation;
  48338. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  48339. vertexData.applyToMesh(polygon, options.updatable);
  48340. return polygon;
  48341. };
  48342. ;
  48343. /**
  48344. * Creates an extruded polygon mesh, with depth in the Y direction.
  48345. * 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).
  48346. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  48347. */
  48348. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  48349. return MeshBuilder.CreatePolygon(name, options, scene);
  48350. };
  48351. ;
  48352. /**
  48353. * Creates a tube mesh.
  48354. * 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.
  48355. *
  48356. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  48357. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  48358. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  48359. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  48360. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  48361. * 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.
  48362. * It must return a radius value (positive float) :
  48363. * ```javascript
  48364. * var radiusFunction = function(i, distance) {
  48365. * // do things
  48366. * return radius; }
  48367. * ```
  48368. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  48369. * 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
  48370. * 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
  48371. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48372. * 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).
  48373. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48374. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48375. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48376. */
  48377. MeshBuilder.CreateTube = function (name, options, scene) {
  48378. var path = options.path;
  48379. var instance = options.instance;
  48380. var radius = 1.0;
  48381. if (instance) {
  48382. radius = instance.radius;
  48383. }
  48384. if (options.radius !== undefined) {
  48385. radius = options.radius;
  48386. }
  48387. ;
  48388. var tessellation = options.tessellation || 64 | 0;
  48389. var radiusFunction = options.radiusFunction || null;
  48390. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48391. var invertUV = options.invertUV || false;
  48392. var updatable = options.updatable;
  48393. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48394. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  48395. // tube geometry
  48396. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  48397. var tangents = path3D.getTangents();
  48398. var normals = path3D.getNormals();
  48399. var distances = path3D.getDistances();
  48400. var pi2 = Math.PI * 2;
  48401. var step = pi2 / tessellation * arc;
  48402. var returnRadius = function () { return radius; };
  48403. var radiusFunctionFinal = radiusFunction || returnRadius;
  48404. var circlePath;
  48405. var rad;
  48406. var normal;
  48407. var rotated;
  48408. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48409. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48410. for (var i = 0; i < path.length; i++) {
  48411. rad = radiusFunctionFinal(i, distances[i]); // current radius
  48412. circlePath = Array(); // current circle array
  48413. normal = normals[i]; // current normal
  48414. for (var t = 0; t < tessellation; t++) {
  48415. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  48416. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  48417. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  48418. rotated.scaleInPlace(rad).addInPlace(path[i]);
  48419. circlePath[t] = rotated;
  48420. }
  48421. circlePaths[index] = circlePath;
  48422. index++;
  48423. }
  48424. // cap
  48425. var capPath = function (nbPoints, pathIndex) {
  48426. var pointCap = Array();
  48427. for (var i = 0; i < nbPoints; i++) {
  48428. pointCap.push(path[pathIndex]);
  48429. }
  48430. return pointCap;
  48431. };
  48432. switch (cap) {
  48433. case BABYLON.Mesh.NO_CAP:
  48434. break;
  48435. case BABYLON.Mesh.CAP_START:
  48436. circlePaths[0] = capPath(tessellation, 0);
  48437. circlePaths[1] = circlePaths[2].slice(0);
  48438. break;
  48439. case BABYLON.Mesh.CAP_END:
  48440. circlePaths[index] = circlePaths[index - 1].slice(0);
  48441. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  48442. break;
  48443. case BABYLON.Mesh.CAP_ALL:
  48444. circlePaths[0] = capPath(tessellation, 0);
  48445. circlePaths[1] = circlePaths[2].slice(0);
  48446. circlePaths[index] = circlePaths[index - 1].slice(0);
  48447. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  48448. break;
  48449. default:
  48450. break;
  48451. }
  48452. return circlePaths;
  48453. };
  48454. var path3D;
  48455. var pathArray;
  48456. if (instance) {
  48457. var arc = options.arc || instance.arc;
  48458. path3D = (instance.path3D).update(path);
  48459. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  48460. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  48461. instance.path3D = path3D;
  48462. instance.pathArray = pathArray;
  48463. instance.arc = arc;
  48464. instance.radius = radius;
  48465. return instance;
  48466. }
  48467. // tube creation
  48468. path3D = new BABYLON.Path3D(path);
  48469. var newPathArray = new Array();
  48470. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48471. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  48472. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48473. tube.pathArray = pathArray;
  48474. tube.path3D = path3D;
  48475. tube.tessellation = tessellation;
  48476. tube.cap = cap;
  48477. tube.arc = options.arc;
  48478. tube.radius = radius;
  48479. return tube;
  48480. };
  48481. /**
  48482. * Creates a polyhedron mesh.
  48483. *
  48484. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  48485. * 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
  48486. * to choose the wanted type.
  48487. * The parameter `size` (positive float, default 1) sets the polygon size.
  48488. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  48489. * 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`.
  48490. * 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
  48491. * 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)`).
  48492. * 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
  48493. * 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.
  48494. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48495. * 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).
  48496. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48497. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48498. */
  48499. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  48500. var polyhedron = new BABYLON.Mesh(name, scene);
  48501. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48502. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  48503. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  48504. vertexData.applyToMesh(polyhedron, options.updatable);
  48505. return polyhedron;
  48506. };
  48507. /**
  48508. * Creates a decal mesh.
  48509. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  48510. * 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.
  48511. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  48512. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  48513. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  48514. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  48515. */
  48516. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  48517. var indices = sourceMesh.getIndices();
  48518. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48519. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48520. var position = options.position || BABYLON.Vector3.Zero();
  48521. var normal = options.normal || BABYLON.Vector3.Up();
  48522. var size = options.size || BABYLON.Vector3.One();
  48523. var angle = options.angle || 0;
  48524. // Getting correct rotation
  48525. if (!normal) {
  48526. var target = new BABYLON.Vector3(0, 0, 1);
  48527. var camera = sourceMesh.getScene().activeCamera;
  48528. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  48529. normal = camera.globalPosition.subtract(cameraWorldTarget);
  48530. }
  48531. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  48532. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  48533. var pitch = Math.atan2(normal.y, len);
  48534. // Matrix
  48535. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  48536. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  48537. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  48538. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  48539. var vertexData = new BABYLON.VertexData();
  48540. vertexData.indices = [];
  48541. vertexData.positions = [];
  48542. vertexData.normals = [];
  48543. vertexData.uvs = [];
  48544. var currentVertexDataIndex = 0;
  48545. var extractDecalVector3 = function (indexId) {
  48546. var result = new BABYLON.PositionNormalVertex();
  48547. if (!indices || !positions || !normals) {
  48548. return result;
  48549. }
  48550. var vertexId = indices[indexId];
  48551. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  48552. // Send vector to decal local world
  48553. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  48554. // Get normal
  48555. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  48556. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  48557. return result;
  48558. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  48559. var clip = function (vertices, axis) {
  48560. if (vertices.length === 0) {
  48561. return vertices;
  48562. }
  48563. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  48564. var clipVertices = function (v0, v1) {
  48565. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  48566. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  48567. };
  48568. var result = new Array();
  48569. for (var index = 0; index < vertices.length; index += 3) {
  48570. var v1Out;
  48571. var v2Out;
  48572. var v3Out;
  48573. var total = 0;
  48574. var nV1 = null;
  48575. var nV2 = null;
  48576. var nV3 = null;
  48577. var nV4 = null;
  48578. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  48579. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  48580. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  48581. v1Out = d1 > 0;
  48582. v2Out = d2 > 0;
  48583. v3Out = d3 > 0;
  48584. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  48585. switch (total) {
  48586. case 0:
  48587. result.push(vertices[index]);
  48588. result.push(vertices[index + 1]);
  48589. result.push(vertices[index + 2]);
  48590. break;
  48591. case 1:
  48592. if (v1Out) {
  48593. nV1 = vertices[index + 1];
  48594. nV2 = vertices[index + 2];
  48595. nV3 = clipVertices(vertices[index], nV1);
  48596. nV4 = clipVertices(vertices[index], nV2);
  48597. }
  48598. if (v2Out) {
  48599. nV1 = vertices[index];
  48600. nV2 = vertices[index + 2];
  48601. nV3 = clipVertices(vertices[index + 1], nV1);
  48602. nV4 = clipVertices(vertices[index + 1], nV2);
  48603. result.push(nV3);
  48604. result.push(nV2.clone());
  48605. result.push(nV1.clone());
  48606. result.push(nV2.clone());
  48607. result.push(nV3.clone());
  48608. result.push(nV4);
  48609. break;
  48610. }
  48611. if (v3Out) {
  48612. nV1 = vertices[index];
  48613. nV2 = vertices[index + 1];
  48614. nV3 = clipVertices(vertices[index + 2], nV1);
  48615. nV4 = clipVertices(vertices[index + 2], nV2);
  48616. }
  48617. if (nV1 && nV2 && nV3 && nV4) {
  48618. result.push(nV1.clone());
  48619. result.push(nV2.clone());
  48620. result.push(nV3);
  48621. result.push(nV4);
  48622. result.push(nV3.clone());
  48623. result.push(nV2.clone());
  48624. }
  48625. break;
  48626. case 2:
  48627. if (!v1Out) {
  48628. nV1 = vertices[index].clone();
  48629. nV2 = clipVertices(nV1, vertices[index + 1]);
  48630. nV3 = clipVertices(nV1, vertices[index + 2]);
  48631. result.push(nV1);
  48632. result.push(nV2);
  48633. result.push(nV3);
  48634. }
  48635. if (!v2Out) {
  48636. nV1 = vertices[index + 1].clone();
  48637. nV2 = clipVertices(nV1, vertices[index + 2]);
  48638. nV3 = clipVertices(nV1, vertices[index]);
  48639. result.push(nV1);
  48640. result.push(nV2);
  48641. result.push(nV3);
  48642. }
  48643. if (!v3Out) {
  48644. nV1 = vertices[index + 2].clone();
  48645. nV2 = clipVertices(nV1, vertices[index]);
  48646. nV3 = clipVertices(nV1, vertices[index + 1]);
  48647. result.push(nV1);
  48648. result.push(nV2);
  48649. result.push(nV3);
  48650. }
  48651. break;
  48652. case 3:
  48653. break;
  48654. }
  48655. }
  48656. return result;
  48657. };
  48658. for (var index = 0; index < indices.length; index += 3) {
  48659. var faceVertices = new Array();
  48660. faceVertices.push(extractDecalVector3(index));
  48661. faceVertices.push(extractDecalVector3(index + 1));
  48662. faceVertices.push(extractDecalVector3(index + 2));
  48663. // Clip
  48664. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  48665. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  48666. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  48667. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  48668. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  48669. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  48670. if (faceVertices.length === 0) {
  48671. continue;
  48672. }
  48673. // Add UVs and get back to world
  48674. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  48675. var vertex = faceVertices[vIndex];
  48676. //TODO check for Int32Array | Uint32Array | Uint16Array
  48677. vertexData.indices.push(currentVertexDataIndex);
  48678. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  48679. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  48680. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  48681. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  48682. currentVertexDataIndex++;
  48683. }
  48684. }
  48685. // Return mesh
  48686. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  48687. vertexData.applyToMesh(decal);
  48688. decal.position = position.clone();
  48689. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  48690. return decal;
  48691. };
  48692. // Privates
  48693. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  48694. // extrusion geometry
  48695. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  48696. var tangents = path3D.getTangents();
  48697. var normals = path3D.getNormals();
  48698. var binormals = path3D.getBinormals();
  48699. var distances = path3D.getDistances();
  48700. var angle = 0;
  48701. var returnScale = function () { return scale !== null ? scale : 1; };
  48702. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  48703. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  48704. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  48705. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48706. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48707. for (var i = 0; i < curve.length; i++) {
  48708. var shapePath = new Array();
  48709. var angleStep = rotate(i, distances[i]);
  48710. var scaleRatio = scl(i, distances[i]);
  48711. for (var p = 0; p < shape.length; p++) {
  48712. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  48713. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  48714. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  48715. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  48716. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  48717. shapePath[p] = rotated;
  48718. }
  48719. shapePaths[index] = shapePath;
  48720. angle += angleStep;
  48721. index++;
  48722. }
  48723. // cap
  48724. var capPath = function (shapePath) {
  48725. var pointCap = Array();
  48726. var barycenter = BABYLON.Vector3.Zero();
  48727. var i;
  48728. for (i = 0; i < shapePath.length; i++) {
  48729. barycenter.addInPlace(shapePath[i]);
  48730. }
  48731. barycenter.scaleInPlace(1.0 / shapePath.length);
  48732. for (i = 0; i < shapePath.length; i++) {
  48733. pointCap.push(barycenter);
  48734. }
  48735. return pointCap;
  48736. };
  48737. switch (cap) {
  48738. case BABYLON.Mesh.NO_CAP:
  48739. break;
  48740. case BABYLON.Mesh.CAP_START:
  48741. shapePaths[0] = capPath(shapePaths[2]);
  48742. shapePaths[1] = shapePaths[2];
  48743. break;
  48744. case BABYLON.Mesh.CAP_END:
  48745. shapePaths[index] = shapePaths[index - 1];
  48746. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48747. break;
  48748. case BABYLON.Mesh.CAP_ALL:
  48749. shapePaths[0] = capPath(shapePaths[2]);
  48750. shapePaths[1] = shapePaths[2];
  48751. shapePaths[index] = shapePaths[index - 1];
  48752. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48753. break;
  48754. default:
  48755. break;
  48756. }
  48757. return shapePaths;
  48758. };
  48759. var path3D;
  48760. var pathArray;
  48761. if (instance) {
  48762. path3D = (instance.path3D).update(curve);
  48763. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  48764. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  48765. return instance;
  48766. }
  48767. // extruded shape creation
  48768. path3D = new BABYLON.Path3D(curve);
  48769. var newShapePaths = new Array();
  48770. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48771. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  48772. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  48773. extrudedGeneric.pathArray = pathArray;
  48774. extrudedGeneric.path3D = path3D;
  48775. extrudedGeneric.cap = cap;
  48776. return extrudedGeneric;
  48777. };
  48778. return MeshBuilder;
  48779. }());
  48780. BABYLON.MeshBuilder = MeshBuilder;
  48781. })(BABYLON || (BABYLON = {}));
  48782. //# sourceMappingURL=babylon.meshBuilder.js.map
  48783. var BABYLON;
  48784. (function (BABYLON) {
  48785. var AudioEngine = /** @class */ (function () {
  48786. function AudioEngine() {
  48787. this._audioContext = null;
  48788. this._audioContextInitialized = false;
  48789. this.canUseWebAudio = false;
  48790. this.WarnedWebAudioUnsupported = false;
  48791. this.unlocked = false;
  48792. this.isMP3supported = false;
  48793. this.isOGGsupported = false;
  48794. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  48795. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  48796. this.canUseWebAudio = true;
  48797. }
  48798. var audioElem = document.createElement('audio');
  48799. try {
  48800. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  48801. this.isMP3supported = true;
  48802. }
  48803. }
  48804. catch (e) {
  48805. // protect error during capability check.
  48806. }
  48807. try {
  48808. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  48809. this.isOGGsupported = true;
  48810. }
  48811. }
  48812. catch (e) {
  48813. // protect error during capability check.
  48814. }
  48815. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  48816. this._unlockiOSaudio();
  48817. }
  48818. else {
  48819. this.unlocked = true;
  48820. }
  48821. }
  48822. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  48823. get: function () {
  48824. if (!this._audioContextInitialized) {
  48825. this._initializeAudioContext();
  48826. }
  48827. return this._audioContext;
  48828. },
  48829. enumerable: true,
  48830. configurable: true
  48831. });
  48832. AudioEngine.prototype._unlockiOSaudio = function () {
  48833. var _this = this;
  48834. var unlockaudio = function () {
  48835. if (!_this.audioContext) {
  48836. return;
  48837. }
  48838. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  48839. var source = _this.audioContext.createBufferSource();
  48840. source.buffer = buffer;
  48841. source.connect(_this.audioContext.destination);
  48842. source.start(0);
  48843. setTimeout(function () {
  48844. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  48845. _this.unlocked = true;
  48846. window.removeEventListener('touchend', unlockaudio, false);
  48847. if (_this.onAudioUnlocked) {
  48848. _this.onAudioUnlocked();
  48849. }
  48850. }
  48851. }, 0);
  48852. };
  48853. window.addEventListener('touchend', unlockaudio, false);
  48854. };
  48855. AudioEngine.prototype._initializeAudioContext = function () {
  48856. try {
  48857. if (this.canUseWebAudio) {
  48858. this._audioContext = new AudioContext();
  48859. // create a global volume gain node
  48860. this.masterGain = this._audioContext.createGain();
  48861. this.masterGain.gain.value = 1;
  48862. this.masterGain.connect(this._audioContext.destination);
  48863. this._audioContextInitialized = true;
  48864. }
  48865. }
  48866. catch (e) {
  48867. this.canUseWebAudio = false;
  48868. BABYLON.Tools.Error("Web Audio: " + e.message);
  48869. }
  48870. };
  48871. AudioEngine.prototype.dispose = function () {
  48872. if (this.canUseWebAudio && this._audioContextInitialized) {
  48873. if (this._connectedAnalyser && this._audioContext) {
  48874. this._connectedAnalyser.stopDebugCanvas();
  48875. this._connectedAnalyser.dispose();
  48876. this.masterGain.disconnect();
  48877. this.masterGain.connect(this._audioContext.destination);
  48878. this._connectedAnalyser = null;
  48879. }
  48880. this.masterGain.gain.value = 1;
  48881. }
  48882. this.WarnedWebAudioUnsupported = false;
  48883. };
  48884. AudioEngine.prototype.getGlobalVolume = function () {
  48885. if (this.canUseWebAudio && this._audioContextInitialized) {
  48886. return this.masterGain.gain.value;
  48887. }
  48888. else {
  48889. return -1;
  48890. }
  48891. };
  48892. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  48893. if (this.canUseWebAudio && this._audioContextInitialized) {
  48894. this.masterGain.gain.value = newVolume;
  48895. }
  48896. };
  48897. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  48898. if (this._connectedAnalyser) {
  48899. this._connectedAnalyser.stopDebugCanvas();
  48900. }
  48901. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  48902. this._connectedAnalyser = analyser;
  48903. this.masterGain.disconnect();
  48904. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  48905. }
  48906. };
  48907. return AudioEngine;
  48908. }());
  48909. BABYLON.AudioEngine = AudioEngine;
  48910. })(BABYLON || (BABYLON = {}));
  48911. //# sourceMappingURL=babylon.audioEngine.js.map
  48912. var BABYLON;
  48913. (function (BABYLON) {
  48914. var Sound = /** @class */ (function () {
  48915. /**
  48916. * Create a sound and attach it to a scene
  48917. * @param name Name of your sound
  48918. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  48919. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  48920. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  48921. */
  48922. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  48923. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  48924. var _this = this;
  48925. this.autoplay = false;
  48926. this.loop = false;
  48927. this.useCustomAttenuation = false;
  48928. this.spatialSound = false;
  48929. this.refDistance = 1;
  48930. this.rolloffFactor = 1;
  48931. this.maxDistance = 100;
  48932. this.distanceModel = "linear";
  48933. this._panningModel = "equalpower";
  48934. this._playbackRate = 1;
  48935. this._streaming = false;
  48936. this._startTime = 0;
  48937. this._startOffset = 0;
  48938. this._position = BABYLON.Vector3.Zero();
  48939. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  48940. this._volume = 1;
  48941. this._isReadyToPlay = false;
  48942. this.isPlaying = false;
  48943. this.isPaused = false;
  48944. this._isDirectional = false;
  48945. // Used if you'd like to create a directional sound.
  48946. // If not set, the sound will be omnidirectional
  48947. this._coneInnerAngle = 360;
  48948. this._coneOuterAngle = 360;
  48949. this._coneOuterGain = 0;
  48950. this._isOutputConnected = false;
  48951. this._urlType = "Unknown";
  48952. this.name = name;
  48953. this._scene = scene;
  48954. this._readyToPlayCallback = readyToPlayCallback;
  48955. // Default custom attenuation function is a linear attenuation
  48956. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  48957. if (currentDistance < maxDistance) {
  48958. return currentVolume * (1 - currentDistance / maxDistance);
  48959. }
  48960. else {
  48961. return 0;
  48962. }
  48963. };
  48964. if (options) {
  48965. this.autoplay = options.autoplay || false;
  48966. this.loop = options.loop || false;
  48967. // if volume === 0, we need another way to check this option
  48968. if (options.volume !== undefined) {
  48969. this._volume = options.volume;
  48970. }
  48971. this.spatialSound = options.spatialSound || false;
  48972. this.maxDistance = options.maxDistance || 100;
  48973. this.useCustomAttenuation = options.useCustomAttenuation || false;
  48974. this.rolloffFactor = options.rolloffFactor || 1;
  48975. this.refDistance = options.refDistance || 1;
  48976. this.distanceModel = options.distanceModel || "linear";
  48977. this._playbackRate = options.playbackRate || 1;
  48978. this._streaming = options.streaming || false;
  48979. }
  48980. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48981. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  48982. this._soundGain.gain.value = this._volume;
  48983. this._inputAudioNode = this._soundGain;
  48984. this._ouputAudioNode = this._soundGain;
  48985. if (this.spatialSound) {
  48986. this._createSpatialParameters();
  48987. }
  48988. this._scene.mainSoundTrack.AddSound(this);
  48989. var validParameter = true;
  48990. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  48991. if (urlOrArrayBuffer) {
  48992. if (typeof (urlOrArrayBuffer) === "string")
  48993. this._urlType = "String";
  48994. if (Array.isArray(urlOrArrayBuffer))
  48995. this._urlType = "Array";
  48996. if (urlOrArrayBuffer instanceof ArrayBuffer)
  48997. this._urlType = "ArrayBuffer";
  48998. var urls = [];
  48999. var codecSupportedFound = false;
  49000. switch (this._urlType) {
  49001. case "ArrayBuffer":
  49002. if (urlOrArrayBuffer.byteLength > 0) {
  49003. codecSupportedFound = true;
  49004. this._soundLoaded(urlOrArrayBuffer);
  49005. }
  49006. break;
  49007. case "String":
  49008. urls.push(urlOrArrayBuffer);
  49009. case "Array":
  49010. if (urls.length === 0)
  49011. urls = urlOrArrayBuffer;
  49012. // If we found a supported format, we load it immediately and stop the loop
  49013. for (var i = 0; i < urls.length; i++) {
  49014. var url = urls[i];
  49015. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  49016. codecSupportedFound = true;
  49017. }
  49018. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  49019. codecSupportedFound = true;
  49020. }
  49021. if (url.indexOf(".wav", url.length - 4) !== -1) {
  49022. codecSupportedFound = true;
  49023. }
  49024. if (url.indexOf("blob:") !== -1) {
  49025. codecSupportedFound = true;
  49026. }
  49027. if (codecSupportedFound) {
  49028. // Loading sound using XHR2
  49029. if (!this._streaming) {
  49030. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  49031. }
  49032. else {
  49033. this._htmlAudioElement = new Audio(url);
  49034. this._htmlAudioElement.controls = false;
  49035. this._htmlAudioElement.loop = this.loop;
  49036. this._htmlAudioElement.crossOrigin = "anonymous";
  49037. this._htmlAudioElement.preload = "auto";
  49038. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  49039. _this._isReadyToPlay = true;
  49040. if (_this.autoplay) {
  49041. _this.play();
  49042. }
  49043. if (_this._readyToPlayCallback) {
  49044. _this._readyToPlayCallback();
  49045. }
  49046. });
  49047. document.body.appendChild(this._htmlAudioElement);
  49048. }
  49049. break;
  49050. }
  49051. }
  49052. break;
  49053. default:
  49054. validParameter = false;
  49055. break;
  49056. }
  49057. if (!validParameter) {
  49058. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  49059. }
  49060. else {
  49061. if (!codecSupportedFound) {
  49062. this._isReadyToPlay = true;
  49063. // Simulating a ready to play event to avoid breaking code path
  49064. if (this._readyToPlayCallback) {
  49065. window.setTimeout(function () {
  49066. if (_this._readyToPlayCallback) {
  49067. _this._readyToPlayCallback();
  49068. }
  49069. }, 1000);
  49070. }
  49071. }
  49072. }
  49073. }
  49074. }
  49075. else {
  49076. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  49077. this._scene.mainSoundTrack.AddSound(this);
  49078. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  49079. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  49080. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  49081. }
  49082. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  49083. if (this._readyToPlayCallback) {
  49084. window.setTimeout(function () {
  49085. if (_this._readyToPlayCallback) {
  49086. _this._readyToPlayCallback();
  49087. }
  49088. }, 1000);
  49089. }
  49090. }
  49091. }
  49092. Sound.prototype.dispose = function () {
  49093. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  49094. if (this.isPlaying) {
  49095. this.stop();
  49096. }
  49097. this._isReadyToPlay = false;
  49098. if (this.soundTrackId === -1) {
  49099. this._scene.mainSoundTrack.RemoveSound(this);
  49100. }
  49101. else {
  49102. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  49103. }
  49104. if (this._soundGain) {
  49105. this._soundGain.disconnect();
  49106. this._soundGain = null;
  49107. }
  49108. if (this._soundPanner) {
  49109. this._soundPanner.disconnect();
  49110. this._soundPanner = null;
  49111. }
  49112. if (this._soundSource) {
  49113. this._soundSource.disconnect();
  49114. this._soundSource = null;
  49115. }
  49116. this._audioBuffer = null;
  49117. if (this._htmlAudioElement) {
  49118. this._htmlAudioElement.pause();
  49119. this._htmlAudioElement.src = "";
  49120. document.body.removeChild(this._htmlAudioElement);
  49121. }
  49122. if (this._connectedMesh && this._registerFunc) {
  49123. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49124. this._connectedMesh = null;
  49125. }
  49126. }
  49127. };
  49128. Sound.prototype.isReady = function () {
  49129. return this._isReadyToPlay;
  49130. };
  49131. Sound.prototype._soundLoaded = function (audioData) {
  49132. var _this = this;
  49133. if (!BABYLON.Engine.audioEngine.audioContext) {
  49134. return;
  49135. }
  49136. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  49137. _this._audioBuffer = buffer;
  49138. _this._isReadyToPlay = true;
  49139. if (_this.autoplay) {
  49140. _this.play();
  49141. }
  49142. if (_this._readyToPlayCallback) {
  49143. _this._readyToPlayCallback();
  49144. }
  49145. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  49146. };
  49147. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  49148. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49149. this._audioBuffer = audioBuffer;
  49150. this._isReadyToPlay = true;
  49151. }
  49152. };
  49153. Sound.prototype.updateOptions = function (options) {
  49154. if (options) {
  49155. this.loop = options.loop || this.loop;
  49156. this.maxDistance = options.maxDistance || this.maxDistance;
  49157. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  49158. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  49159. this.refDistance = options.refDistance || this.refDistance;
  49160. this.distanceModel = options.distanceModel || this.distanceModel;
  49161. this._playbackRate = options.playbackRate || this._playbackRate;
  49162. this._updateSpatialParameters();
  49163. if (this.isPlaying) {
  49164. if (this._streaming) {
  49165. this._htmlAudioElement.playbackRate = this._playbackRate;
  49166. }
  49167. else {
  49168. if (this._soundSource) {
  49169. this._soundSource.playbackRate.value = this._playbackRate;
  49170. }
  49171. }
  49172. }
  49173. }
  49174. };
  49175. Sound.prototype._createSpatialParameters = function () {
  49176. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49177. if (this._scene.headphone) {
  49178. this._panningModel = "HRTF";
  49179. }
  49180. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  49181. this._updateSpatialParameters();
  49182. this._soundPanner.connect(this._ouputAudioNode);
  49183. this._inputAudioNode = this._soundPanner;
  49184. }
  49185. };
  49186. Sound.prototype._updateSpatialParameters = function () {
  49187. if (this.spatialSound && this._soundPanner) {
  49188. if (this.useCustomAttenuation) {
  49189. // Tricks to disable in a way embedded Web Audio attenuation
  49190. this._soundPanner.distanceModel = "linear";
  49191. this._soundPanner.maxDistance = Number.MAX_VALUE;
  49192. this._soundPanner.refDistance = 1;
  49193. this._soundPanner.rolloffFactor = 1;
  49194. this._soundPanner.panningModel = this._panningModel;
  49195. }
  49196. else {
  49197. this._soundPanner.distanceModel = this.distanceModel;
  49198. this._soundPanner.maxDistance = this.maxDistance;
  49199. this._soundPanner.refDistance = this.refDistance;
  49200. this._soundPanner.rolloffFactor = this.rolloffFactor;
  49201. this._soundPanner.panningModel = this._panningModel;
  49202. }
  49203. }
  49204. };
  49205. Sound.prototype.switchPanningModelToHRTF = function () {
  49206. this._panningModel = "HRTF";
  49207. this._switchPanningModel();
  49208. };
  49209. Sound.prototype.switchPanningModelToEqualPower = function () {
  49210. this._panningModel = "equalpower";
  49211. this._switchPanningModel();
  49212. };
  49213. Sound.prototype._switchPanningModel = function () {
  49214. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49215. this._soundPanner.panningModel = this._panningModel;
  49216. }
  49217. };
  49218. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  49219. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49220. if (this._isOutputConnected) {
  49221. this._ouputAudioNode.disconnect();
  49222. }
  49223. this._ouputAudioNode.connect(soundTrackAudioNode);
  49224. this._isOutputConnected = true;
  49225. }
  49226. };
  49227. /**
  49228. * Transform this sound into a directional source
  49229. * @param coneInnerAngle Size of the inner cone in degree
  49230. * @param coneOuterAngle Size of the outer cone in degree
  49231. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  49232. */
  49233. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  49234. if (coneOuterAngle < coneInnerAngle) {
  49235. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  49236. return;
  49237. }
  49238. this._coneInnerAngle = coneInnerAngle;
  49239. this._coneOuterAngle = coneOuterAngle;
  49240. this._coneOuterGain = coneOuterGain;
  49241. this._isDirectional = true;
  49242. if (this.isPlaying && this.loop) {
  49243. this.stop();
  49244. this.play();
  49245. }
  49246. };
  49247. Sound.prototype.setPosition = function (newPosition) {
  49248. this._position = newPosition;
  49249. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49250. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  49251. }
  49252. };
  49253. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  49254. this._localDirection = newLocalDirection;
  49255. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  49256. this._updateDirection();
  49257. }
  49258. };
  49259. Sound.prototype._updateDirection = function () {
  49260. if (!this._connectedMesh || !this._soundPanner) {
  49261. return;
  49262. }
  49263. var mat = this._connectedMesh.getWorldMatrix();
  49264. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  49265. direction.normalize();
  49266. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  49267. };
  49268. Sound.prototype.updateDistanceFromListener = function () {
  49269. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  49270. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  49271. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  49272. }
  49273. };
  49274. Sound.prototype.setAttenuationFunction = function (callback) {
  49275. this._customAttenuationFunction = callback;
  49276. };
  49277. /**
  49278. * Play the sound
  49279. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  49280. * @param offset (optional) Start the sound setting it at a specific time
  49281. */
  49282. Sound.prototype.play = function (time, offset) {
  49283. var _this = this;
  49284. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  49285. try {
  49286. if (this._startOffset < 0) {
  49287. time = -this._startOffset;
  49288. this._startOffset = 0;
  49289. }
  49290. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  49291. if (!this._soundSource || !this._streamingSource) {
  49292. if (this.spatialSound && this._soundPanner) {
  49293. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  49294. if (this._isDirectional) {
  49295. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  49296. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  49297. this._soundPanner.coneOuterGain = this._coneOuterGain;
  49298. if (this._connectedMesh) {
  49299. this._updateDirection();
  49300. }
  49301. else {
  49302. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  49303. }
  49304. }
  49305. }
  49306. }
  49307. if (this._streaming) {
  49308. if (!this._streamingSource) {
  49309. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  49310. this._htmlAudioElement.onended = function () { _this._onended(); };
  49311. this._htmlAudioElement.playbackRate = this._playbackRate;
  49312. }
  49313. this._streamingSource.disconnect();
  49314. this._streamingSource.connect(this._inputAudioNode);
  49315. this._htmlAudioElement.play();
  49316. }
  49317. else {
  49318. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  49319. this._soundSource.buffer = this._audioBuffer;
  49320. this._soundSource.connect(this._inputAudioNode);
  49321. this._soundSource.loop = this.loop;
  49322. this._soundSource.playbackRate.value = this._playbackRate;
  49323. this._soundSource.onended = function () { _this._onended(); };
  49324. if (this._soundSource.buffer) {
  49325. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  49326. }
  49327. }
  49328. this._startTime = startTime;
  49329. this.isPlaying = true;
  49330. this.isPaused = false;
  49331. }
  49332. catch (ex) {
  49333. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  49334. }
  49335. }
  49336. };
  49337. Sound.prototype._onended = function () {
  49338. this.isPlaying = false;
  49339. if (this.onended) {
  49340. this.onended();
  49341. }
  49342. };
  49343. /**
  49344. * Stop the sound
  49345. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  49346. */
  49347. Sound.prototype.stop = function (time) {
  49348. if (this.isPlaying) {
  49349. if (this._streaming) {
  49350. this._htmlAudioElement.pause();
  49351. // Test needed for Firefox or it will generate an Invalid State Error
  49352. if (this._htmlAudioElement.currentTime > 0) {
  49353. this._htmlAudioElement.currentTime = 0;
  49354. }
  49355. }
  49356. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  49357. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  49358. this._soundSource.stop(stopTime);
  49359. this._soundSource.onended = function () { };
  49360. if (!this.isPaused) {
  49361. this._startOffset = 0;
  49362. }
  49363. }
  49364. this.isPlaying = false;
  49365. }
  49366. };
  49367. Sound.prototype.pause = function () {
  49368. if (this.isPlaying) {
  49369. this.isPaused = true;
  49370. if (this._streaming) {
  49371. this._htmlAudioElement.pause();
  49372. }
  49373. else if (BABYLON.Engine.audioEngine.audioContext) {
  49374. this.stop(0);
  49375. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  49376. }
  49377. }
  49378. };
  49379. Sound.prototype.setVolume = function (newVolume, time) {
  49380. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  49381. if (time && BABYLON.Engine.audioEngine.audioContext) {
  49382. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  49383. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  49384. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  49385. }
  49386. else {
  49387. this._soundGain.gain.value = newVolume;
  49388. }
  49389. }
  49390. this._volume = newVolume;
  49391. };
  49392. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  49393. this._playbackRate = newPlaybackRate;
  49394. if (this.isPlaying) {
  49395. if (this._streaming) {
  49396. this._htmlAudioElement.playbackRate = this._playbackRate;
  49397. }
  49398. else if (this._soundSource) {
  49399. this._soundSource.playbackRate.value = this._playbackRate;
  49400. }
  49401. }
  49402. };
  49403. Sound.prototype.getVolume = function () {
  49404. return this._volume;
  49405. };
  49406. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  49407. var _this = this;
  49408. if (this._connectedMesh && this._registerFunc) {
  49409. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49410. this._registerFunc = null;
  49411. }
  49412. this._connectedMesh = meshToConnectTo;
  49413. if (!this.spatialSound) {
  49414. this.spatialSound = true;
  49415. this._createSpatialParameters();
  49416. if (this.isPlaying && this.loop) {
  49417. this.stop();
  49418. this.play();
  49419. }
  49420. }
  49421. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  49422. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  49423. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  49424. };
  49425. Sound.prototype.detachFromMesh = function () {
  49426. if (this._connectedMesh && this._registerFunc) {
  49427. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49428. this._registerFunc = null;
  49429. this._connectedMesh = null;
  49430. }
  49431. };
  49432. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  49433. if (!node.getBoundingInfo) {
  49434. return;
  49435. }
  49436. var mesh = node;
  49437. var boundingInfo = mesh.getBoundingInfo();
  49438. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  49439. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  49440. this._updateDirection();
  49441. }
  49442. };
  49443. Sound.prototype.clone = function () {
  49444. var _this = this;
  49445. if (!this._streaming) {
  49446. var setBufferAndRun = function () {
  49447. if (_this._isReadyToPlay) {
  49448. clonedSound._audioBuffer = _this.getAudioBuffer();
  49449. clonedSound._isReadyToPlay = true;
  49450. if (clonedSound.autoplay) {
  49451. clonedSound.play();
  49452. }
  49453. }
  49454. else {
  49455. window.setTimeout(setBufferAndRun, 300);
  49456. }
  49457. };
  49458. var currentOptions = {
  49459. autoplay: this.autoplay, loop: this.loop,
  49460. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  49461. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  49462. refDistance: this.refDistance, distanceModel: this.distanceModel
  49463. };
  49464. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  49465. if (this.useCustomAttenuation) {
  49466. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  49467. }
  49468. clonedSound.setPosition(this._position);
  49469. clonedSound.setPlaybackRate(this._playbackRate);
  49470. setBufferAndRun();
  49471. return clonedSound;
  49472. }
  49473. else {
  49474. return null;
  49475. }
  49476. };
  49477. Sound.prototype.getAudioBuffer = function () {
  49478. return this._audioBuffer;
  49479. };
  49480. Sound.prototype.serialize = function () {
  49481. var serializationObject = {
  49482. name: this.name,
  49483. url: this.name,
  49484. autoplay: this.autoplay,
  49485. loop: this.loop,
  49486. volume: this._volume,
  49487. spatialSound: this.spatialSound,
  49488. maxDistance: this.maxDistance,
  49489. rolloffFactor: this.rolloffFactor,
  49490. refDistance: this.refDistance,
  49491. distanceModel: this.distanceModel,
  49492. playbackRate: this._playbackRate,
  49493. panningModel: this._panningModel,
  49494. soundTrackId: this.soundTrackId
  49495. };
  49496. if (this.spatialSound) {
  49497. if (this._connectedMesh)
  49498. serializationObject.connectedMeshId = this._connectedMesh.id;
  49499. serializationObject.position = this._position.asArray();
  49500. serializationObject.refDistance = this.refDistance;
  49501. serializationObject.distanceModel = this.distanceModel;
  49502. serializationObject.isDirectional = this._isDirectional;
  49503. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  49504. serializationObject.coneInnerAngle = this._coneInnerAngle;
  49505. serializationObject.coneOuterAngle = this._coneOuterAngle;
  49506. serializationObject.coneOuterGain = this._coneOuterGain;
  49507. }
  49508. return serializationObject;
  49509. };
  49510. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  49511. var soundName = parsedSound.name;
  49512. var soundUrl;
  49513. if (parsedSound.url) {
  49514. soundUrl = rootUrl + parsedSound.url;
  49515. }
  49516. else {
  49517. soundUrl = rootUrl + soundName;
  49518. }
  49519. var options = {
  49520. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  49521. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  49522. rolloffFactor: parsedSound.rolloffFactor,
  49523. refDistance: parsedSound.refDistance,
  49524. distanceModel: parsedSound.distanceModel,
  49525. playbackRate: parsedSound.playbackRate
  49526. };
  49527. var newSound;
  49528. if (!sourceSound) {
  49529. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  49530. scene._addPendingData(newSound);
  49531. }
  49532. else {
  49533. var setBufferAndRun = function () {
  49534. if (sourceSound._isReadyToPlay) {
  49535. newSound._audioBuffer = sourceSound.getAudioBuffer();
  49536. newSound._isReadyToPlay = true;
  49537. if (newSound.autoplay) {
  49538. newSound.play();
  49539. }
  49540. }
  49541. else {
  49542. window.setTimeout(setBufferAndRun, 300);
  49543. }
  49544. };
  49545. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  49546. setBufferAndRun();
  49547. }
  49548. if (parsedSound.position) {
  49549. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  49550. newSound.setPosition(soundPosition);
  49551. }
  49552. if (parsedSound.isDirectional) {
  49553. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  49554. if (parsedSound.localDirectionToMesh) {
  49555. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  49556. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  49557. }
  49558. }
  49559. if (parsedSound.connectedMeshId) {
  49560. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  49561. if (connectedMesh) {
  49562. newSound.attachToMesh(connectedMesh);
  49563. }
  49564. }
  49565. return newSound;
  49566. };
  49567. return Sound;
  49568. }());
  49569. BABYLON.Sound = Sound;
  49570. })(BABYLON || (BABYLON = {}));
  49571. //# sourceMappingURL=babylon.sound.js.map
  49572. var BABYLON;
  49573. (function (BABYLON) {
  49574. var SoundTrack = /** @class */ (function () {
  49575. function SoundTrack(scene, options) {
  49576. this.id = -1;
  49577. this._isMainTrack = false;
  49578. this._isInitialized = false;
  49579. this._scene = scene;
  49580. this.soundCollection = new Array();
  49581. this._options = options;
  49582. if (!this._isMainTrack) {
  49583. this._scene.soundTracks.push(this);
  49584. this.id = this._scene.soundTracks.length - 1;
  49585. }
  49586. }
  49587. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  49588. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49589. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  49590. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  49591. if (this._options) {
  49592. if (this._options.volume) {
  49593. this._outputAudioNode.gain.value = this._options.volume;
  49594. }
  49595. if (this._options.mainTrack) {
  49596. this._isMainTrack = this._options.mainTrack;
  49597. }
  49598. }
  49599. this._isInitialized = true;
  49600. }
  49601. };
  49602. SoundTrack.prototype.dispose = function () {
  49603. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49604. if (this._connectedAnalyser) {
  49605. this._connectedAnalyser.stopDebugCanvas();
  49606. }
  49607. while (this.soundCollection.length) {
  49608. this.soundCollection[0].dispose();
  49609. }
  49610. if (this._outputAudioNode) {
  49611. this._outputAudioNode.disconnect();
  49612. }
  49613. this._outputAudioNode = null;
  49614. }
  49615. };
  49616. SoundTrack.prototype.AddSound = function (sound) {
  49617. if (!this._isInitialized) {
  49618. this._initializeSoundTrackAudioGraph();
  49619. }
  49620. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49621. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  49622. }
  49623. if (sound.soundTrackId) {
  49624. if (sound.soundTrackId === -1) {
  49625. this._scene.mainSoundTrack.RemoveSound(sound);
  49626. }
  49627. else {
  49628. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  49629. }
  49630. }
  49631. this.soundCollection.push(sound);
  49632. sound.soundTrackId = this.id;
  49633. };
  49634. SoundTrack.prototype.RemoveSound = function (sound) {
  49635. var index = this.soundCollection.indexOf(sound);
  49636. if (index !== -1) {
  49637. this.soundCollection.splice(index, 1);
  49638. }
  49639. };
  49640. SoundTrack.prototype.setVolume = function (newVolume) {
  49641. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49642. this._outputAudioNode.gain.value = newVolume;
  49643. }
  49644. };
  49645. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  49646. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49647. for (var i = 0; i < this.soundCollection.length; i++) {
  49648. this.soundCollection[i].switchPanningModelToHRTF();
  49649. }
  49650. }
  49651. };
  49652. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  49653. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49654. for (var i = 0; i < this.soundCollection.length; i++) {
  49655. this.soundCollection[i].switchPanningModelToEqualPower();
  49656. }
  49657. }
  49658. };
  49659. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  49660. if (this._connectedAnalyser) {
  49661. this._connectedAnalyser.stopDebugCanvas();
  49662. }
  49663. this._connectedAnalyser = analyser;
  49664. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49665. this._outputAudioNode.disconnect();
  49666. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  49667. }
  49668. };
  49669. return SoundTrack;
  49670. }());
  49671. BABYLON.SoundTrack = SoundTrack;
  49672. })(BABYLON || (BABYLON = {}));
  49673. //# sourceMappingURL=babylon.soundtrack.js.map
  49674. var BABYLON;
  49675. (function (BABYLON) {
  49676. var Analyser = /** @class */ (function () {
  49677. function Analyser(scene) {
  49678. this.SMOOTHING = 0.75;
  49679. this.FFT_SIZE = 512;
  49680. this.BARGRAPHAMPLITUDE = 256;
  49681. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  49682. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  49683. this._scene = scene;
  49684. this._audioEngine = BABYLON.Engine.audioEngine;
  49685. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  49686. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  49687. this._webAudioAnalyser.minDecibels = -140;
  49688. this._webAudioAnalyser.maxDecibels = 0;
  49689. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49690. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49691. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  49692. }
  49693. }
  49694. Analyser.prototype.getFrequencyBinCount = function () {
  49695. if (this._audioEngine.canUseWebAudio) {
  49696. return this._webAudioAnalyser.frequencyBinCount;
  49697. }
  49698. else {
  49699. return 0;
  49700. }
  49701. };
  49702. Analyser.prototype.getByteFrequencyData = function () {
  49703. if (this._audioEngine.canUseWebAudio) {
  49704. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49705. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49706. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  49707. }
  49708. return this._byteFreqs;
  49709. };
  49710. Analyser.prototype.getByteTimeDomainData = function () {
  49711. if (this._audioEngine.canUseWebAudio) {
  49712. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49713. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49714. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  49715. }
  49716. return this._byteTime;
  49717. };
  49718. Analyser.prototype.getFloatFrequencyData = function () {
  49719. if (this._audioEngine.canUseWebAudio) {
  49720. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49721. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49722. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  49723. }
  49724. return this._floatFreqs;
  49725. };
  49726. Analyser.prototype.drawDebugCanvas = function () {
  49727. var _this = this;
  49728. if (this._audioEngine.canUseWebAudio) {
  49729. if (!this._debugCanvas) {
  49730. this._debugCanvas = document.createElement("canvas");
  49731. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  49732. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  49733. this._debugCanvas.style.position = "absolute";
  49734. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  49735. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  49736. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  49737. document.body.appendChild(this._debugCanvas);
  49738. this._registerFunc = function () {
  49739. _this.drawDebugCanvas();
  49740. };
  49741. this._scene.registerBeforeRender(this._registerFunc);
  49742. }
  49743. if (this._registerFunc && this._debugCanvasContext) {
  49744. var workingArray = this.getByteFrequencyData();
  49745. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  49746. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  49747. // Draw the frequency domain chart.
  49748. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  49749. var value = workingArray[i];
  49750. var percent = value / this.BARGRAPHAMPLITUDE;
  49751. var height = this.DEBUGCANVASSIZE.height * percent;
  49752. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  49753. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  49754. var hue = i / this.getFrequencyBinCount() * 360;
  49755. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  49756. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  49757. }
  49758. }
  49759. }
  49760. };
  49761. Analyser.prototype.stopDebugCanvas = function () {
  49762. if (this._debugCanvas) {
  49763. if (this._registerFunc) {
  49764. this._scene.unregisterBeforeRender(this._registerFunc);
  49765. this._registerFunc = null;
  49766. }
  49767. document.body.removeChild(this._debugCanvas);
  49768. this._debugCanvas = null;
  49769. this._debugCanvasContext = null;
  49770. }
  49771. };
  49772. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  49773. if (this._audioEngine.canUseWebAudio) {
  49774. inputAudioNode.connect(this._webAudioAnalyser);
  49775. this._webAudioAnalyser.connect(outputAudioNode);
  49776. }
  49777. };
  49778. Analyser.prototype.dispose = function () {
  49779. if (this._audioEngine.canUseWebAudio) {
  49780. this._webAudioAnalyser.disconnect();
  49781. }
  49782. };
  49783. return Analyser;
  49784. }());
  49785. BABYLON.Analyser = Analyser;
  49786. })(BABYLON || (BABYLON = {}));
  49787. //# sourceMappingURL=babylon.analyser.js.map
  49788. var BABYLON;
  49789. (function (BABYLON) {
  49790. var CubeTexture = /** @class */ (function (_super) {
  49791. __extends(CubeTexture, _super);
  49792. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  49793. if (extensions === void 0) { extensions = null; }
  49794. if (noMipmap === void 0) { noMipmap = false; }
  49795. if (files === void 0) { files = null; }
  49796. if (onLoad === void 0) { onLoad = null; }
  49797. if (onError === void 0) { onError = null; }
  49798. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49799. if (prefiltered === void 0) { prefiltered = false; }
  49800. if (forcedExtension === void 0) { forcedExtension = null; }
  49801. var _this = _super.call(this, scene) || this;
  49802. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  49803. _this.name = rootUrl;
  49804. _this.url = rootUrl;
  49805. _this._noMipmap = noMipmap;
  49806. _this.hasAlpha = false;
  49807. _this._format = format;
  49808. _this._prefiltered = prefiltered;
  49809. _this.isCube = true;
  49810. _this._textureMatrix = BABYLON.Matrix.Identity();
  49811. if (prefiltered) {
  49812. _this.gammaSpace = false;
  49813. }
  49814. if (!rootUrl && !files) {
  49815. return _this;
  49816. }
  49817. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  49818. var lastDot = rootUrl.lastIndexOf(".");
  49819. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  49820. var isDDS = (extension === ".dds");
  49821. if (!files) {
  49822. if (!isDDS && !extensions) {
  49823. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  49824. }
  49825. files = [];
  49826. if (extensions) {
  49827. for (var index = 0; index < extensions.length; index++) {
  49828. files.push(rootUrl + extensions[index]);
  49829. }
  49830. }
  49831. }
  49832. if (!_this._texture) {
  49833. if (!scene.useDelayedTextureLoading) {
  49834. if (prefiltered) {
  49835. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  49836. }
  49837. else {
  49838. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  49839. }
  49840. }
  49841. else {
  49842. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  49843. }
  49844. }
  49845. else if (onLoad) {
  49846. if (_this._texture.isReady) {
  49847. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  49848. }
  49849. else {
  49850. _this._texture.onLoadedObservable.add(onLoad);
  49851. }
  49852. }
  49853. return _this;
  49854. }
  49855. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  49856. return new CubeTexture("", scene, null, noMipmap, files);
  49857. };
  49858. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  49859. if (forcedExtension === void 0) { forcedExtension = null; }
  49860. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  49861. };
  49862. // Methods
  49863. CubeTexture.prototype.delayLoad = function () {
  49864. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  49865. return;
  49866. }
  49867. var scene = this.getScene();
  49868. if (!scene) {
  49869. return;
  49870. }
  49871. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  49872. this._texture = this._getFromCache(this.url, this._noMipmap);
  49873. if (!this._texture) {
  49874. if (this._prefiltered) {
  49875. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  49876. }
  49877. else {
  49878. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  49879. }
  49880. }
  49881. };
  49882. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  49883. return this._textureMatrix;
  49884. };
  49885. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  49886. this._textureMatrix = value;
  49887. };
  49888. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49889. var texture = BABYLON.SerializationHelper.Parse(function () {
  49890. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  49891. }, parsedTexture, scene);
  49892. // Animations
  49893. if (parsedTexture.animations) {
  49894. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  49895. var parsedAnimation = parsedTexture.animations[animationIndex];
  49896. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  49897. }
  49898. }
  49899. return texture;
  49900. };
  49901. CubeTexture.prototype.clone = function () {
  49902. var _this = this;
  49903. return BABYLON.SerializationHelper.Clone(function () {
  49904. var scene = _this.getScene();
  49905. if (!scene) {
  49906. return _this;
  49907. }
  49908. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  49909. }, this);
  49910. };
  49911. return CubeTexture;
  49912. }(BABYLON.BaseTexture));
  49913. BABYLON.CubeTexture = CubeTexture;
  49914. })(BABYLON || (BABYLON = {}));
  49915. //# sourceMappingURL=babylon.cubeTexture.js.map
  49916. var BABYLON;
  49917. (function (BABYLON) {
  49918. var RenderTargetTexture = /** @class */ (function (_super) {
  49919. __extends(RenderTargetTexture, _super);
  49920. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  49921. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  49922. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49923. if (isCube === void 0) { isCube = false; }
  49924. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49925. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49926. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  49927. if (isMulti === void 0) { isMulti = false; }
  49928. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49929. _this.isCube = isCube;
  49930. /**
  49931. * Use this list to define the list of mesh you want to render.
  49932. */
  49933. _this.renderList = new Array();
  49934. _this.renderParticles = true;
  49935. _this.renderSprites = false;
  49936. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  49937. _this.ignoreCameraViewport = false;
  49938. // Events
  49939. /**
  49940. * An event triggered when the texture is unbind.
  49941. * @type {BABYLON.Observable}
  49942. */
  49943. _this.onBeforeBindObservable = new BABYLON.Observable();
  49944. /**
  49945. * An event triggered when the texture is unbind.
  49946. * @type {BABYLON.Observable}
  49947. */
  49948. _this.onAfterUnbindObservable = new BABYLON.Observable();
  49949. /**
  49950. * An event triggered before rendering the texture
  49951. * @type {BABYLON.Observable}
  49952. */
  49953. _this.onBeforeRenderObservable = new BABYLON.Observable();
  49954. /**
  49955. * An event triggered after rendering the texture
  49956. * @type {BABYLON.Observable}
  49957. */
  49958. _this.onAfterRenderObservable = new BABYLON.Observable();
  49959. /**
  49960. * An event triggered after the texture clear
  49961. * @type {BABYLON.Observable}
  49962. */
  49963. _this.onClearObservable = new BABYLON.Observable();
  49964. _this._currentRefreshId = -1;
  49965. _this._refreshRate = 1;
  49966. _this._samples = 1;
  49967. scene = _this.getScene();
  49968. if (!scene) {
  49969. return _this;
  49970. }
  49971. _this._engine = scene.getEngine();
  49972. _this.name = name;
  49973. _this.isRenderTarget = true;
  49974. _this._initialSizeParameter = size;
  49975. _this._processSizeParameter(size);
  49976. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  49977. });
  49978. _this._generateMipMaps = generateMipMaps ? true : false;
  49979. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  49980. // Rendering groups
  49981. _this._renderingManager = new BABYLON.RenderingManager(scene);
  49982. if (isMulti) {
  49983. return _this;
  49984. }
  49985. _this._renderTargetOptions = {
  49986. generateMipMaps: generateMipMaps,
  49987. type: type,
  49988. samplingMode: samplingMode,
  49989. generateDepthBuffer: generateDepthBuffer,
  49990. generateStencilBuffer: generateStencilBuffer
  49991. };
  49992. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  49993. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49994. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49995. }
  49996. if (isCube) {
  49997. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  49998. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  49999. _this._textureMatrix = BABYLON.Matrix.Identity();
  50000. }
  50001. else {
  50002. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  50003. }
  50004. return _this;
  50005. }
  50006. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  50007. get: function () {
  50008. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  50009. },
  50010. enumerable: true,
  50011. configurable: true
  50012. });
  50013. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  50014. get: function () {
  50015. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  50016. },
  50017. enumerable: true,
  50018. configurable: true
  50019. });
  50020. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  50021. get: function () {
  50022. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  50023. },
  50024. enumerable: true,
  50025. configurable: true
  50026. });
  50027. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  50028. set: function (callback) {
  50029. if (this._onAfterUnbindObserver) {
  50030. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  50031. }
  50032. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  50033. },
  50034. enumerable: true,
  50035. configurable: true
  50036. });
  50037. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  50038. set: function (callback) {
  50039. if (this._onBeforeRenderObserver) {
  50040. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50041. }
  50042. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50043. },
  50044. enumerable: true,
  50045. configurable: true
  50046. });
  50047. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  50048. set: function (callback) {
  50049. if (this._onAfterRenderObserver) {
  50050. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50051. }
  50052. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50053. },
  50054. enumerable: true,
  50055. configurable: true
  50056. });
  50057. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  50058. set: function (callback) {
  50059. if (this._onClearObserver) {
  50060. this.onClearObservable.remove(this._onClearObserver);
  50061. }
  50062. this._onClearObserver = this.onClearObservable.add(callback);
  50063. },
  50064. enumerable: true,
  50065. configurable: true
  50066. });
  50067. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  50068. get: function () {
  50069. return this._renderTargetOptions;
  50070. },
  50071. enumerable: true,
  50072. configurable: true
  50073. });
  50074. RenderTargetTexture.prototype._onRatioRescale = function () {
  50075. if (this._sizeRatio) {
  50076. this.resize(this._initialSizeParameter);
  50077. }
  50078. };
  50079. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  50080. if (size.ratio) {
  50081. this._sizeRatio = size.ratio;
  50082. this._size = {
  50083. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  50084. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  50085. };
  50086. }
  50087. else {
  50088. this._size = size;
  50089. }
  50090. };
  50091. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  50092. get: function () {
  50093. return this._samples;
  50094. },
  50095. set: function (value) {
  50096. if (this._samples === value) {
  50097. return;
  50098. }
  50099. var scene = this.getScene();
  50100. if (!scene) {
  50101. return;
  50102. }
  50103. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  50104. },
  50105. enumerable: true,
  50106. configurable: true
  50107. });
  50108. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  50109. this._currentRefreshId = -1;
  50110. };
  50111. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  50112. get: function () {
  50113. return this._refreshRate;
  50114. },
  50115. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  50116. set: function (value) {
  50117. this._refreshRate = value;
  50118. this.resetRefreshCounter();
  50119. },
  50120. enumerable: true,
  50121. configurable: true
  50122. });
  50123. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  50124. if (!this._postProcessManager) {
  50125. var scene = this.getScene();
  50126. if (!scene) {
  50127. return;
  50128. }
  50129. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  50130. this._postProcesses = new Array();
  50131. }
  50132. this._postProcesses.push(postProcess);
  50133. this._postProcesses[0].autoClear = false;
  50134. };
  50135. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  50136. if (!this._postProcesses) {
  50137. return;
  50138. }
  50139. if (dispose) {
  50140. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  50141. var postProcess = _a[_i];
  50142. postProcess.dispose();
  50143. }
  50144. }
  50145. this._postProcesses = [];
  50146. };
  50147. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  50148. if (!this._postProcesses) {
  50149. return;
  50150. }
  50151. var index = this._postProcesses.indexOf(postProcess);
  50152. if (index === -1) {
  50153. return;
  50154. }
  50155. this._postProcesses.splice(index, 1);
  50156. if (this._postProcesses.length > 0) {
  50157. this._postProcesses[0].autoClear = false;
  50158. }
  50159. };
  50160. RenderTargetTexture.prototype._shouldRender = function () {
  50161. if (this._currentRefreshId === -1) {
  50162. this._currentRefreshId = 1;
  50163. return true;
  50164. }
  50165. if (this.refreshRate === this._currentRefreshId) {
  50166. this._currentRefreshId = 1;
  50167. return true;
  50168. }
  50169. this._currentRefreshId++;
  50170. return false;
  50171. };
  50172. RenderTargetTexture.prototype.getRenderSize = function () {
  50173. if (this._size.width) {
  50174. return this._size.width;
  50175. }
  50176. return this._size;
  50177. };
  50178. RenderTargetTexture.prototype.getRenderWidth = function () {
  50179. if (this._size.width) {
  50180. return this._size.width;
  50181. }
  50182. return this._size;
  50183. };
  50184. RenderTargetTexture.prototype.getRenderHeight = function () {
  50185. if (this._size.width) {
  50186. return this._size.height;
  50187. }
  50188. return this._size;
  50189. };
  50190. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  50191. get: function () {
  50192. return true;
  50193. },
  50194. enumerable: true,
  50195. configurable: true
  50196. });
  50197. RenderTargetTexture.prototype.scale = function (ratio) {
  50198. var newSize = this.getRenderSize() * ratio;
  50199. this.resize(newSize);
  50200. };
  50201. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  50202. if (this.isCube) {
  50203. return this._textureMatrix;
  50204. }
  50205. return _super.prototype.getReflectionTextureMatrix.call(this);
  50206. };
  50207. RenderTargetTexture.prototype.resize = function (size) {
  50208. this.releaseInternalTexture();
  50209. var scene = this.getScene();
  50210. if (!scene) {
  50211. return;
  50212. }
  50213. this._processSizeParameter(size);
  50214. if (this.isCube) {
  50215. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  50216. }
  50217. else {
  50218. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  50219. }
  50220. };
  50221. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  50222. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  50223. if (dumpForDebug === void 0) { dumpForDebug = false; }
  50224. var scene = this.getScene();
  50225. if (!scene) {
  50226. return;
  50227. }
  50228. var engine = scene.getEngine();
  50229. if (this.useCameraPostProcesses !== undefined) {
  50230. useCameraPostProcess = this.useCameraPostProcesses;
  50231. }
  50232. if (this._waitingRenderList) {
  50233. this.renderList = [];
  50234. for (var index = 0; index < this._waitingRenderList.length; index++) {
  50235. var id = this._waitingRenderList[index];
  50236. var mesh_1 = scene.getMeshByID(id);
  50237. if (mesh_1) {
  50238. this.renderList.push(mesh_1);
  50239. }
  50240. }
  50241. delete this._waitingRenderList;
  50242. }
  50243. // Is predicate defined?
  50244. if (this.renderListPredicate) {
  50245. if (this.renderList) {
  50246. this.renderList.splice(0); // Clear previous renderList
  50247. }
  50248. else {
  50249. this.renderList = [];
  50250. }
  50251. var scene = this.getScene();
  50252. if (!scene) {
  50253. return;
  50254. }
  50255. var sceneMeshes = scene.meshes;
  50256. for (var index = 0; index < sceneMeshes.length; index++) {
  50257. var mesh = sceneMeshes[index];
  50258. if (this.renderListPredicate(mesh)) {
  50259. this.renderList.push(mesh);
  50260. }
  50261. }
  50262. }
  50263. this.onBeforeBindObservable.notifyObservers(this);
  50264. // Set custom projection.
  50265. // Needs to be before binding to prevent changing the aspect ratio.
  50266. var camera;
  50267. if (this.activeCamera) {
  50268. camera = this.activeCamera;
  50269. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  50270. if (this.activeCamera !== scene.activeCamera) {
  50271. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  50272. }
  50273. }
  50274. else {
  50275. camera = scene.activeCamera;
  50276. if (camera) {
  50277. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  50278. }
  50279. }
  50280. // Prepare renderingManager
  50281. this._renderingManager.reset();
  50282. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  50283. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  50284. var sceneRenderId = scene.getRenderId();
  50285. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  50286. var mesh = currentRenderList[meshIndex];
  50287. if (mesh) {
  50288. if (!mesh.isReady()) {
  50289. // Reset _currentRefreshId
  50290. this.resetRefreshCounter();
  50291. continue;
  50292. }
  50293. mesh._preActivateForIntermediateRendering(sceneRenderId);
  50294. var isMasked = void 0;
  50295. if (!this.renderList && camera) {
  50296. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  50297. }
  50298. else {
  50299. isMasked = false;
  50300. }
  50301. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  50302. mesh._activate(sceneRenderId);
  50303. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  50304. var subMesh = mesh.subMeshes[subIndex];
  50305. scene._activeIndices.addCount(subMesh.indexCount, false);
  50306. this._renderingManager.dispatch(subMesh);
  50307. }
  50308. }
  50309. }
  50310. }
  50311. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  50312. var particleSystem = scene.particleSystems[particleIndex];
  50313. var emitter = particleSystem.emitter;
  50314. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  50315. continue;
  50316. }
  50317. if (currentRenderList.indexOf(emitter) >= 0) {
  50318. this._renderingManager.dispatchParticles(particleSystem);
  50319. }
  50320. }
  50321. if (this.isCube) {
  50322. for (var face = 0; face < 6; face++) {
  50323. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  50324. scene.incrementRenderId();
  50325. scene.resetCachedMaterial();
  50326. }
  50327. }
  50328. else {
  50329. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  50330. }
  50331. this.onAfterUnbindObservable.notifyObservers(this);
  50332. if (scene.activeCamera) {
  50333. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  50334. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  50335. }
  50336. engine.setViewport(scene.activeCamera.viewport);
  50337. }
  50338. scene.resetCachedMaterial();
  50339. };
  50340. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  50341. var minimum = 128;
  50342. var x = renderDimension * scale;
  50343. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  50344. // Ensure we don't exceed the render dimension (while staying POT)
  50345. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  50346. };
  50347. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  50348. var _this = this;
  50349. var scene = this.getScene();
  50350. if (!scene) {
  50351. return;
  50352. }
  50353. var engine = scene.getEngine();
  50354. if (!this._texture) {
  50355. return;
  50356. }
  50357. // Bind
  50358. if (this._postProcessManager) {
  50359. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  50360. }
  50361. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  50362. if (this._texture) {
  50363. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  50364. }
  50365. }
  50366. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  50367. // Clear
  50368. if (this.onClearObservable.hasObservers()) {
  50369. this.onClearObservable.notifyObservers(engine);
  50370. }
  50371. else {
  50372. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  50373. }
  50374. if (!this._doNotChangeAspectRatio) {
  50375. scene.updateTransformMatrix(true);
  50376. }
  50377. // Render
  50378. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  50379. if (this._postProcessManager) {
  50380. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  50381. }
  50382. else if (useCameraPostProcess) {
  50383. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  50384. }
  50385. if (!this._doNotChangeAspectRatio) {
  50386. scene.updateTransformMatrix(true);
  50387. }
  50388. // Dump ?
  50389. if (dumpForDebug) {
  50390. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  50391. }
  50392. // Unbind
  50393. if (!this.isCube || faceIndex === 5) {
  50394. if (this.isCube) {
  50395. if (faceIndex === 5) {
  50396. engine.generateMipMapsForCubemap(this._texture);
  50397. }
  50398. }
  50399. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  50400. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  50401. });
  50402. }
  50403. else {
  50404. this.onAfterRenderObservable.notifyObservers(faceIndex);
  50405. }
  50406. };
  50407. /**
  50408. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  50409. * This allowed control for front to back rendering or reversly depending of the special needs.
  50410. *
  50411. * @param renderingGroupId The rendering group id corresponding to its index
  50412. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  50413. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  50414. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  50415. */
  50416. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  50417. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  50418. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  50419. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  50420. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  50421. };
  50422. /**
  50423. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  50424. *
  50425. * @param renderingGroupId The rendering group id corresponding to its index
  50426. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  50427. */
  50428. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  50429. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  50430. };
  50431. RenderTargetTexture.prototype.clone = function () {
  50432. var textureSize = this.getSize();
  50433. 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);
  50434. // Base texture
  50435. newTexture.hasAlpha = this.hasAlpha;
  50436. newTexture.level = this.level;
  50437. // RenderTarget Texture
  50438. newTexture.coordinatesMode = this.coordinatesMode;
  50439. if (this.renderList) {
  50440. newTexture.renderList = this.renderList.slice(0);
  50441. }
  50442. return newTexture;
  50443. };
  50444. RenderTargetTexture.prototype.serialize = function () {
  50445. if (!this.name) {
  50446. return null;
  50447. }
  50448. var serializationObject = _super.prototype.serialize.call(this);
  50449. serializationObject.renderTargetSize = this.getRenderSize();
  50450. serializationObject.renderList = [];
  50451. if (this.renderList) {
  50452. for (var index = 0; index < this.renderList.length; index++) {
  50453. serializationObject.renderList.push(this.renderList[index].id);
  50454. }
  50455. }
  50456. return serializationObject;
  50457. };
  50458. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  50459. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  50460. var objBuffer = this.getInternalTexture();
  50461. var scene = this.getScene();
  50462. if (objBuffer && scene) {
  50463. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  50464. }
  50465. };
  50466. RenderTargetTexture.prototype.dispose = function () {
  50467. if (this._postProcessManager) {
  50468. this._postProcessManager.dispose();
  50469. this._postProcessManager = null;
  50470. }
  50471. this.clearPostProcesses(true);
  50472. if (this._resizeObserver) {
  50473. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  50474. this._resizeObserver = null;
  50475. }
  50476. this.renderList = null;
  50477. // Remove from custom render targets
  50478. var scene = this.getScene();
  50479. if (!scene) {
  50480. return;
  50481. }
  50482. var index = scene.customRenderTargets.indexOf(this);
  50483. if (index >= 0) {
  50484. scene.customRenderTargets.splice(index, 1);
  50485. }
  50486. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  50487. var camera = _a[_i];
  50488. index = camera.customRenderTargets.indexOf(this);
  50489. if (index >= 0) {
  50490. camera.customRenderTargets.splice(index, 1);
  50491. }
  50492. }
  50493. _super.prototype.dispose.call(this);
  50494. };
  50495. RenderTargetTexture.prototype._rebuild = function () {
  50496. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  50497. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  50498. }
  50499. if (this._postProcessManager) {
  50500. this._postProcessManager._rebuild();
  50501. }
  50502. };
  50503. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  50504. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  50505. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  50506. return RenderTargetTexture;
  50507. }(BABYLON.Texture));
  50508. BABYLON.RenderTargetTexture = RenderTargetTexture;
  50509. })(BABYLON || (BABYLON = {}));
  50510. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  50511. var BABYLON;
  50512. (function (BABYLON) {
  50513. ;
  50514. var MultiRenderTarget = /** @class */ (function (_super) {
  50515. __extends(MultiRenderTarget, _super);
  50516. function MultiRenderTarget(name, size, count, scene, options) {
  50517. var _this = this;
  50518. options = options || {};
  50519. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  50520. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  50521. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  50522. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  50523. _this._engine = scene.getEngine();
  50524. if (!_this.isSupported) {
  50525. _this.dispose();
  50526. return;
  50527. }
  50528. var types = [];
  50529. var samplingModes = [];
  50530. for (var i = 0; i < count; i++) {
  50531. if (options.types && options.types[i]) {
  50532. types.push(options.types[i]);
  50533. }
  50534. else {
  50535. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  50536. }
  50537. if (options.samplingModes && options.samplingModes[i]) {
  50538. samplingModes.push(options.samplingModes[i]);
  50539. }
  50540. else {
  50541. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50542. }
  50543. }
  50544. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  50545. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  50546. _this._size = size;
  50547. _this._multiRenderTargetOptions = {
  50548. samplingModes: samplingModes,
  50549. generateMipMaps: generateMipMaps,
  50550. generateDepthBuffer: generateDepthBuffer,
  50551. generateStencilBuffer: generateStencilBuffer,
  50552. generateDepthTexture: generateDepthTexture,
  50553. types: types,
  50554. textureCount: count
  50555. };
  50556. _this._createInternalTextures();
  50557. _this._createTextures();
  50558. return _this;
  50559. }
  50560. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  50561. get: function () {
  50562. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  50563. },
  50564. enumerable: true,
  50565. configurable: true
  50566. });
  50567. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  50568. get: function () {
  50569. return this._textures;
  50570. },
  50571. enumerable: true,
  50572. configurable: true
  50573. });
  50574. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  50575. get: function () {
  50576. return this._textures[this._textures.length - 1];
  50577. },
  50578. enumerable: true,
  50579. configurable: true
  50580. });
  50581. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  50582. set: function (wrap) {
  50583. if (this._textures) {
  50584. for (var i = 0; i < this._textures.length; i++) {
  50585. this._textures[i].wrapU = wrap;
  50586. }
  50587. }
  50588. },
  50589. enumerable: true,
  50590. configurable: true
  50591. });
  50592. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  50593. set: function (wrap) {
  50594. if (this._textures) {
  50595. for (var i = 0; i < this._textures.length; i++) {
  50596. this._textures[i].wrapV = wrap;
  50597. }
  50598. }
  50599. },
  50600. enumerable: true,
  50601. configurable: true
  50602. });
  50603. MultiRenderTarget.prototype._rebuild = function () {
  50604. this.releaseInternalTextures();
  50605. this._createInternalTextures();
  50606. for (var i = 0; i < this._internalTextures.length; i++) {
  50607. var texture = this._textures[i];
  50608. texture._texture = this._internalTextures[i];
  50609. }
  50610. // Keeps references to frame buffer and stencil/depth buffer
  50611. this._texture = this._internalTextures[0];
  50612. };
  50613. MultiRenderTarget.prototype._createInternalTextures = function () {
  50614. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  50615. };
  50616. MultiRenderTarget.prototype._createTextures = function () {
  50617. this._textures = [];
  50618. for (var i = 0; i < this._internalTextures.length; i++) {
  50619. var texture = new BABYLON.Texture(null, this.getScene());
  50620. texture._texture = this._internalTextures[i];
  50621. this._textures.push(texture);
  50622. }
  50623. // Keeps references to frame buffer and stencil/depth buffer
  50624. this._texture = this._internalTextures[0];
  50625. };
  50626. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  50627. get: function () {
  50628. return this._samples;
  50629. },
  50630. set: function (value) {
  50631. if (this._samples === value) {
  50632. return;
  50633. }
  50634. for (var i = 0; i < this._internalTextures.length; i++) {
  50635. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  50636. }
  50637. },
  50638. enumerable: true,
  50639. configurable: true
  50640. });
  50641. MultiRenderTarget.prototype.resize = function (size) {
  50642. this.releaseInternalTextures();
  50643. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  50644. this._createInternalTextures();
  50645. };
  50646. MultiRenderTarget.prototype.dispose = function () {
  50647. this.releaseInternalTextures();
  50648. _super.prototype.dispose.call(this);
  50649. };
  50650. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  50651. if (!this._internalTextures) {
  50652. return;
  50653. }
  50654. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  50655. if (this._internalTextures[i] !== undefined) {
  50656. this._internalTextures[i].dispose();
  50657. this._internalTextures.splice(i, 1);
  50658. }
  50659. }
  50660. };
  50661. return MultiRenderTarget;
  50662. }(BABYLON.RenderTargetTexture));
  50663. BABYLON.MultiRenderTarget = MultiRenderTarget;
  50664. })(BABYLON || (BABYLON = {}));
  50665. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  50666. var BABYLON;
  50667. (function (BABYLON) {
  50668. var MirrorTexture = /** @class */ (function (_super) {
  50669. __extends(MirrorTexture, _super);
  50670. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  50671. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50672. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50673. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  50674. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  50675. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  50676. _this._transformMatrix = BABYLON.Matrix.Zero();
  50677. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  50678. _this._adaptiveBlurKernel = 0;
  50679. _this._blurKernelX = 0;
  50680. _this._blurKernelY = 0;
  50681. _this._blurRatio = 1.0;
  50682. _this.ignoreCameraViewport = true;
  50683. _this.onBeforeRenderObservable.add(function () {
  50684. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  50685. _this._savedViewMatrix = scene.getViewMatrix();
  50686. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  50687. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  50688. scene.clipPlane = _this.mirrorPlane;
  50689. scene.getEngine().cullBackFaces = false;
  50690. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  50691. });
  50692. _this.onAfterRenderObservable.add(function () {
  50693. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  50694. scene.getEngine().cullBackFaces = true;
  50695. scene._mirroredCameraPosition = null;
  50696. delete scene.clipPlane;
  50697. });
  50698. return _this;
  50699. }
  50700. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  50701. get: function () {
  50702. return this._blurRatio;
  50703. },
  50704. set: function (value) {
  50705. if (this._blurRatio === value) {
  50706. return;
  50707. }
  50708. this._blurRatio = value;
  50709. this._preparePostProcesses();
  50710. },
  50711. enumerable: true,
  50712. configurable: true
  50713. });
  50714. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  50715. set: function (value) {
  50716. this._adaptiveBlurKernel = value;
  50717. this._autoComputeBlurKernel();
  50718. },
  50719. enumerable: true,
  50720. configurable: true
  50721. });
  50722. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  50723. set: function (value) {
  50724. this.blurKernelX = value;
  50725. this.blurKernelY = value;
  50726. },
  50727. enumerable: true,
  50728. configurable: true
  50729. });
  50730. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  50731. get: function () {
  50732. return this._blurKernelX;
  50733. },
  50734. set: function (value) {
  50735. if (this._blurKernelX === value) {
  50736. return;
  50737. }
  50738. this._blurKernelX = value;
  50739. this._preparePostProcesses();
  50740. },
  50741. enumerable: true,
  50742. configurable: true
  50743. });
  50744. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  50745. get: function () {
  50746. return this._blurKernelY;
  50747. },
  50748. set: function (value) {
  50749. if (this._blurKernelY === value) {
  50750. return;
  50751. }
  50752. this._blurKernelY = value;
  50753. this._preparePostProcesses();
  50754. },
  50755. enumerable: true,
  50756. configurable: true
  50757. });
  50758. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  50759. var engine = this.getScene().getEngine();
  50760. var dw = this.getRenderWidth() / engine.getRenderWidth();
  50761. var dh = this.getRenderHeight() / engine.getRenderHeight();
  50762. this.blurKernelX = this._adaptiveBlurKernel * dw;
  50763. this.blurKernelY = this._adaptiveBlurKernel * dh;
  50764. };
  50765. MirrorTexture.prototype._onRatioRescale = function () {
  50766. if (this._sizeRatio) {
  50767. this.resize(this._initialSizeParameter);
  50768. if (!this._adaptiveBlurKernel) {
  50769. this._preparePostProcesses();
  50770. }
  50771. }
  50772. if (this._adaptiveBlurKernel) {
  50773. this._autoComputeBlurKernel();
  50774. }
  50775. };
  50776. MirrorTexture.prototype._preparePostProcesses = function () {
  50777. this.clearPostProcesses(true);
  50778. if (this._blurKernelX && this._blurKernelY) {
  50779. var engine = this.getScene().getEngine();
  50780. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50781. 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);
  50782. this._blurX.autoClear = false;
  50783. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  50784. this._blurX.outputTexture = this._texture;
  50785. }
  50786. else {
  50787. this._blurX.alwaysForcePOT = true;
  50788. }
  50789. 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);
  50790. this._blurY.autoClear = false;
  50791. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  50792. this.addPostProcess(this._blurX);
  50793. this.addPostProcess(this._blurY);
  50794. }
  50795. else {
  50796. if (this._blurY) {
  50797. this.removePostProcess(this._blurY);
  50798. this._blurY.dispose();
  50799. this._blurY = null;
  50800. }
  50801. if (this._blurX) {
  50802. this.removePostProcess(this._blurX);
  50803. this._blurX.dispose();
  50804. this._blurX = null;
  50805. }
  50806. }
  50807. };
  50808. MirrorTexture.prototype.clone = function () {
  50809. var scene = this.getScene();
  50810. if (!scene) {
  50811. return this;
  50812. }
  50813. var textureSize = this.getSize();
  50814. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  50815. // Base texture
  50816. newTexture.hasAlpha = this.hasAlpha;
  50817. newTexture.level = this.level;
  50818. // Mirror Texture
  50819. newTexture.mirrorPlane = this.mirrorPlane.clone();
  50820. if (this.renderList) {
  50821. newTexture.renderList = this.renderList.slice(0);
  50822. }
  50823. return newTexture;
  50824. };
  50825. MirrorTexture.prototype.serialize = function () {
  50826. if (!this.name) {
  50827. return null;
  50828. }
  50829. var serializationObject = _super.prototype.serialize.call(this);
  50830. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  50831. return serializationObject;
  50832. };
  50833. return MirrorTexture;
  50834. }(BABYLON.RenderTargetTexture));
  50835. BABYLON.MirrorTexture = MirrorTexture;
  50836. })(BABYLON || (BABYLON = {}));
  50837. //# sourceMappingURL=babylon.mirrorTexture.js.map
  50838. var BABYLON;
  50839. (function (BABYLON) {
  50840. /**
  50841. * Creates a refraction texture used by refraction channel of the standard material.
  50842. * @param name the texture name
  50843. * @param size size of the underlying texture
  50844. * @param scene root scene
  50845. */
  50846. var RefractionTexture = /** @class */ (function (_super) {
  50847. __extends(RefractionTexture, _super);
  50848. function RefractionTexture(name, size, scene, generateMipMaps) {
  50849. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  50850. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  50851. _this.depth = 2.0;
  50852. _this.onBeforeRenderObservable.add(function () {
  50853. scene.clipPlane = _this.refractionPlane;
  50854. });
  50855. _this.onAfterRenderObservable.add(function () {
  50856. delete scene.clipPlane;
  50857. });
  50858. return _this;
  50859. }
  50860. RefractionTexture.prototype.clone = function () {
  50861. var scene = this.getScene();
  50862. if (!scene) {
  50863. return this;
  50864. }
  50865. var textureSize = this.getSize();
  50866. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  50867. // Base texture
  50868. newTexture.hasAlpha = this.hasAlpha;
  50869. newTexture.level = this.level;
  50870. // Refraction Texture
  50871. newTexture.refractionPlane = this.refractionPlane.clone();
  50872. if (this.renderList) {
  50873. newTexture.renderList = this.renderList.slice(0);
  50874. }
  50875. newTexture.depth = this.depth;
  50876. return newTexture;
  50877. };
  50878. RefractionTexture.prototype.serialize = function () {
  50879. if (!this.name) {
  50880. return null;
  50881. }
  50882. var serializationObject = _super.prototype.serialize.call(this);
  50883. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  50884. serializationObject.depth = this.depth;
  50885. return serializationObject;
  50886. };
  50887. return RefractionTexture;
  50888. }(BABYLON.RenderTargetTexture));
  50889. BABYLON.RefractionTexture = RefractionTexture;
  50890. })(BABYLON || (BABYLON = {}));
  50891. //# sourceMappingURL=babylon.refractionTexture.js.map
  50892. var BABYLON;
  50893. (function (BABYLON) {
  50894. var DynamicTexture = /** @class */ (function (_super) {
  50895. __extends(DynamicTexture, _super);
  50896. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  50897. if (scene === void 0) { scene = null; }
  50898. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50899. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  50900. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  50901. _this.name = name;
  50902. _this._engine = _this.getScene().getEngine();
  50903. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50904. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50905. _this._generateMipMaps = generateMipMaps;
  50906. if (options.getContext) {
  50907. _this._canvas = options;
  50908. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50909. }
  50910. else {
  50911. _this._canvas = document.createElement("canvas");
  50912. if (options.width) {
  50913. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50914. }
  50915. else {
  50916. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  50917. }
  50918. }
  50919. var textureSize = _this.getSize();
  50920. _this._canvas.width = textureSize.width;
  50921. _this._canvas.height = textureSize.height;
  50922. _this._context = _this._canvas.getContext("2d");
  50923. return _this;
  50924. }
  50925. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  50926. get: function () {
  50927. return true;
  50928. },
  50929. enumerable: true,
  50930. configurable: true
  50931. });
  50932. DynamicTexture.prototype._recreate = function (textureSize) {
  50933. this._canvas.width = textureSize.width;
  50934. this._canvas.height = textureSize.height;
  50935. this.releaseInternalTexture();
  50936. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  50937. };
  50938. DynamicTexture.prototype.scale = function (ratio) {
  50939. var textureSize = this.getSize();
  50940. textureSize.width *= ratio;
  50941. textureSize.height *= ratio;
  50942. this._recreate(textureSize);
  50943. };
  50944. DynamicTexture.prototype.scaleTo = function (width, height) {
  50945. var textureSize = this.getSize();
  50946. textureSize.width = width;
  50947. textureSize.height = height;
  50948. this._recreate(textureSize);
  50949. };
  50950. DynamicTexture.prototype.getContext = function () {
  50951. return this._context;
  50952. };
  50953. DynamicTexture.prototype.clear = function () {
  50954. var size = this.getSize();
  50955. this._context.fillRect(0, 0, size.width, size.height);
  50956. };
  50957. DynamicTexture.prototype.update = function (invertY) {
  50958. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  50959. };
  50960. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  50961. if (update === void 0) { update = true; }
  50962. var size = this.getSize();
  50963. if (clearColor) {
  50964. this._context.fillStyle = clearColor;
  50965. this._context.fillRect(0, 0, size.width, size.height);
  50966. }
  50967. this._context.font = font;
  50968. if (x === null || x === undefined) {
  50969. var textSize = this._context.measureText(text);
  50970. x = (size.width - textSize.width) / 2;
  50971. }
  50972. if (y === null || y === undefined) {
  50973. var fontSize = parseInt((font.replace(/\D/g, '')));
  50974. ;
  50975. y = (size.height / 2) + (fontSize / 3.65);
  50976. }
  50977. this._context.fillStyle = color;
  50978. this._context.fillText(text, x, y);
  50979. if (update) {
  50980. this.update(invertY);
  50981. }
  50982. };
  50983. DynamicTexture.prototype.clone = function () {
  50984. var scene = this.getScene();
  50985. if (!scene) {
  50986. return this;
  50987. }
  50988. var textureSize = this.getSize();
  50989. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  50990. // Base texture
  50991. newTexture.hasAlpha = this.hasAlpha;
  50992. newTexture.level = this.level;
  50993. // Dynamic Texture
  50994. newTexture.wrapU = this.wrapU;
  50995. newTexture.wrapV = this.wrapV;
  50996. return newTexture;
  50997. };
  50998. DynamicTexture.prototype._rebuild = function () {
  50999. this.update();
  51000. };
  51001. return DynamicTexture;
  51002. }(BABYLON.Texture));
  51003. BABYLON.DynamicTexture = DynamicTexture;
  51004. })(BABYLON || (BABYLON = {}));
  51005. //# sourceMappingURL=babylon.dynamicTexture.js.map
  51006. var BABYLON;
  51007. (function (BABYLON) {
  51008. var VideoTexture = /** @class */ (function (_super) {
  51009. __extends(VideoTexture, _super);
  51010. /**
  51011. * Creates a video texture.
  51012. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  51013. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  51014. * @param {BABYLON.Scene} scene is obviously the current scene.
  51015. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  51016. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  51017. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  51018. */
  51019. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  51020. if (generateMipMaps === void 0) { generateMipMaps = false; }
  51021. if (invertY === void 0) { invertY = false; }
  51022. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51023. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51024. _this._autoLaunch = true;
  51025. var urls = null;
  51026. _this.name = name;
  51027. if (urlsOrVideo instanceof HTMLVideoElement) {
  51028. _this.video = urlsOrVideo;
  51029. }
  51030. else {
  51031. urls = urlsOrVideo;
  51032. _this.video = document.createElement("video");
  51033. _this.video.autoplay = false;
  51034. _this.video.loop = true;
  51035. }
  51036. _this._engine = _this.getScene().getEngine();
  51037. _this._generateMipMaps = generateMipMaps;
  51038. _this._samplingMode = samplingMode;
  51039. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  51040. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51041. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51042. }
  51043. else {
  51044. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51045. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51046. _this._generateMipMaps = false;
  51047. }
  51048. if (urls) {
  51049. _this.video.addEventListener("canplay", function () {
  51050. _this._createTexture();
  51051. });
  51052. urls.forEach(function (url) {
  51053. var source = document.createElement("source");
  51054. source.src = url;
  51055. _this.video.appendChild(source);
  51056. });
  51057. }
  51058. else {
  51059. _this._createTexture();
  51060. }
  51061. _this._lastUpdate = BABYLON.Tools.Now;
  51062. return _this;
  51063. }
  51064. VideoTexture.prototype.__setTextureReady = function () {
  51065. if (this._texture) {
  51066. this._texture.isReady = true;
  51067. }
  51068. };
  51069. VideoTexture.prototype._createTexture = function () {
  51070. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  51071. if (this._autoLaunch) {
  51072. this._autoLaunch = false;
  51073. this.video.play();
  51074. }
  51075. this._setTextureReady = this.__setTextureReady.bind(this);
  51076. this.video.addEventListener("playing", this._setTextureReady);
  51077. };
  51078. VideoTexture.prototype._rebuild = function () {
  51079. this.update();
  51080. };
  51081. VideoTexture.prototype.update = function () {
  51082. var now = BABYLON.Tools.Now;
  51083. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  51084. return false;
  51085. }
  51086. this._lastUpdate = now;
  51087. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  51088. return true;
  51089. };
  51090. VideoTexture.prototype.dispose = function () {
  51091. _super.prototype.dispose.call(this);
  51092. this.video.removeEventListener("playing", this._setTextureReady);
  51093. };
  51094. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  51095. var video = document.createElement("video");
  51096. var constraintsDeviceId;
  51097. if (constraints && constraints.deviceId) {
  51098. constraintsDeviceId = {
  51099. exact: constraints.deviceId
  51100. };
  51101. }
  51102. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  51103. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  51104. if (navigator.getUserMedia) {
  51105. navigator.getUserMedia({
  51106. video: {
  51107. deviceId: constraintsDeviceId,
  51108. width: {
  51109. min: (constraints && constraints.minWidth) || 256,
  51110. max: (constraints && constraints.maxWidth) || 640
  51111. },
  51112. height: {
  51113. min: (constraints && constraints.minHeight) || 256,
  51114. max: (constraints && constraints.maxHeight) || 480
  51115. }
  51116. }
  51117. }, function (stream) {
  51118. if (video.mozSrcObject !== undefined) {
  51119. video.mozSrcObject = stream;
  51120. }
  51121. else {
  51122. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  51123. }
  51124. video.play();
  51125. if (onReady) {
  51126. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  51127. }
  51128. }, function (e) {
  51129. BABYLON.Tools.Error(e.name);
  51130. });
  51131. }
  51132. };
  51133. return VideoTexture;
  51134. }(BABYLON.Texture));
  51135. BABYLON.VideoTexture = VideoTexture;
  51136. })(BABYLON || (BABYLON = {}));
  51137. //# sourceMappingURL=babylon.videoTexture.js.map
  51138. var BABYLON;
  51139. (function (BABYLON) {
  51140. var RawTexture = /** @class */ (function (_super) {
  51141. __extends(RawTexture, _super);
  51142. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  51143. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51144. if (invertY === void 0) { invertY = false; }
  51145. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51146. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51147. _this.format = format;
  51148. _this._engine = scene.getEngine();
  51149. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  51150. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51151. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51152. return _this;
  51153. }
  51154. RawTexture.prototype.update = function (data) {
  51155. this._engine.updateRawTexture(this._texture, data, this.format, this._invertY);
  51156. };
  51157. // Statics
  51158. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51159. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51160. if (invertY === void 0) { invertY = false; }
  51161. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51162. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  51163. };
  51164. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51165. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51166. if (invertY === void 0) { invertY = false; }
  51167. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51168. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51169. };
  51170. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51171. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51172. if (invertY === void 0) { invertY = false; }
  51173. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51174. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51175. };
  51176. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51177. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51178. if (invertY === void 0) { invertY = false; }
  51179. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51180. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  51181. };
  51182. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51183. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51184. if (invertY === void 0) { invertY = false; }
  51185. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51186. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  51187. };
  51188. return RawTexture;
  51189. }(BABYLON.Texture));
  51190. BABYLON.RawTexture = RawTexture;
  51191. })(BABYLON || (BABYLON = {}));
  51192. //# sourceMappingURL=babylon.rawTexture.js.map
  51193. var BABYLON;
  51194. (function (BABYLON) {
  51195. var PostProcess = /** @class */ (function () {
  51196. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  51197. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  51198. if (defines === void 0) { defines = null; }
  51199. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51200. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  51201. if (blockCompilation === void 0) { blockCompilation = false; }
  51202. this.name = name;
  51203. this.width = -1;
  51204. this.height = -1;
  51205. this.autoClear = true;
  51206. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  51207. this.animations = new Array();
  51208. /*
  51209. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  51210. Can only be used on a single postprocess or on the last one of a chain.
  51211. */
  51212. this.enablePixelPerfectMode = false;
  51213. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  51214. this.alwaysForcePOT = false;
  51215. this.samples = 1;
  51216. this.adaptScaleToCurrentViewport = false;
  51217. this._reusable = false;
  51218. this._textures = new BABYLON.SmartArray(2);
  51219. this._currentRenderTextureInd = 0;
  51220. this._scaleRatio = new BABYLON.Vector2(1, 1);
  51221. this._texelSize = BABYLON.Vector2.Zero();
  51222. // Events
  51223. /**
  51224. * An event triggered when the postprocess is activated.
  51225. * @type {BABYLON.Observable}
  51226. */
  51227. this.onActivateObservable = new BABYLON.Observable();
  51228. /**
  51229. * An event triggered when the postprocess changes its size.
  51230. * @type {BABYLON.Observable}
  51231. */
  51232. this.onSizeChangedObservable = new BABYLON.Observable();
  51233. /**
  51234. * An event triggered when the postprocess applies its effect.
  51235. * @type {BABYLON.Observable}
  51236. */
  51237. this.onApplyObservable = new BABYLON.Observable();
  51238. /**
  51239. * An event triggered before rendering the postprocess
  51240. * @type {BABYLON.Observable}
  51241. */
  51242. this.onBeforeRenderObservable = new BABYLON.Observable();
  51243. /**
  51244. * An event triggered after rendering the postprocess
  51245. * @type {BABYLON.Observable}
  51246. */
  51247. this.onAfterRenderObservable = new BABYLON.Observable();
  51248. if (camera != null) {
  51249. this._camera = camera;
  51250. this._scene = camera.getScene();
  51251. camera.attachPostProcess(this);
  51252. this._engine = this._scene.getEngine();
  51253. this._scene.postProcesses.push(this);
  51254. }
  51255. else if (engine) {
  51256. this._engine = engine;
  51257. this._engine.postProcesses.push(this);
  51258. }
  51259. this._options = options;
  51260. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  51261. this._reusable = reusable || false;
  51262. this._textureType = textureType;
  51263. this._samplers = samplers || [];
  51264. this._samplers.push("textureSampler");
  51265. this._fragmentUrl = fragmentUrl;
  51266. this._vertexUrl = vertexUrl;
  51267. this._parameters = parameters || [];
  51268. this._parameters.push("scale");
  51269. this._indexParameters = indexParameters;
  51270. if (!blockCompilation) {
  51271. this.updateEffect(defines);
  51272. }
  51273. }
  51274. Object.defineProperty(PostProcess.prototype, "onActivate", {
  51275. set: function (callback) {
  51276. if (this._onActivateObserver) {
  51277. this.onActivateObservable.remove(this._onActivateObserver);
  51278. }
  51279. if (callback) {
  51280. this._onActivateObserver = this.onActivateObservable.add(callback);
  51281. }
  51282. },
  51283. enumerable: true,
  51284. configurable: true
  51285. });
  51286. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  51287. set: function (callback) {
  51288. if (this._onSizeChangedObserver) {
  51289. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  51290. }
  51291. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  51292. },
  51293. enumerable: true,
  51294. configurable: true
  51295. });
  51296. Object.defineProperty(PostProcess.prototype, "onApply", {
  51297. set: function (callback) {
  51298. if (this._onApplyObserver) {
  51299. this.onApplyObservable.remove(this._onApplyObserver);
  51300. }
  51301. this._onApplyObserver = this.onApplyObservable.add(callback);
  51302. },
  51303. enumerable: true,
  51304. configurable: true
  51305. });
  51306. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  51307. set: function (callback) {
  51308. if (this._onBeforeRenderObserver) {
  51309. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51310. }
  51311. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51312. },
  51313. enumerable: true,
  51314. configurable: true
  51315. });
  51316. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  51317. set: function (callback) {
  51318. if (this._onAfterRenderObserver) {
  51319. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51320. }
  51321. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51322. },
  51323. enumerable: true,
  51324. configurable: true
  51325. });
  51326. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  51327. get: function () {
  51328. return this._textures.data[this._currentRenderTextureInd];
  51329. },
  51330. set: function (value) {
  51331. this._forcedOutputTexture = value;
  51332. },
  51333. enumerable: true,
  51334. configurable: true
  51335. });
  51336. PostProcess.prototype.getCamera = function () {
  51337. return this._camera;
  51338. };
  51339. Object.defineProperty(PostProcess.prototype, "texelSize", {
  51340. get: function () {
  51341. if (this._shareOutputWithPostProcess) {
  51342. return this._shareOutputWithPostProcess.texelSize;
  51343. }
  51344. if (this._forcedOutputTexture) {
  51345. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  51346. }
  51347. return this._texelSize;
  51348. },
  51349. enumerable: true,
  51350. configurable: true
  51351. });
  51352. PostProcess.prototype.getEngine = function () {
  51353. return this._engine;
  51354. };
  51355. PostProcess.prototype.getEffect = function () {
  51356. return this._effect;
  51357. };
  51358. PostProcess.prototype.shareOutputWith = function (postProcess) {
  51359. this._disposeTextures();
  51360. this._shareOutputWithPostProcess = postProcess;
  51361. return this;
  51362. };
  51363. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  51364. if (defines === void 0) { defines = null; }
  51365. if (uniforms === void 0) { uniforms = null; }
  51366. if (samplers === void 0) { samplers = null; }
  51367. 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);
  51368. };
  51369. PostProcess.prototype.isReusable = function () {
  51370. return this._reusable;
  51371. };
  51372. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  51373. PostProcess.prototype.markTextureDirty = function () {
  51374. this.width = -1;
  51375. };
  51376. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  51377. var _this = this;
  51378. if (sourceTexture === void 0) { sourceTexture = null; }
  51379. camera = camera || this._camera;
  51380. var scene = camera.getScene();
  51381. var engine = scene.getEngine();
  51382. var maxSize = engine.getCaps().maxTextureSize;
  51383. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  51384. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  51385. var desiredWidth = (this._options.width || requiredWidth);
  51386. var desiredHeight = this._options.height || requiredHeight;
  51387. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  51388. if (this.adaptScaleToCurrentViewport) {
  51389. var currentViewport = engine.currentViewport;
  51390. if (currentViewport) {
  51391. desiredWidth *= currentViewport.width;
  51392. desiredHeight *= currentViewport.height;
  51393. }
  51394. }
  51395. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  51396. if (!this._options.width) {
  51397. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  51398. }
  51399. if (!this._options.height) {
  51400. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  51401. }
  51402. }
  51403. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  51404. if (this._textures.length > 0) {
  51405. for (var i = 0; i < this._textures.length; i++) {
  51406. this._engine._releaseTexture(this._textures.data[i]);
  51407. }
  51408. this._textures.reset();
  51409. }
  51410. this.width = desiredWidth;
  51411. this.height = desiredHeight;
  51412. var textureSize = { width: this.width, height: this.height };
  51413. var textureOptions = {
  51414. generateMipMaps: false,
  51415. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  51416. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  51417. samplingMode: this.renderTargetSamplingMode,
  51418. type: this._textureType
  51419. };
  51420. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  51421. if (this._reusable) {
  51422. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  51423. }
  51424. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  51425. this.onSizeChangedObservable.notifyObservers(this);
  51426. }
  51427. this._textures.forEach(function (texture) {
  51428. if (texture.samples !== _this.samples) {
  51429. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  51430. }
  51431. });
  51432. }
  51433. var target;
  51434. if (this._shareOutputWithPostProcess) {
  51435. target = this._shareOutputWithPostProcess.outputTexture;
  51436. }
  51437. else if (this._forcedOutputTexture) {
  51438. target = this._forcedOutputTexture;
  51439. this.width = this._forcedOutputTexture.width;
  51440. this.height = this._forcedOutputTexture.height;
  51441. }
  51442. else {
  51443. target = this.outputTexture;
  51444. }
  51445. if (this.enablePixelPerfectMode) {
  51446. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  51447. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  51448. }
  51449. else {
  51450. this._scaleRatio.copyFromFloats(1, 1);
  51451. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  51452. }
  51453. this.onActivateObservable.notifyObservers(camera);
  51454. // Clear
  51455. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  51456. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  51457. }
  51458. if (this._reusable) {
  51459. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  51460. }
  51461. };
  51462. Object.defineProperty(PostProcess.prototype, "isSupported", {
  51463. get: function () {
  51464. return this._effect.isSupported;
  51465. },
  51466. enumerable: true,
  51467. configurable: true
  51468. });
  51469. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  51470. get: function () {
  51471. if (this._shareOutputWithPostProcess) {
  51472. return this._shareOutputWithPostProcess.aspectRatio;
  51473. }
  51474. if (this._forcedOutputTexture) {
  51475. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  51476. }
  51477. return this.width / this.height;
  51478. },
  51479. enumerable: true,
  51480. configurable: true
  51481. });
  51482. PostProcess.prototype.apply = function () {
  51483. // Check
  51484. if (!this._effect || !this._effect.isReady())
  51485. return null;
  51486. // States
  51487. this._engine.enableEffect(this._effect);
  51488. this._engine.setState(false);
  51489. this._engine.setDepthBuffer(false);
  51490. this._engine.setDepthWrite(false);
  51491. // Alpha
  51492. this._engine.setAlphaMode(this.alphaMode);
  51493. if (this.alphaConstants) {
  51494. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  51495. }
  51496. // Texture
  51497. var source;
  51498. if (this._shareOutputWithPostProcess) {
  51499. source = this._shareOutputWithPostProcess.outputTexture;
  51500. }
  51501. else if (this._forcedOutputTexture) {
  51502. source = this._forcedOutputTexture;
  51503. }
  51504. else {
  51505. source = this.outputTexture;
  51506. }
  51507. this._effect._bindTexture("textureSampler", source);
  51508. // Parameters
  51509. this._effect.setVector2("scale", this._scaleRatio);
  51510. this.onApplyObservable.notifyObservers(this._effect);
  51511. return this._effect;
  51512. };
  51513. PostProcess.prototype._disposeTextures = function () {
  51514. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  51515. return;
  51516. }
  51517. if (this._textures.length > 0) {
  51518. for (var i = 0; i < this._textures.length; i++) {
  51519. this._engine._releaseTexture(this._textures.data[i]);
  51520. }
  51521. }
  51522. this._textures.dispose();
  51523. };
  51524. PostProcess.prototype.dispose = function (camera) {
  51525. camera = camera || this._camera;
  51526. this._disposeTextures();
  51527. if (this._scene) {
  51528. var index_1 = this._scene.postProcesses.indexOf(this);
  51529. if (index_1 !== -1) {
  51530. this._scene.postProcesses.splice(index_1, 1);
  51531. }
  51532. }
  51533. else {
  51534. var index_2 = this._engine.postProcesses.indexOf(this);
  51535. if (index_2 !== -1) {
  51536. this._engine.postProcesses.splice(index_2, 1);
  51537. }
  51538. }
  51539. if (!camera) {
  51540. return;
  51541. }
  51542. camera.detachPostProcess(this);
  51543. var index = camera._postProcesses.indexOf(this);
  51544. if (index === 0 && camera._postProcesses.length > 0) {
  51545. this._camera._postProcesses[0].markTextureDirty();
  51546. }
  51547. this.onActivateObservable.clear();
  51548. this.onAfterRenderObservable.clear();
  51549. this.onApplyObservable.clear();
  51550. this.onBeforeRenderObservable.clear();
  51551. this.onSizeChangedObservable.clear();
  51552. };
  51553. return PostProcess;
  51554. }());
  51555. BABYLON.PostProcess = PostProcess;
  51556. })(BABYLON || (BABYLON = {}));
  51557. //# sourceMappingURL=babylon.postProcess.js.map
  51558. var BABYLON;
  51559. (function (BABYLON) {
  51560. var PassPostProcess = /** @class */ (function (_super) {
  51561. __extends(PassPostProcess, _super);
  51562. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  51563. if (camera === void 0) { camera = null; }
  51564. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51565. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  51566. }
  51567. return PassPostProcess;
  51568. }(BABYLON.PostProcess));
  51569. BABYLON.PassPostProcess = PassPostProcess;
  51570. })(BABYLON || (BABYLON = {}));
  51571. //# sourceMappingURL=babylon.passPostProcess.js.map
  51572. var __assign = (this && this.__assign) || Object.assign || function(t) {
  51573. for (var s, i = 1, n = arguments.length; i < n; i++) {
  51574. s = arguments[i];
  51575. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  51576. t[p] = s[p];
  51577. }
  51578. return t;
  51579. };
  51580. var BABYLON;
  51581. (function (BABYLON) {
  51582. var ShadowGenerator = /** @class */ (function () {
  51583. /**
  51584. * Creates a ShadowGenerator object.
  51585. * A ShadowGenerator is the required tool to use the shadows.
  51586. * Each light casting shadows needs to use its own ShadowGenerator.
  51587. * Required parameters :
  51588. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  51589. * - `light`: the light object generating the shadows.
  51590. * - `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.
  51591. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  51592. */
  51593. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  51594. // Members
  51595. this._bias = 0.00005;
  51596. this._blurBoxOffset = 1;
  51597. this._blurScale = 2;
  51598. this._blurKernel = 1;
  51599. this._useKernelBlur = false;
  51600. this._filter = ShadowGenerator.FILTER_NONE;
  51601. this._darkness = 0;
  51602. this._transparencyShadow = false;
  51603. /**
  51604. * Controls the extent to which the shadows fade out at the edge of the frustum
  51605. * Used only by directionals and spots
  51606. */
  51607. this.frustumEdgeFalloff = 0;
  51608. this.forceBackFacesOnly = false;
  51609. this._lightDirection = BABYLON.Vector3.Zero();
  51610. this._viewMatrix = BABYLON.Matrix.Zero();
  51611. this._projectionMatrix = BABYLON.Matrix.Zero();
  51612. this._transformMatrix = BABYLON.Matrix.Zero();
  51613. this._currentFaceIndex = 0;
  51614. this._currentFaceIndexCache = 0;
  51615. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  51616. this._mapSize = mapSize;
  51617. this._light = light;
  51618. this._scene = light.getScene();
  51619. light._shadowGenerator = this;
  51620. // Texture type fallback from float to int if not supported.
  51621. var caps = this._scene.getEngine().getCaps();
  51622. if (!useFullFloatFirst) {
  51623. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  51624. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51625. }
  51626. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  51627. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51628. }
  51629. else {
  51630. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51631. }
  51632. }
  51633. else {
  51634. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  51635. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51636. }
  51637. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  51638. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51639. }
  51640. else {
  51641. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51642. }
  51643. }
  51644. this._initializeGenerator();
  51645. }
  51646. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  51647. // Static
  51648. get: function () {
  51649. return ShadowGenerator._FILTER_NONE;
  51650. },
  51651. enumerable: true,
  51652. configurable: true
  51653. });
  51654. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  51655. get: function () {
  51656. return ShadowGenerator._FILTER_POISSONSAMPLING;
  51657. },
  51658. enumerable: true,
  51659. configurable: true
  51660. });
  51661. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  51662. get: function () {
  51663. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  51664. },
  51665. enumerable: true,
  51666. configurable: true
  51667. });
  51668. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  51669. get: function () {
  51670. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  51671. },
  51672. enumerable: true,
  51673. configurable: true
  51674. });
  51675. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  51676. get: function () {
  51677. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51678. },
  51679. enumerable: true,
  51680. configurable: true
  51681. });
  51682. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  51683. get: function () {
  51684. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51685. },
  51686. enumerable: true,
  51687. configurable: true
  51688. });
  51689. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  51690. get: function () {
  51691. return this._bias;
  51692. },
  51693. set: function (bias) {
  51694. this._bias = bias;
  51695. },
  51696. enumerable: true,
  51697. configurable: true
  51698. });
  51699. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  51700. get: function () {
  51701. return this._blurBoxOffset;
  51702. },
  51703. set: function (value) {
  51704. if (this._blurBoxOffset === value) {
  51705. return;
  51706. }
  51707. this._blurBoxOffset = value;
  51708. this._disposeBlurPostProcesses();
  51709. },
  51710. enumerable: true,
  51711. configurable: true
  51712. });
  51713. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  51714. get: function () {
  51715. return this._blurScale;
  51716. },
  51717. set: function (value) {
  51718. if (this._blurScale === value) {
  51719. return;
  51720. }
  51721. this._blurScale = value;
  51722. this._disposeBlurPostProcesses();
  51723. },
  51724. enumerable: true,
  51725. configurable: true
  51726. });
  51727. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  51728. get: function () {
  51729. return this._blurKernel;
  51730. },
  51731. set: function (value) {
  51732. if (this._blurKernel === value) {
  51733. return;
  51734. }
  51735. this._blurKernel = value;
  51736. this._disposeBlurPostProcesses();
  51737. },
  51738. enumerable: true,
  51739. configurable: true
  51740. });
  51741. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  51742. get: function () {
  51743. return this._useKernelBlur;
  51744. },
  51745. set: function (value) {
  51746. if (this._useKernelBlur === value) {
  51747. return;
  51748. }
  51749. this._useKernelBlur = value;
  51750. this._disposeBlurPostProcesses();
  51751. },
  51752. enumerable: true,
  51753. configurable: true
  51754. });
  51755. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  51756. get: function () {
  51757. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  51758. },
  51759. set: function (value) {
  51760. this._depthScale = value;
  51761. },
  51762. enumerable: true,
  51763. configurable: true
  51764. });
  51765. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  51766. get: function () {
  51767. return this._filter;
  51768. },
  51769. set: function (value) {
  51770. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  51771. if (this._light.needCube()) {
  51772. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51773. this.useExponentialShadowMap = true;
  51774. return;
  51775. }
  51776. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51777. this.useCloseExponentialShadowMap = true;
  51778. return;
  51779. }
  51780. }
  51781. if (this._filter === value) {
  51782. return;
  51783. }
  51784. this._filter = value;
  51785. this._disposeBlurPostProcesses();
  51786. this._applyFilterValues();
  51787. this._light._markMeshesAsLightDirty();
  51788. },
  51789. enumerable: true,
  51790. configurable: true
  51791. });
  51792. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  51793. get: function () {
  51794. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  51795. },
  51796. set: function (value) {
  51797. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  51798. return;
  51799. }
  51800. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  51801. },
  51802. enumerable: true,
  51803. configurable: true
  51804. });
  51805. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  51806. get: function () {
  51807. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51808. return this.useExponentialShadowMap;
  51809. },
  51810. set: function (value) {
  51811. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51812. this.useExponentialShadowMap = value;
  51813. },
  51814. enumerable: true,
  51815. configurable: true
  51816. });
  51817. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  51818. get: function () {
  51819. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51820. return this.useBlurExponentialShadowMap;
  51821. },
  51822. set: function (value) {
  51823. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51824. this.useBlurExponentialShadowMap = value;
  51825. },
  51826. enumerable: true,
  51827. configurable: true
  51828. });
  51829. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  51830. get: function () {
  51831. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  51832. },
  51833. set: function (value) {
  51834. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  51835. return;
  51836. }
  51837. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51838. },
  51839. enumerable: true,
  51840. configurable: true
  51841. });
  51842. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  51843. get: function () {
  51844. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  51845. },
  51846. set: function (value) {
  51847. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51848. return;
  51849. }
  51850. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51851. },
  51852. enumerable: true,
  51853. configurable: true
  51854. });
  51855. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  51856. get: function () {
  51857. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51858. },
  51859. set: function (value) {
  51860. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  51861. return;
  51862. }
  51863. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51864. },
  51865. enumerable: true,
  51866. configurable: true
  51867. });
  51868. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  51869. get: function () {
  51870. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51871. },
  51872. set: function (value) {
  51873. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51874. return;
  51875. }
  51876. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51877. },
  51878. enumerable: true,
  51879. configurable: true
  51880. });
  51881. /**
  51882. * Returns the darkness value (float).
  51883. */
  51884. ShadowGenerator.prototype.getDarkness = function () {
  51885. return this._darkness;
  51886. };
  51887. /**
  51888. * Sets the ShadowGenerator darkness value (float <= 1.0).
  51889. * Returns the ShadowGenerator.
  51890. */
  51891. ShadowGenerator.prototype.setDarkness = function (darkness) {
  51892. if (darkness >= 1.0)
  51893. this._darkness = 1.0;
  51894. else if (darkness <= 0.0)
  51895. this._darkness = 0.0;
  51896. else
  51897. this._darkness = darkness;
  51898. return this;
  51899. };
  51900. /**
  51901. * Sets the ability to have transparent shadow (boolean).
  51902. * Returns the ShadowGenerator.
  51903. */
  51904. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  51905. this._transparencyShadow = hasShadow;
  51906. return this;
  51907. };
  51908. /**
  51909. * Returns a RenderTargetTexture object : the shadow map texture.
  51910. */
  51911. ShadowGenerator.prototype.getShadowMap = function () {
  51912. return this._shadowMap;
  51913. };
  51914. /**
  51915. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  51916. */
  51917. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  51918. if (this._shadowMap2) {
  51919. return this._shadowMap2;
  51920. }
  51921. return this._shadowMap;
  51922. };
  51923. /**
  51924. * Helper function to add a mesh and its descendants to the list of shadow casters
  51925. * @param mesh Mesh to add
  51926. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  51927. */
  51928. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  51929. if (includeDescendants === void 0) { includeDescendants = true; }
  51930. if (!this._shadowMap) {
  51931. return this;
  51932. }
  51933. if (!this._shadowMap.renderList) {
  51934. this._shadowMap.renderList = [];
  51935. }
  51936. this._shadowMap.renderList.push(mesh);
  51937. if (includeDescendants) {
  51938. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  51939. }
  51940. return this;
  51941. var _a;
  51942. };
  51943. /**
  51944. * Helper function to remove a mesh and its descendants from the list of shadow casters
  51945. * @param mesh Mesh to remove
  51946. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  51947. */
  51948. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  51949. if (includeDescendants === void 0) { includeDescendants = true; }
  51950. if (!this._shadowMap || !this._shadowMap.renderList) {
  51951. return this;
  51952. }
  51953. var index = this._shadowMap.renderList.indexOf(mesh);
  51954. if (index !== -1) {
  51955. this._shadowMap.renderList.splice(index, 1);
  51956. }
  51957. if (includeDescendants) {
  51958. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  51959. var child = _a[_i];
  51960. this.removeShadowCaster(child);
  51961. }
  51962. }
  51963. return this;
  51964. };
  51965. /**
  51966. * Returns the associated light object.
  51967. */
  51968. ShadowGenerator.prototype.getLight = function () {
  51969. return this._light;
  51970. };
  51971. ShadowGenerator.prototype._initializeGenerator = function () {
  51972. this._light._markMeshesAsLightDirty();
  51973. this._initializeShadowMap();
  51974. };
  51975. ShadowGenerator.prototype._initializeShadowMap = function () {
  51976. var _this = this;
  51977. // Render target
  51978. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  51979. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51980. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51981. this._shadowMap.anisotropicFilteringLevel = 1;
  51982. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51983. this._shadowMap.renderParticles = false;
  51984. this._shadowMap.ignoreCameraViewport = true;
  51985. // Record Face Index before render.
  51986. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  51987. _this._currentFaceIndex = faceIndex;
  51988. });
  51989. // Custom render function.
  51990. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  51991. // Blur if required afer render.
  51992. this._shadowMap.onAfterUnbindObservable.add(function () {
  51993. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  51994. return;
  51995. }
  51996. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  51997. _this._initializeBlurRTTAndPostProcesses();
  51998. }
  51999. var shadowMap = _this.getShadowMapForRendering();
  52000. if (shadowMap) {
  52001. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  52002. }
  52003. });
  52004. // Clear according to the chosen filter.
  52005. this._shadowMap.onClearObservable.add(function (engine) {
  52006. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  52007. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  52008. }
  52009. else {
  52010. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  52011. }
  52012. });
  52013. };
  52014. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  52015. var _this = this;
  52016. var engine = this._scene.getEngine();
  52017. var targetSize = this._mapSize / this.blurScale;
  52018. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  52019. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  52020. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52021. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52022. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52023. }
  52024. if (this.useKernelBlur) {
  52025. 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);
  52026. this._kernelBlurXPostprocess.width = targetSize;
  52027. this._kernelBlurXPostprocess.height = targetSize;
  52028. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  52029. effect.setTexture("textureSampler", _this._shadowMap);
  52030. });
  52031. 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);
  52032. this._kernelBlurXPostprocess.autoClear = false;
  52033. this._kernelBlurYPostprocess.autoClear = false;
  52034. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  52035. this._kernelBlurXPostprocess.packedFloat = true;
  52036. this._kernelBlurYPostprocess.packedFloat = true;
  52037. }
  52038. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  52039. }
  52040. else {
  52041. 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);
  52042. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  52043. effect.setFloat2("screenSize", targetSize, targetSize);
  52044. effect.setTexture("textureSampler", _this._shadowMap);
  52045. });
  52046. this._boxBlurPostprocess.autoClear = false;
  52047. this._blurPostProcesses = [this._boxBlurPostprocess];
  52048. }
  52049. };
  52050. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  52051. var index;
  52052. var engine = this._scene.getEngine();
  52053. if (depthOnlySubMeshes.length) {
  52054. engine.setColorWrite(false);
  52055. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  52056. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  52057. }
  52058. engine.setColorWrite(true);
  52059. }
  52060. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52061. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  52062. }
  52063. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52064. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  52065. }
  52066. if (this._transparencyShadow) {
  52067. for (index = 0; index < transparentSubMeshes.length; index++) {
  52068. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  52069. }
  52070. }
  52071. };
  52072. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  52073. var _this = this;
  52074. var mesh = subMesh.getRenderingMesh();
  52075. var scene = this._scene;
  52076. var engine = scene.getEngine();
  52077. var material = subMesh.getMaterial();
  52078. if (!material) {
  52079. return;
  52080. }
  52081. // Culling
  52082. engine.setState(material.backFaceCulling);
  52083. // Managing instances
  52084. var batch = mesh._getInstancesRenderList(subMesh._id);
  52085. if (batch.mustReturn) {
  52086. return;
  52087. }
  52088. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  52089. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  52090. engine.enableEffect(this._effect);
  52091. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  52092. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  52093. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  52094. this._effect.setVector3("lightPosition", this.getLight().position);
  52095. if (scene.activeCamera) {
  52096. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  52097. }
  52098. // Alpha test
  52099. if (material && material.needAlphaTesting()) {
  52100. var alphaTexture = material.getAlphaTestTexture();
  52101. if (alphaTexture) {
  52102. this._effect.setTexture("diffuseSampler", alphaTexture);
  52103. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  52104. }
  52105. }
  52106. // Bones
  52107. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52108. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  52109. }
  52110. if (this.forceBackFacesOnly) {
  52111. engine.setState(true, 0, false, true);
  52112. }
  52113. // Draw
  52114. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52115. if (this.forceBackFacesOnly) {
  52116. engine.setState(true, 0, false, false);
  52117. }
  52118. }
  52119. else {
  52120. // Need to reset refresh rate of the shadowMap
  52121. if (this._shadowMap) {
  52122. this._shadowMap.resetRefreshCounter();
  52123. }
  52124. }
  52125. };
  52126. ShadowGenerator.prototype._applyFilterValues = function () {
  52127. if (!this._shadowMap) {
  52128. return;
  52129. }
  52130. if (this.filter === ShadowGenerator.FILTER_NONE) {
  52131. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  52132. }
  52133. else {
  52134. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52135. }
  52136. };
  52137. /**
  52138. * Force shader compilation including textures ready check
  52139. */
  52140. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  52141. var _this = this;
  52142. var localOptions = __assign({ useInstances: false }, options);
  52143. var shadowMap = this.getShadowMap();
  52144. if (!shadowMap) {
  52145. if (onCompiled) {
  52146. onCompiled(this);
  52147. }
  52148. return;
  52149. }
  52150. var renderList = shadowMap.renderList;
  52151. if (!renderList) {
  52152. if (onCompiled) {
  52153. onCompiled(this);
  52154. }
  52155. return;
  52156. }
  52157. var subMeshes = new Array();
  52158. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  52159. var mesh = renderList_1[_i];
  52160. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  52161. }
  52162. if (subMeshes.length === 0) {
  52163. if (onCompiled) {
  52164. onCompiled(this);
  52165. }
  52166. return;
  52167. }
  52168. var currentIndex = 0;
  52169. var checkReady = function () {
  52170. if (!_this._scene || !_this._scene.getEngine()) {
  52171. return;
  52172. }
  52173. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  52174. currentIndex++;
  52175. if (currentIndex >= subMeshes.length) {
  52176. if (onCompiled) {
  52177. onCompiled(_this);
  52178. }
  52179. return;
  52180. }
  52181. }
  52182. setTimeout(checkReady, 16);
  52183. };
  52184. checkReady();
  52185. };
  52186. /**
  52187. * Boolean : true when the ShadowGenerator is finally computed.
  52188. */
  52189. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  52190. var defines = [];
  52191. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  52192. defines.push("#define FLOAT");
  52193. }
  52194. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  52195. defines.push("#define ESM");
  52196. }
  52197. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52198. var mesh = subMesh.getMesh();
  52199. var material = subMesh.getMaterial();
  52200. // Alpha test
  52201. if (material && material.needAlphaTesting()) {
  52202. var alphaTexture = material.getAlphaTestTexture();
  52203. if (alphaTexture) {
  52204. defines.push("#define ALPHATEST");
  52205. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52206. attribs.push(BABYLON.VertexBuffer.UVKind);
  52207. defines.push("#define UV1");
  52208. }
  52209. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52210. if (alphaTexture.coordinatesIndex === 1) {
  52211. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52212. defines.push("#define UV2");
  52213. }
  52214. }
  52215. }
  52216. }
  52217. // Bones
  52218. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52219. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52220. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52221. if (mesh.numBoneInfluencers > 4) {
  52222. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52223. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52224. }
  52225. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52226. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52227. }
  52228. else {
  52229. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52230. }
  52231. // Instances
  52232. if (useInstances) {
  52233. defines.push("#define INSTANCES");
  52234. attribs.push("world0");
  52235. attribs.push("world1");
  52236. attribs.push("world2");
  52237. attribs.push("world3");
  52238. }
  52239. // Get correct effect
  52240. var join = defines.join("\n");
  52241. if (this._cachedDefines !== join) {
  52242. this._cachedDefines = join;
  52243. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  52244. }
  52245. return this._effect.isReady();
  52246. };
  52247. /**
  52248. * This creates the defines related to the standard BJS materials.
  52249. */
  52250. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  52251. var scene = this._scene;
  52252. var light = this._light;
  52253. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  52254. return;
  52255. }
  52256. defines["SHADOW" + lightIndex] = true;
  52257. if (this.usePoissonSampling) {
  52258. defines["SHADOWPCF" + lightIndex] = true;
  52259. }
  52260. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  52261. defines["SHADOWESM" + lightIndex] = true;
  52262. }
  52263. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  52264. defines["SHADOWCLOSEESM" + lightIndex] = true;
  52265. }
  52266. if (light.needCube()) {
  52267. defines["SHADOWCUBE" + lightIndex] = true;
  52268. }
  52269. };
  52270. /**
  52271. * This binds shadow lights related to the standard BJS materials.
  52272. * It implies the unifroms available on the materials are the standard BJS ones.
  52273. */
  52274. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  52275. var light = this._light;
  52276. var scene = this._scene;
  52277. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  52278. return;
  52279. }
  52280. var camera = scene.activeCamera;
  52281. if (!camera) {
  52282. return;
  52283. }
  52284. var shadowMap = this.getShadowMap();
  52285. if (!shadowMap) {
  52286. return;
  52287. }
  52288. if (!light.needCube()) {
  52289. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  52290. }
  52291. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  52292. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  52293. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  52294. };
  52295. // Methods
  52296. /**
  52297. * Returns a Matrix object : the updated transformation matrix.
  52298. */
  52299. ShadowGenerator.prototype.getTransformMatrix = function () {
  52300. var scene = this._scene;
  52301. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  52302. return this._transformMatrix;
  52303. }
  52304. this._currentRenderID = scene.getRenderId();
  52305. this._currentFaceIndexCache = this._currentFaceIndex;
  52306. var lightPosition = this._light.position;
  52307. if (this._light.computeTransformedInformation()) {
  52308. lightPosition = this._light.transformedPosition;
  52309. }
  52310. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  52311. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  52312. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  52313. }
  52314. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  52315. this._cachedPosition = lightPosition.clone();
  52316. this._cachedDirection = this._lightDirection.clone();
  52317. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  52318. var shadowMap = this.getShadowMap();
  52319. if (shadowMap) {
  52320. var renderList = shadowMap.renderList;
  52321. if (renderList) {
  52322. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  52323. }
  52324. }
  52325. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  52326. }
  52327. return this._transformMatrix;
  52328. };
  52329. ShadowGenerator.prototype.recreateShadowMap = function () {
  52330. var shadowMap = this._shadowMap;
  52331. if (!shadowMap) {
  52332. return;
  52333. }
  52334. // Track render list.
  52335. var renderList = shadowMap.renderList;
  52336. // Clean up existing data.
  52337. this._disposeRTTandPostProcesses();
  52338. // Reinitializes.
  52339. this._initializeGenerator();
  52340. // Reaffect the filter to ensure a correct fallback if necessary.
  52341. this.filter = this.filter;
  52342. // Reaffect the filter.
  52343. this._applyFilterValues();
  52344. // Reaffect Render List.
  52345. this._shadowMap.renderList = renderList;
  52346. };
  52347. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  52348. if (this._shadowMap2) {
  52349. this._shadowMap2.dispose();
  52350. this._shadowMap2 = null;
  52351. }
  52352. if (this._downSamplePostprocess) {
  52353. this._downSamplePostprocess.dispose();
  52354. this._downSamplePostprocess = null;
  52355. }
  52356. if (this._boxBlurPostprocess) {
  52357. this._boxBlurPostprocess.dispose();
  52358. this._boxBlurPostprocess = null;
  52359. }
  52360. if (this._kernelBlurXPostprocess) {
  52361. this._kernelBlurXPostprocess.dispose();
  52362. this._kernelBlurXPostprocess = null;
  52363. }
  52364. if (this._kernelBlurYPostprocess) {
  52365. this._kernelBlurYPostprocess.dispose();
  52366. this._kernelBlurYPostprocess = null;
  52367. }
  52368. this._blurPostProcesses = [];
  52369. };
  52370. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  52371. if (this._shadowMap) {
  52372. this._shadowMap.dispose();
  52373. this._shadowMap = null;
  52374. }
  52375. this._disposeBlurPostProcesses();
  52376. };
  52377. /**
  52378. * Disposes the ShadowGenerator.
  52379. * Returns nothing.
  52380. */
  52381. ShadowGenerator.prototype.dispose = function () {
  52382. this._disposeRTTandPostProcesses();
  52383. if (this._light) {
  52384. this._light._shadowGenerator = null;
  52385. this._light._markMeshesAsLightDirty();
  52386. }
  52387. };
  52388. /**
  52389. * Serializes the ShadowGenerator and returns a serializationObject.
  52390. */
  52391. ShadowGenerator.prototype.serialize = function () {
  52392. var serializationObject = {};
  52393. var shadowMap = this.getShadowMap();
  52394. if (!shadowMap) {
  52395. return serializationObject;
  52396. }
  52397. serializationObject.lightId = this._light.id;
  52398. serializationObject.mapSize = shadowMap.getRenderSize();
  52399. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  52400. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  52401. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  52402. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  52403. serializationObject.usePoissonSampling = this.usePoissonSampling;
  52404. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  52405. serializationObject.depthScale = this.depthScale;
  52406. serializationObject.darkness = this.getDarkness();
  52407. serializationObject.blurBoxOffset = this.blurBoxOffset;
  52408. serializationObject.blurKernel = this.blurKernel;
  52409. serializationObject.blurScale = this.blurScale;
  52410. serializationObject.useKernelBlur = this.useKernelBlur;
  52411. serializationObject.transparencyShadow = this._transparencyShadow;
  52412. serializationObject.renderList = [];
  52413. if (shadowMap.renderList) {
  52414. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  52415. var mesh = shadowMap.renderList[meshIndex];
  52416. serializationObject.renderList.push(mesh.id);
  52417. }
  52418. }
  52419. return serializationObject;
  52420. };
  52421. /**
  52422. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  52423. */
  52424. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  52425. //casting to point light, as light is missing the position attr and typescript complains.
  52426. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  52427. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  52428. var shadowMap = shadowGenerator.getShadowMap();
  52429. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  52430. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  52431. meshes.forEach(function (mesh) {
  52432. if (!shadowMap) {
  52433. return;
  52434. }
  52435. if (!shadowMap.renderList) {
  52436. shadowMap.renderList = [];
  52437. }
  52438. shadowMap.renderList.push(mesh);
  52439. });
  52440. }
  52441. if (parsedShadowGenerator.usePoissonSampling) {
  52442. shadowGenerator.usePoissonSampling = true;
  52443. }
  52444. else if (parsedShadowGenerator.useExponentialShadowMap) {
  52445. shadowGenerator.useExponentialShadowMap = true;
  52446. }
  52447. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  52448. shadowGenerator.useBlurExponentialShadowMap = true;
  52449. }
  52450. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  52451. shadowGenerator.useCloseExponentialShadowMap = true;
  52452. }
  52453. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  52454. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  52455. }
  52456. else if (parsedShadowGenerator.useVarianceShadowMap) {
  52457. shadowGenerator.useExponentialShadowMap = true;
  52458. }
  52459. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  52460. shadowGenerator.useBlurExponentialShadowMap = true;
  52461. }
  52462. if (parsedShadowGenerator.depthScale) {
  52463. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  52464. }
  52465. if (parsedShadowGenerator.blurScale) {
  52466. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  52467. }
  52468. if (parsedShadowGenerator.blurBoxOffset) {
  52469. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  52470. }
  52471. if (parsedShadowGenerator.useKernelBlur) {
  52472. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  52473. }
  52474. if (parsedShadowGenerator.blurKernel) {
  52475. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  52476. }
  52477. if (parsedShadowGenerator.bias !== undefined) {
  52478. shadowGenerator.bias = parsedShadowGenerator.bias;
  52479. }
  52480. if (parsedShadowGenerator.darkness) {
  52481. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  52482. }
  52483. if (parsedShadowGenerator.transparencyShadow) {
  52484. shadowGenerator.setTransparencyShadow(true);
  52485. }
  52486. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  52487. return shadowGenerator;
  52488. };
  52489. ShadowGenerator._FILTER_NONE = 0;
  52490. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  52491. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  52492. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  52493. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  52494. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  52495. return ShadowGenerator;
  52496. }());
  52497. BABYLON.ShadowGenerator = ShadowGenerator;
  52498. })(BABYLON || (BABYLON = {}));
  52499. //# sourceMappingURL=babylon.shadowGenerator.js.map
  52500. var BABYLON;
  52501. (function (BABYLON) {
  52502. var DefaultLoadingScreen = /** @class */ (function () {
  52503. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  52504. if (_loadingText === void 0) { _loadingText = ""; }
  52505. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  52506. var _this = this;
  52507. this._renderingCanvas = _renderingCanvas;
  52508. this._loadingText = _loadingText;
  52509. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  52510. // Resize
  52511. this._resizeLoadingUI = function () {
  52512. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  52513. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  52514. if (!_this._loadingDiv) {
  52515. return;
  52516. }
  52517. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  52518. _this._loadingDiv.style.left = canvasRect.left + "px";
  52519. _this._loadingDiv.style.top = canvasRect.top + "px";
  52520. _this._loadingDiv.style.width = canvasRect.width + "px";
  52521. _this._loadingDiv.style.height = canvasRect.height + "px";
  52522. };
  52523. }
  52524. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  52525. if (this._loadingDiv) {
  52526. // Do not add a loading screen if there is already one
  52527. return;
  52528. }
  52529. this._loadingDiv = document.createElement("div");
  52530. this._loadingDiv.id = "babylonjsLoadingDiv";
  52531. this._loadingDiv.style.opacity = "0";
  52532. this._loadingDiv.style.transition = "opacity 1.5s ease";
  52533. this._loadingDiv.style.pointerEvents = "none";
  52534. // Loading text
  52535. this._loadingTextDiv = document.createElement("div");
  52536. this._loadingTextDiv.style.position = "absolute";
  52537. this._loadingTextDiv.style.left = "0";
  52538. this._loadingTextDiv.style.top = "50%";
  52539. this._loadingTextDiv.style.marginTop = "80px";
  52540. this._loadingTextDiv.style.width = "100%";
  52541. this._loadingTextDiv.style.height = "20px";
  52542. this._loadingTextDiv.style.fontFamily = "Arial";
  52543. this._loadingTextDiv.style.fontSize = "14px";
  52544. this._loadingTextDiv.style.color = "white";
  52545. this._loadingTextDiv.style.textAlign = "center";
  52546. this._loadingTextDiv.innerHTML = "Loading";
  52547. this._loadingDiv.appendChild(this._loadingTextDiv);
  52548. //set the predefined text
  52549. this._loadingTextDiv.innerHTML = this._loadingText;
  52550. // Generating keyframes
  52551. var style = document.createElement('style');
  52552. style.type = 'text/css';
  52553. 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 }";
  52554. style.innerHTML = keyFrames;
  52555. document.getElementsByTagName('head')[0].appendChild(style);
  52556. // Loading img
  52557. var imgBack = new Image();
  52558. 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";
  52559. imgBack.style.position = "absolute";
  52560. imgBack.style.left = "50%";
  52561. imgBack.style.top = "50%";
  52562. imgBack.style.marginLeft = "-60px";
  52563. imgBack.style.marginTop = "-60px";
  52564. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  52565. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  52566. imgBack.style.transformOrigin = "50% 50%";
  52567. imgBack.style.webkitTransformOrigin = "50% 50%";
  52568. this._loadingDiv.appendChild(imgBack);
  52569. this._resizeLoadingUI();
  52570. window.addEventListener("resize", this._resizeLoadingUI);
  52571. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  52572. document.body.appendChild(this._loadingDiv);
  52573. this._loadingDiv.style.opacity = "1";
  52574. };
  52575. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  52576. var _this = this;
  52577. if (!this._loadingDiv) {
  52578. return;
  52579. }
  52580. var onTransitionEnd = function () {
  52581. if (!_this._loadingDiv) {
  52582. return;
  52583. }
  52584. document.body.removeChild(_this._loadingDiv);
  52585. window.removeEventListener("resize", _this._resizeLoadingUI);
  52586. _this._loadingDiv = null;
  52587. };
  52588. this._loadingDiv.style.opacity = "0";
  52589. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  52590. };
  52591. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  52592. set: function (text) {
  52593. this._loadingText = text;
  52594. if (this._loadingTextDiv) {
  52595. this._loadingTextDiv.innerHTML = this._loadingText;
  52596. }
  52597. },
  52598. enumerable: true,
  52599. configurable: true
  52600. });
  52601. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  52602. get: function () {
  52603. return this._loadingDivBackgroundColor;
  52604. },
  52605. set: function (color) {
  52606. this._loadingDivBackgroundColor = color;
  52607. if (!this._loadingDiv) {
  52608. return;
  52609. }
  52610. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  52611. },
  52612. enumerable: true,
  52613. configurable: true
  52614. });
  52615. return DefaultLoadingScreen;
  52616. }());
  52617. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  52618. })(BABYLON || (BABYLON = {}));
  52619. //# sourceMappingURL=babylon.loadingScreen.js.map
  52620. var BABYLON;
  52621. (function (BABYLON) {
  52622. var SceneLoader = /** @class */ (function () {
  52623. function SceneLoader() {
  52624. }
  52625. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  52626. get: function () {
  52627. return 0;
  52628. },
  52629. enumerable: true,
  52630. configurable: true
  52631. });
  52632. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  52633. get: function () {
  52634. return 1;
  52635. },
  52636. enumerable: true,
  52637. configurable: true
  52638. });
  52639. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  52640. get: function () {
  52641. return 2;
  52642. },
  52643. enumerable: true,
  52644. configurable: true
  52645. });
  52646. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  52647. get: function () {
  52648. return 3;
  52649. },
  52650. enumerable: true,
  52651. configurable: true
  52652. });
  52653. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  52654. get: function () {
  52655. return SceneLoader._ForceFullSceneLoadingForIncremental;
  52656. },
  52657. set: function (value) {
  52658. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  52659. },
  52660. enumerable: true,
  52661. configurable: true
  52662. });
  52663. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  52664. get: function () {
  52665. return SceneLoader._ShowLoadingScreen;
  52666. },
  52667. set: function (value) {
  52668. SceneLoader._ShowLoadingScreen = value;
  52669. },
  52670. enumerable: true,
  52671. configurable: true
  52672. });
  52673. Object.defineProperty(SceneLoader, "loggingLevel", {
  52674. get: function () {
  52675. return SceneLoader._loggingLevel;
  52676. },
  52677. set: function (value) {
  52678. SceneLoader._loggingLevel = value;
  52679. },
  52680. enumerable: true,
  52681. configurable: true
  52682. });
  52683. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  52684. get: function () {
  52685. return SceneLoader._CleanBoneMatrixWeights;
  52686. },
  52687. set: function (value) {
  52688. SceneLoader._CleanBoneMatrixWeights = value;
  52689. },
  52690. enumerable: true,
  52691. configurable: true
  52692. });
  52693. SceneLoader._getDefaultPlugin = function () {
  52694. return SceneLoader._registeredPlugins[".babylon"];
  52695. };
  52696. SceneLoader._getPluginForExtension = function (extension) {
  52697. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  52698. if (registeredPlugin) {
  52699. return registeredPlugin;
  52700. }
  52701. return SceneLoader._getDefaultPlugin();
  52702. };
  52703. SceneLoader._getPluginForDirectLoad = function (data) {
  52704. for (var extension in SceneLoader._registeredPlugins) {
  52705. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  52706. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  52707. return SceneLoader._registeredPlugins[extension];
  52708. }
  52709. }
  52710. return SceneLoader._getDefaultPlugin();
  52711. };
  52712. SceneLoader._getPluginForFilename = function (sceneFilename) {
  52713. if (sceneFilename.name) {
  52714. sceneFilename = sceneFilename.name;
  52715. }
  52716. var queryStringPosition = sceneFilename.indexOf("?");
  52717. if (queryStringPosition !== -1) {
  52718. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  52719. }
  52720. var dotPosition = sceneFilename.lastIndexOf(".");
  52721. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  52722. return SceneLoader._getPluginForExtension(extension);
  52723. };
  52724. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  52725. SceneLoader._getDirectLoad = function (sceneFilename) {
  52726. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  52727. return sceneFilename.substr(5);
  52728. }
  52729. return null;
  52730. };
  52731. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52732. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  52733. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  52734. var plugin;
  52735. if (registeredPlugin.plugin.createPlugin) {
  52736. plugin = registeredPlugin.plugin.createPlugin();
  52737. }
  52738. else {
  52739. plugin = registeredPlugin.plugin;
  52740. }
  52741. var useArrayBuffer = registeredPlugin.isBinary;
  52742. var database;
  52743. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  52744. var dataCallback = function (data, responseURL) {
  52745. if (scene.isDisposed) {
  52746. onError("Scene has been disposed");
  52747. return;
  52748. }
  52749. scene.database = database;
  52750. try {
  52751. onSuccess(plugin, data, responseURL);
  52752. }
  52753. catch (e) {
  52754. onError(null, e);
  52755. }
  52756. };
  52757. var manifestChecked = function (success) {
  52758. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  52759. if (request) {
  52760. onError(request.status + " " + request.statusText);
  52761. }
  52762. });
  52763. };
  52764. if (directLoad) {
  52765. dataCallback(directLoad);
  52766. return plugin;
  52767. }
  52768. if (rootUrl.indexOf("file:") === -1) {
  52769. if (scene.getEngine().enableOfflineSupport) {
  52770. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  52771. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  52772. }
  52773. else {
  52774. manifestChecked(true);
  52775. }
  52776. }
  52777. else {
  52778. var fileOrString = sceneFilename;
  52779. if (fileOrString.name) {
  52780. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  52781. }
  52782. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  52783. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  52784. }
  52785. else {
  52786. onError("Unable to find file named " + sceneFilename);
  52787. }
  52788. }
  52789. return plugin;
  52790. };
  52791. // Public functions
  52792. SceneLoader.GetPluginForExtension = function (extension) {
  52793. return SceneLoader._getPluginForExtension(extension).plugin;
  52794. };
  52795. SceneLoader.RegisterPlugin = function (plugin) {
  52796. if (typeof plugin.extensions === "string") {
  52797. var extension = plugin.extensions;
  52798. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52799. plugin: plugin,
  52800. isBinary: false
  52801. };
  52802. }
  52803. else {
  52804. var extensions = plugin.extensions;
  52805. Object.keys(extensions).forEach(function (extension) {
  52806. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52807. plugin: plugin,
  52808. isBinary: extensions[extension].isBinary
  52809. };
  52810. });
  52811. }
  52812. };
  52813. /**
  52814. * Import meshes into a scene
  52815. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  52816. * @param rootUrl a string that defines the root url for scene and resources
  52817. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52818. * @param scene the instance of BABYLON.Scene to append to
  52819. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  52820. * @param onProgress a callback with a progress event for each file being loaded
  52821. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52822. */
  52823. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52824. if (onSuccess === void 0) { onSuccess = null; }
  52825. if (onProgress === void 0) { onProgress = null; }
  52826. if (onError === void 0) { onError = null; }
  52827. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52828. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52829. return null;
  52830. }
  52831. var loadingToken = {};
  52832. scene._addPendingData(loadingToken);
  52833. var errorHandler = function (message, exception) {
  52834. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52835. if (onError) {
  52836. onError(scene, errorMessage, exception);
  52837. }
  52838. else {
  52839. BABYLON.Tools.Error(errorMessage);
  52840. // should the exception be thrown?
  52841. }
  52842. scene._removePendingData(loadingToken);
  52843. };
  52844. var progressHandler = function (event) {
  52845. if (onProgress) {
  52846. onProgress(event);
  52847. }
  52848. };
  52849. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  52850. if (plugin.rewriteRootURL) {
  52851. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  52852. }
  52853. if (plugin.importMesh) {
  52854. var syncedPlugin = plugin;
  52855. var meshes = new Array();
  52856. var particleSystems = new Array();
  52857. var skeletons = new Array();
  52858. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  52859. return;
  52860. }
  52861. if (onSuccess) {
  52862. // wrap onSuccess with try-catch to know if something went wrong.
  52863. try {
  52864. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52865. onSuccess(meshes, particleSystems, skeletons);
  52866. scene._removePendingData(loadingToken);
  52867. }
  52868. catch (e) {
  52869. var message = 'Error in onSuccess callback.';
  52870. errorHandler(message, e);
  52871. }
  52872. }
  52873. }
  52874. else {
  52875. var asyncedPlugin = plugin;
  52876. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  52877. if (onSuccess) {
  52878. try {
  52879. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52880. onSuccess(meshes, particleSystems, skeletons);
  52881. scene._removePendingData(loadingToken);
  52882. }
  52883. catch (e) {
  52884. var message = 'Error in onSuccess callback.';
  52885. errorHandler(message, e);
  52886. }
  52887. }
  52888. }, progressHandler, errorHandler);
  52889. }
  52890. }, progressHandler, errorHandler, pluginExtension);
  52891. };
  52892. /**
  52893. * Load a scene
  52894. * @param rootUrl a string that defines the root url for scene and resources
  52895. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52896. * @param engine is the instance of BABYLON.Engine to use to create the scene
  52897. * @param onSuccess a callback with the scene when import succeeds
  52898. * @param onProgress a callback with a progress event for each file being loaded
  52899. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52900. */
  52901. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  52902. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  52903. };
  52904. /**
  52905. * Append a scene
  52906. * @param rootUrl a string that defines the root url for scene and resources
  52907. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52908. * @param scene is the instance of BABYLON.Scene to append to
  52909. * @param onSuccess a callback with the scene when import succeeds
  52910. * @param onProgress a callback with a progress event for each file being loaded
  52911. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52912. */
  52913. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52914. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52915. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52916. return null;
  52917. }
  52918. if (SceneLoader.ShowLoadingScreen) {
  52919. scene.getEngine().displayLoadingUI();
  52920. }
  52921. var loadingToken = {};
  52922. scene._addPendingData(loadingToken);
  52923. var errorHandler = function (message, exception) {
  52924. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52925. if (onError) {
  52926. onError(scene, errorMessage, exception);
  52927. }
  52928. else {
  52929. BABYLON.Tools.Error(errorMessage);
  52930. // should the exception be thrown?
  52931. }
  52932. scene._removePendingData(loadingToken);
  52933. scene.getEngine().hideLoadingUI();
  52934. };
  52935. var progressHandler = function (event) {
  52936. if (onProgress) {
  52937. onProgress(event);
  52938. }
  52939. };
  52940. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  52941. if (plugin.load) {
  52942. var syncedPlugin = plugin;
  52943. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  52944. return;
  52945. }
  52946. if (onSuccess) {
  52947. try {
  52948. onSuccess(scene);
  52949. }
  52950. catch (e) {
  52951. errorHandler("Error in onSuccess callback", e);
  52952. }
  52953. }
  52954. scene.loadingPluginName = plugin.name;
  52955. scene._removePendingData(loadingToken);
  52956. }
  52957. else {
  52958. var asyncedPlugin = plugin;
  52959. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  52960. if (onSuccess) {
  52961. onSuccess(scene);
  52962. }
  52963. scene.loadingPluginName = plugin.name;
  52964. scene._removePendingData(loadingToken);
  52965. }, progressHandler, errorHandler);
  52966. }
  52967. if (SceneLoader.ShowLoadingScreen) {
  52968. scene.executeWhenReady(function () {
  52969. scene.getEngine().hideLoadingUI();
  52970. });
  52971. }
  52972. }, progressHandler, errorHandler, pluginExtension);
  52973. };
  52974. // Flags
  52975. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  52976. SceneLoader._ShowLoadingScreen = true;
  52977. SceneLoader._CleanBoneMatrixWeights = false;
  52978. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  52979. // Members
  52980. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  52981. SceneLoader._registeredPlugins = {};
  52982. return SceneLoader;
  52983. }());
  52984. BABYLON.SceneLoader = SceneLoader;
  52985. ;
  52986. })(BABYLON || (BABYLON = {}));
  52987. //# sourceMappingURL=babylon.sceneLoader.js.map
  52988. var BABYLON;
  52989. (function (BABYLON) {
  52990. var Internals;
  52991. (function (Internals) {
  52992. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  52993. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52994. var parsedMaterial = parsedData.materials[index];
  52995. if (parsedMaterial.id === id) {
  52996. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52997. }
  52998. }
  52999. return null;
  53000. };
  53001. var isDescendantOf = function (mesh, names, hierarchyIds) {
  53002. for (var i in names) {
  53003. if (mesh.name === names[i]) {
  53004. hierarchyIds.push(mesh.id);
  53005. return true;
  53006. }
  53007. }
  53008. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  53009. hierarchyIds.push(mesh.id);
  53010. return true;
  53011. }
  53012. return false;
  53013. };
  53014. var logOperation = function (operation, producer) {
  53015. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  53016. };
  53017. BABYLON.SceneLoader.RegisterPlugin({
  53018. name: "babylon.js",
  53019. extensions: ".babylon",
  53020. canDirectLoad: function (data) {
  53021. if (data.indexOf("babylon") !== -1) {
  53022. return true;
  53023. }
  53024. return false;
  53025. },
  53026. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  53027. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  53028. // when SceneLoader.debugLogging = true (default), or exception encountered.
  53029. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  53030. // and avoid problems with multiple concurrent .babylon loads.
  53031. var log = "importMesh has failed JSON parse";
  53032. try {
  53033. var parsedData = JSON.parse(data);
  53034. log = "";
  53035. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  53036. if (!meshesNames) {
  53037. meshesNames = null;
  53038. }
  53039. else if (!Array.isArray(meshesNames)) {
  53040. meshesNames = [meshesNames];
  53041. }
  53042. var hierarchyIds = new Array();
  53043. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  53044. var loadedSkeletonsIds = [];
  53045. var loadedMaterialsIds = [];
  53046. var index;
  53047. var cache;
  53048. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  53049. var parsedMesh = parsedData.meshes[index];
  53050. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  53051. if (meshesNames !== null) {
  53052. // Remove found mesh name from list.
  53053. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  53054. }
  53055. //Geometry?
  53056. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  53057. //does the file contain geometries?
  53058. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  53059. //find the correct geometry and add it to the scene
  53060. var found = false;
  53061. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  53062. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  53063. return;
  53064. }
  53065. else {
  53066. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  53067. if (parsedGeometryData.id === parsedMesh.geometryId) {
  53068. switch (geometryType) {
  53069. case "boxes":
  53070. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  53071. break;
  53072. case "spheres":
  53073. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  53074. break;
  53075. case "cylinders":
  53076. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  53077. break;
  53078. case "toruses":
  53079. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  53080. break;
  53081. case "grounds":
  53082. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  53083. break;
  53084. case "planes":
  53085. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  53086. break;
  53087. case "torusKnots":
  53088. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  53089. break;
  53090. case "vertexData":
  53091. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  53092. break;
  53093. }
  53094. found = true;
  53095. }
  53096. });
  53097. }
  53098. });
  53099. if (found === false) {
  53100. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  53101. }
  53102. }
  53103. }
  53104. // Material ?
  53105. if (parsedMesh.materialId) {
  53106. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  53107. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53108. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  53109. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  53110. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  53111. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  53112. var subMatId = parsedMultiMaterial.materials[matIndex];
  53113. loadedMaterialsIds.push(subMatId);
  53114. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  53115. log += "\n\tMaterial " + mat.toString(fullDetails);
  53116. }
  53117. loadedMaterialsIds.push(parsedMultiMaterial.id);
  53118. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53119. materialFound = true;
  53120. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  53121. break;
  53122. }
  53123. }
  53124. }
  53125. if (materialFound === false) {
  53126. loadedMaterialsIds.push(parsedMesh.materialId);
  53127. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  53128. if (!mat) {
  53129. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  53130. }
  53131. else {
  53132. log += "\n\tMaterial " + mat.toString(fullDetails);
  53133. }
  53134. }
  53135. }
  53136. // Skeleton ?
  53137. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53138. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  53139. if (skeletonAlreadyLoaded === false) {
  53140. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  53141. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  53142. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  53143. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53144. skeletons.push(skeleton);
  53145. loadedSkeletonsIds.push(parsedSkeleton.id);
  53146. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  53147. }
  53148. }
  53149. }
  53150. }
  53151. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53152. meshes.push(mesh);
  53153. log += "\n\tMesh " + mesh.toString(fullDetails);
  53154. }
  53155. }
  53156. // Connecting parents
  53157. var currentMesh;
  53158. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53159. currentMesh = scene.meshes[index];
  53160. if (currentMesh._waitingParentId) {
  53161. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  53162. currentMesh._waitingParentId = null;
  53163. }
  53164. }
  53165. // freeze and compute world matrix application
  53166. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53167. currentMesh = scene.meshes[index];
  53168. if (currentMesh._waitingFreezeWorldMatrix) {
  53169. currentMesh.freezeWorldMatrix();
  53170. currentMesh._waitingFreezeWorldMatrix = null;
  53171. }
  53172. else {
  53173. currentMesh.computeWorldMatrix(true);
  53174. }
  53175. }
  53176. }
  53177. // Particles
  53178. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  53179. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  53180. var parsedParticleSystem = parsedData.particleSystems[index];
  53181. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  53182. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  53183. }
  53184. }
  53185. }
  53186. return true;
  53187. }
  53188. catch (err) {
  53189. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  53190. if (onError) {
  53191. onError(msg, err);
  53192. }
  53193. else {
  53194. BABYLON.Tools.Log(msg);
  53195. throw err;
  53196. }
  53197. }
  53198. finally {
  53199. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  53200. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  53201. }
  53202. }
  53203. return false;
  53204. },
  53205. load: function (scene, data, rootUrl, onError) {
  53206. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  53207. // when SceneLoader.debugLogging = true (default), or exception encountered.
  53208. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  53209. // and avoid problems with multiple concurrent .babylon loads.
  53210. var log = "importScene has failed JSON parse";
  53211. try {
  53212. var parsedData = JSON.parse(data);
  53213. log = "";
  53214. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  53215. // Scene
  53216. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  53217. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  53218. }
  53219. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  53220. scene.autoClear = parsedData.autoClear;
  53221. }
  53222. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  53223. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  53224. }
  53225. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  53226. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  53227. }
  53228. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  53229. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  53230. }
  53231. // Fog
  53232. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  53233. scene.fogMode = parsedData.fogMode;
  53234. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  53235. scene.fogStart = parsedData.fogStart;
  53236. scene.fogEnd = parsedData.fogEnd;
  53237. scene.fogDensity = parsedData.fogDensity;
  53238. log += "\tFog mode for scene: ";
  53239. switch (scene.fogMode) {
  53240. // getters not compiling, so using hardcoded
  53241. case 1:
  53242. log += "exp\n";
  53243. break;
  53244. case 2:
  53245. log += "exp2\n";
  53246. break;
  53247. case 3:
  53248. log += "linear\n";
  53249. break;
  53250. }
  53251. }
  53252. //Physics
  53253. if (parsedData.physicsEnabled) {
  53254. var physicsPlugin;
  53255. if (parsedData.physicsEngine === "cannon") {
  53256. physicsPlugin = new BABYLON.CannonJSPlugin();
  53257. }
  53258. else if (parsedData.physicsEngine === "oimo") {
  53259. physicsPlugin = new BABYLON.OimoJSPlugin();
  53260. }
  53261. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  53262. //else - default engine, which is currently oimo
  53263. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  53264. scene.enablePhysics(physicsGravity, physicsPlugin);
  53265. }
  53266. // Metadata
  53267. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  53268. scene.metadata = parsedData.metadata;
  53269. }
  53270. //collisions, if defined. otherwise, default is true
  53271. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  53272. scene.collisionsEnabled = parsedData.collisionsEnabled;
  53273. }
  53274. scene.workerCollisions = !!parsedData.workerCollisions;
  53275. var index;
  53276. var cache;
  53277. // Lights
  53278. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  53279. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  53280. var parsedLight = parsedData.lights[index];
  53281. var light = BABYLON.Light.Parse(parsedLight, scene);
  53282. if (light) {
  53283. log += (index === 0 ? "\n\tLights:" : "");
  53284. log += "\n\t\t" + light.toString(fullDetails);
  53285. }
  53286. }
  53287. }
  53288. // Animations
  53289. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  53290. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  53291. var parsedAnimation = parsedData.animations[index];
  53292. var animation = BABYLON.Animation.Parse(parsedAnimation);
  53293. scene.animations.push(animation);
  53294. log += (index === 0 ? "\n\tAnimations:" : "");
  53295. log += "\n\t\t" + animation.toString(fullDetails);
  53296. }
  53297. }
  53298. if (parsedData.autoAnimate) {
  53299. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  53300. }
  53301. // Materials
  53302. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  53303. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  53304. var parsedMaterial = parsedData.materials[index];
  53305. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  53306. log += (index === 0 ? "\n\tMaterials:" : "");
  53307. log += "\n\t\t" + mat.toString(fullDetails);
  53308. }
  53309. }
  53310. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53311. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  53312. var parsedMultiMaterial = parsedData.multiMaterials[index];
  53313. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53314. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  53315. log += "\n\t\t" + mmat.toString(fullDetails);
  53316. }
  53317. }
  53318. // Morph targets
  53319. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  53320. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  53321. var managerData = _a[_i];
  53322. BABYLON.MorphTargetManager.Parse(managerData, scene);
  53323. }
  53324. }
  53325. // Skeletons
  53326. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53327. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  53328. var parsedSkeleton = parsedData.skeletons[index];
  53329. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53330. log += (index === 0 ? "\n\tSkeletons:" : "");
  53331. log += "\n\t\t" + skeleton.toString(fullDetails);
  53332. }
  53333. }
  53334. // Geometries
  53335. var geometries = parsedData.geometries;
  53336. if (geometries !== undefined && geometries !== null) {
  53337. // Boxes
  53338. var boxes = geometries.boxes;
  53339. if (boxes !== undefined && boxes !== null) {
  53340. for (index = 0, cache = boxes.length; index < cache; index++) {
  53341. var parsedBox = boxes[index];
  53342. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  53343. }
  53344. }
  53345. // Spheres
  53346. var spheres = geometries.spheres;
  53347. if (spheres !== undefined && spheres !== null) {
  53348. for (index = 0, cache = spheres.length; index < cache; index++) {
  53349. var parsedSphere = spheres[index];
  53350. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  53351. }
  53352. }
  53353. // Cylinders
  53354. var cylinders = geometries.cylinders;
  53355. if (cylinders !== undefined && cylinders !== null) {
  53356. for (index = 0, cache = cylinders.length; index < cache; index++) {
  53357. var parsedCylinder = cylinders[index];
  53358. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  53359. }
  53360. }
  53361. // Toruses
  53362. var toruses = geometries.toruses;
  53363. if (toruses !== undefined && toruses !== null) {
  53364. for (index = 0, cache = toruses.length; index < cache; index++) {
  53365. var parsedTorus = toruses[index];
  53366. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  53367. }
  53368. }
  53369. // Grounds
  53370. var grounds = geometries.grounds;
  53371. if (grounds !== undefined && grounds !== null) {
  53372. for (index = 0, cache = grounds.length; index < cache; index++) {
  53373. var parsedGround = grounds[index];
  53374. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  53375. }
  53376. }
  53377. // Planes
  53378. var planes = geometries.planes;
  53379. if (planes !== undefined && planes !== null) {
  53380. for (index = 0, cache = planes.length; index < cache; index++) {
  53381. var parsedPlane = planes[index];
  53382. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  53383. }
  53384. }
  53385. // TorusKnots
  53386. var torusKnots = geometries.torusKnots;
  53387. if (torusKnots !== undefined && torusKnots !== null) {
  53388. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  53389. var parsedTorusKnot = torusKnots[index];
  53390. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  53391. }
  53392. }
  53393. // VertexData
  53394. var vertexData = geometries.vertexData;
  53395. if (vertexData !== undefined && vertexData !== null) {
  53396. for (index = 0, cache = vertexData.length; index < cache; index++) {
  53397. var parsedVertexData = vertexData[index];
  53398. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  53399. }
  53400. }
  53401. }
  53402. // Transform nodes
  53403. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  53404. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  53405. var parsedTransformNode = parsedData.transformNodes[index];
  53406. BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  53407. }
  53408. }
  53409. // Meshes
  53410. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  53411. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  53412. var parsedMesh = parsedData.meshes[index];
  53413. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53414. log += (index === 0 ? "\n\tMeshes:" : "");
  53415. log += "\n\t\t" + mesh.toString(fullDetails);
  53416. }
  53417. }
  53418. // Cameras
  53419. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  53420. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  53421. var parsedCamera = parsedData.cameras[index];
  53422. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  53423. log += (index === 0 ? "\n\tCameras:" : "");
  53424. log += "\n\t\t" + camera.toString(fullDetails);
  53425. }
  53426. }
  53427. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  53428. scene.setActiveCameraByID(parsedData.activeCameraID);
  53429. }
  53430. // Browsing all the graph to connect the dots
  53431. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  53432. var camera = scene.cameras[index];
  53433. if (camera._waitingParentId) {
  53434. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  53435. camera._waitingParentId = null;
  53436. }
  53437. }
  53438. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  53439. var light_1 = scene.lights[index];
  53440. if (light_1 && light_1._waitingParentId) {
  53441. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  53442. light_1._waitingParentId = null;
  53443. }
  53444. }
  53445. // Sounds
  53446. var loadedSounds = [];
  53447. var loadedSound;
  53448. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  53449. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  53450. var parsedSound = parsedData.sounds[index];
  53451. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53452. if (!parsedSound.url)
  53453. parsedSound.url = parsedSound.name;
  53454. if (!loadedSounds[parsedSound.url]) {
  53455. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  53456. loadedSounds[parsedSound.url] = loadedSound;
  53457. }
  53458. else {
  53459. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  53460. }
  53461. }
  53462. else {
  53463. new BABYLON.Sound(parsedSound.name, null, scene);
  53464. }
  53465. }
  53466. }
  53467. loadedSounds = [];
  53468. // Connect parents & children and parse actions
  53469. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  53470. var transformNode = scene.transformNodes[index];
  53471. if (transformNode._waitingParentId) {
  53472. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  53473. transformNode._waitingParentId = null;
  53474. }
  53475. }
  53476. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53477. var mesh = scene.meshes[index];
  53478. if (mesh._waitingParentId) {
  53479. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  53480. mesh._waitingParentId = null;
  53481. }
  53482. if (mesh._waitingActions) {
  53483. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  53484. mesh._waitingActions = null;
  53485. }
  53486. }
  53487. // freeze world matrix application
  53488. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53489. var currentMesh = scene.meshes[index];
  53490. if (currentMesh._waitingFreezeWorldMatrix) {
  53491. currentMesh.freezeWorldMatrix();
  53492. currentMesh._waitingFreezeWorldMatrix = null;
  53493. }
  53494. else {
  53495. currentMesh.computeWorldMatrix(true);
  53496. }
  53497. }
  53498. // Particles Systems
  53499. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  53500. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  53501. var parsedParticleSystem = parsedData.particleSystems[index];
  53502. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  53503. }
  53504. }
  53505. // Environment texture
  53506. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  53507. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  53508. if (parsedData.createDefaultSkybox === true) {
  53509. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  53510. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  53511. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  53512. }
  53513. }
  53514. // Lens flares
  53515. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  53516. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  53517. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  53518. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  53519. }
  53520. }
  53521. // Shadows
  53522. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  53523. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  53524. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  53525. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  53526. }
  53527. }
  53528. // Lights exclusions / inclusions
  53529. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  53530. var light_2 = scene.lights[index];
  53531. // Excluded check
  53532. if (light_2._excludedMeshesIds.length > 0) {
  53533. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  53534. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  53535. if (excludedMesh) {
  53536. light_2.excludedMeshes.push(excludedMesh);
  53537. }
  53538. }
  53539. light_2._excludedMeshesIds = [];
  53540. }
  53541. // Included check
  53542. if (light_2._includedOnlyMeshesIds.length > 0) {
  53543. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  53544. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  53545. if (includedOnlyMesh) {
  53546. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  53547. }
  53548. }
  53549. light_2._includedOnlyMeshesIds = [];
  53550. }
  53551. }
  53552. // Actions (scene)
  53553. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  53554. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  53555. }
  53556. // Finish
  53557. return true;
  53558. }
  53559. catch (err) {
  53560. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  53561. if (onError) {
  53562. onError(msg, err);
  53563. }
  53564. else {
  53565. BABYLON.Tools.Log(msg);
  53566. throw err;
  53567. }
  53568. }
  53569. finally {
  53570. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  53571. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  53572. }
  53573. }
  53574. return false;
  53575. }
  53576. });
  53577. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53578. })(BABYLON || (BABYLON = {}));
  53579. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  53580. var BABYLON;
  53581. (function (BABYLON) {
  53582. var FilesInput = /** @class */ (function () {
  53583. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  53584. this.onProcessFileCallback = function () { return true; };
  53585. this._engine = engine;
  53586. this._currentScene = scene;
  53587. this._sceneLoadedCallback = sceneLoadedCallback;
  53588. this._progressCallback = progressCallback;
  53589. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  53590. this._textureLoadingCallback = textureLoadingCallback;
  53591. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  53592. this._onReloadCallback = onReloadCallback;
  53593. this._errorCallback = errorCallback;
  53594. }
  53595. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  53596. var _this = this;
  53597. if (elementToMonitor) {
  53598. this._elementToMonitor = elementToMonitor;
  53599. this._dragEnterHandler = function (e) { _this.drag(e); };
  53600. this._dragOverHandler = function (e) { _this.drag(e); };
  53601. this._dropHandler = function (e) { _this.drop(e); };
  53602. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  53603. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  53604. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  53605. }
  53606. };
  53607. FilesInput.prototype.dispose = function () {
  53608. if (!this._elementToMonitor) {
  53609. return;
  53610. }
  53611. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  53612. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  53613. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  53614. };
  53615. FilesInput.prototype.renderFunction = function () {
  53616. if (this._additionalRenderLoopLogicCallback) {
  53617. this._additionalRenderLoopLogicCallback();
  53618. }
  53619. if (this._currentScene) {
  53620. if (this._textureLoadingCallback) {
  53621. var remaining = this._currentScene.getWaitingItemsCount();
  53622. if (remaining > 0) {
  53623. this._textureLoadingCallback(remaining);
  53624. }
  53625. }
  53626. this._currentScene.render();
  53627. }
  53628. };
  53629. FilesInput.prototype.drag = function (e) {
  53630. e.stopPropagation();
  53631. e.preventDefault();
  53632. };
  53633. FilesInput.prototype.drop = function (eventDrop) {
  53634. eventDrop.stopPropagation();
  53635. eventDrop.preventDefault();
  53636. this.loadFiles(eventDrop);
  53637. };
  53638. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  53639. var _this = this;
  53640. var reader = folder.createReader();
  53641. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  53642. reader.readEntries(function (entries) {
  53643. remaining.count += entries.length;
  53644. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  53645. var entry = entries_1[_i];
  53646. if (entry.isFile) {
  53647. entry.file(function (file) {
  53648. file.correctName = relativePath + file.name;
  53649. files.push(file);
  53650. if (--remaining.count === 0) {
  53651. callback();
  53652. }
  53653. });
  53654. }
  53655. else if (entry.isDirectory) {
  53656. _this._traverseFolder(entry, files, remaining, callback);
  53657. }
  53658. }
  53659. if (--remaining.count) {
  53660. callback();
  53661. }
  53662. });
  53663. };
  53664. FilesInput.prototype._processFiles = function (files) {
  53665. var skippedFiles = 0;
  53666. for (var i = 0; i < files.length; i++) {
  53667. var name = files[i].correctName.toLowerCase();
  53668. var extension = name.split('.').pop();
  53669. if (!this.onProcessFileCallback(files[i], name, extension)) {
  53670. skippedFiles++;
  53671. continue;
  53672. }
  53673. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  53674. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  53675. this._sceneFileToLoad = files[i];
  53676. }
  53677. else {
  53678. FilesInput.FilesToLoad[name] = files[i];
  53679. }
  53680. }
  53681. if (this._onReloadCallback) {
  53682. this._onReloadCallback(this._sceneFileToLoad);
  53683. }
  53684. else if (skippedFiles < files.length) {
  53685. this.reload();
  53686. }
  53687. };
  53688. FilesInput.prototype.loadFiles = function (event) {
  53689. var _this = this;
  53690. if (this._startingProcessingFilesCallback)
  53691. this._startingProcessingFilesCallback();
  53692. // Handling data transfer via drag'n'drop
  53693. if (event && event.dataTransfer && event.dataTransfer.files) {
  53694. this._filesToLoad = event.dataTransfer.files;
  53695. }
  53696. // Handling files from input files
  53697. if (event && event.target && event.target.files) {
  53698. this._filesToLoad = event.target.files;
  53699. }
  53700. if (this._filesToLoad && this._filesToLoad.length > 0) {
  53701. var files_1 = new Array();
  53702. var folders = [];
  53703. var items = event.dataTransfer ? event.dataTransfer.items : null;
  53704. for (var i = 0; i < this._filesToLoad.length; i++) {
  53705. var fileToLoad = this._filesToLoad[i];
  53706. var name_1 = fileToLoad.name.toLowerCase();
  53707. var entry = void 0;
  53708. fileToLoad.correctName = name_1;
  53709. if (items) {
  53710. var item = items[i];
  53711. if (item.getAsEntry) {
  53712. entry = item.getAsEntry();
  53713. }
  53714. else if (item.webkitGetAsEntry) {
  53715. entry = item.webkitGetAsEntry();
  53716. }
  53717. }
  53718. if (!entry) {
  53719. files_1.push(fileToLoad);
  53720. }
  53721. else {
  53722. if (entry.isDirectory) {
  53723. folders.push(entry);
  53724. }
  53725. else {
  53726. files_1.push(fileToLoad);
  53727. }
  53728. }
  53729. }
  53730. if (folders.length === 0) {
  53731. this._processFiles(files_1);
  53732. }
  53733. else {
  53734. var remaining = { count: folders.length };
  53735. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  53736. var folder = folders_1[_i];
  53737. this._traverseFolder(folder, files_1, remaining, function () {
  53738. _this._processFiles(files_1);
  53739. });
  53740. }
  53741. }
  53742. }
  53743. };
  53744. FilesInput.prototype.reload = function () {
  53745. var _this = this;
  53746. // If a ".babylon" file has been provided
  53747. if (this._sceneFileToLoad) {
  53748. if (this._currentScene) {
  53749. if (BABYLON.Tools.errorsCount > 0) {
  53750. BABYLON.Tools.ClearLogCache();
  53751. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  53752. }
  53753. this._engine.stopRenderLoop();
  53754. this._currentScene.dispose();
  53755. }
  53756. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  53757. _this._currentScene = newScene;
  53758. if (_this._sceneLoadedCallback) {
  53759. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  53760. }
  53761. // Wait for textures and shaders to be ready
  53762. _this._currentScene.executeWhenReady(function () {
  53763. _this._engine.runRenderLoop(function () {
  53764. _this.renderFunction();
  53765. });
  53766. });
  53767. }, function (progress) {
  53768. if (_this._progressCallback) {
  53769. _this._progressCallback(progress);
  53770. }
  53771. }, function (scene, message) {
  53772. _this._currentScene = scene;
  53773. if (_this._errorCallback) {
  53774. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  53775. }
  53776. });
  53777. }
  53778. else {
  53779. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  53780. }
  53781. };
  53782. FilesInput.FilesToLoad = {};
  53783. return FilesInput;
  53784. }());
  53785. BABYLON.FilesInput = FilesInput;
  53786. })(BABYLON || (BABYLON = {}));
  53787. //# sourceMappingURL=babylon.filesInput.js.map
  53788. var BABYLON;
  53789. (function (BABYLON) {
  53790. /**
  53791. * This class implement a typical dictionary using a string as key and the generic type T as value.
  53792. * The underlying implementation relies on an associative array to ensure the best performances.
  53793. * The value can be anything including 'null' but except 'undefined'
  53794. */
  53795. var StringDictionary = /** @class */ (function () {
  53796. function StringDictionary() {
  53797. this._count = 0;
  53798. this._data = {};
  53799. }
  53800. /**
  53801. * This will clear this dictionary and copy the content from the 'source' one.
  53802. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  53803. * @param source the dictionary to take the content from and copy to this dictionary
  53804. */
  53805. StringDictionary.prototype.copyFrom = function (source) {
  53806. var _this = this;
  53807. this.clear();
  53808. source.forEach(function (t, v) { return _this.add(t, v); });
  53809. };
  53810. /**
  53811. * Get a value based from its key
  53812. * @param key the given key to get the matching value from
  53813. * @return the value if found, otherwise undefined is returned
  53814. */
  53815. StringDictionary.prototype.get = function (key) {
  53816. var val = this._data[key];
  53817. if (val !== undefined) {
  53818. return val;
  53819. }
  53820. return undefined;
  53821. };
  53822. /**
  53823. * Get a value from its key or add it if it doesn't exist.
  53824. * This method will ensure you that a given key/data will be present in the dictionary.
  53825. * @param key the given key to get the matching value from
  53826. * @param factory the factory that will create the value if the key is not present in the dictionary.
  53827. * The factory will only be invoked if there's no data for the given key.
  53828. * @return the value corresponding to the key.
  53829. */
  53830. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  53831. var val = this.get(key);
  53832. if (val !== undefined) {
  53833. return val;
  53834. }
  53835. val = factory(key);
  53836. if (val) {
  53837. this.add(key, val);
  53838. }
  53839. return val;
  53840. };
  53841. /**
  53842. * Get a value from its key if present in the dictionary otherwise add it
  53843. * @param key the key to get the value from
  53844. * @param val if there's no such key/value pair in the dictionary add it with this value
  53845. * @return the value corresponding to the key
  53846. */
  53847. StringDictionary.prototype.getOrAdd = function (key, val) {
  53848. var curVal = this.get(key);
  53849. if (curVal !== undefined) {
  53850. return curVal;
  53851. }
  53852. this.add(key, val);
  53853. return val;
  53854. };
  53855. /**
  53856. * Check if there's a given key in the dictionary
  53857. * @param key the key to check for
  53858. * @return true if the key is present, false otherwise
  53859. */
  53860. StringDictionary.prototype.contains = function (key) {
  53861. return this._data[key] !== undefined;
  53862. };
  53863. /**
  53864. * Add a new key and its corresponding value
  53865. * @param key the key to add
  53866. * @param value the value corresponding to the key
  53867. * @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
  53868. */
  53869. StringDictionary.prototype.add = function (key, value) {
  53870. if (this._data[key] !== undefined) {
  53871. return false;
  53872. }
  53873. this._data[key] = value;
  53874. ++this._count;
  53875. return true;
  53876. };
  53877. StringDictionary.prototype.set = function (key, value) {
  53878. if (this._data[key] === undefined) {
  53879. return false;
  53880. }
  53881. this._data[key] = value;
  53882. return true;
  53883. };
  53884. /**
  53885. * Get the element of the given key and remove it from the dictionary
  53886. * @param key
  53887. */
  53888. StringDictionary.prototype.getAndRemove = function (key) {
  53889. var val = this.get(key);
  53890. if (val !== undefined) {
  53891. delete this._data[key];
  53892. --this._count;
  53893. return val;
  53894. }
  53895. return null;
  53896. };
  53897. /**
  53898. * Remove a key/value from the dictionary.
  53899. * @param key the key to remove
  53900. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  53901. */
  53902. StringDictionary.prototype.remove = function (key) {
  53903. if (this.contains(key)) {
  53904. delete this._data[key];
  53905. --this._count;
  53906. return true;
  53907. }
  53908. return false;
  53909. };
  53910. /**
  53911. * Clear the whole content of the dictionary
  53912. */
  53913. StringDictionary.prototype.clear = function () {
  53914. this._data = {};
  53915. this._count = 0;
  53916. };
  53917. Object.defineProperty(StringDictionary.prototype, "count", {
  53918. get: function () {
  53919. return this._count;
  53920. },
  53921. enumerable: true,
  53922. configurable: true
  53923. });
  53924. /**
  53925. * Execute a callback on each key/val of the dictionary.
  53926. * Note that you can remove any element in this dictionary in the callback implementation
  53927. * @param callback the callback to execute on a given key/value pair
  53928. */
  53929. StringDictionary.prototype.forEach = function (callback) {
  53930. for (var cur in this._data) {
  53931. var val = this._data[cur];
  53932. callback(cur, val);
  53933. }
  53934. };
  53935. /**
  53936. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  53937. * If the callback returns null or undefined the method will iterate to the next key/value pair
  53938. * Note that you can remove any element in this dictionary in the callback implementation
  53939. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  53940. */
  53941. StringDictionary.prototype.first = function (callback) {
  53942. for (var cur in this._data) {
  53943. var val = this._data[cur];
  53944. var res = callback(cur, val);
  53945. if (res) {
  53946. return res;
  53947. }
  53948. }
  53949. return null;
  53950. };
  53951. return StringDictionary;
  53952. }());
  53953. BABYLON.StringDictionary = StringDictionary;
  53954. })(BABYLON || (BABYLON = {}));
  53955. //# sourceMappingURL=babylon.stringDictionary.js.map
  53956. var BABYLON;
  53957. (function (BABYLON) {
  53958. var Tags = /** @class */ (function () {
  53959. function Tags() {
  53960. }
  53961. Tags.EnableFor = function (obj) {
  53962. obj._tags = obj._tags || {};
  53963. obj.hasTags = function () {
  53964. return Tags.HasTags(obj);
  53965. };
  53966. obj.addTags = function (tagsString) {
  53967. return Tags.AddTagsTo(obj, tagsString);
  53968. };
  53969. obj.removeTags = function (tagsString) {
  53970. return Tags.RemoveTagsFrom(obj, tagsString);
  53971. };
  53972. obj.matchesTagsQuery = function (tagsQuery) {
  53973. return Tags.MatchesQuery(obj, tagsQuery);
  53974. };
  53975. };
  53976. Tags.DisableFor = function (obj) {
  53977. delete obj._tags;
  53978. delete obj.hasTags;
  53979. delete obj.addTags;
  53980. delete obj.removeTags;
  53981. delete obj.matchesTagsQuery;
  53982. };
  53983. Tags.HasTags = function (obj) {
  53984. if (!obj._tags) {
  53985. return false;
  53986. }
  53987. return !BABYLON.Tools.IsEmpty(obj._tags);
  53988. };
  53989. Tags.GetTags = function (obj, asString) {
  53990. if (asString === void 0) { asString = true; }
  53991. if (!obj._tags) {
  53992. return null;
  53993. }
  53994. if (asString) {
  53995. var tagsArray = [];
  53996. for (var tag in obj._tags) {
  53997. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  53998. tagsArray.push(tag);
  53999. }
  54000. }
  54001. return tagsArray.join(" ");
  54002. }
  54003. else {
  54004. return obj._tags;
  54005. }
  54006. };
  54007. // the tags 'true' and 'false' are reserved and cannot be used as tags
  54008. // a tag cannot start with '||', '&&', and '!'
  54009. // it cannot contain whitespaces
  54010. Tags.AddTagsTo = function (obj, tagsString) {
  54011. if (!tagsString) {
  54012. return;
  54013. }
  54014. if (typeof tagsString !== "string") {
  54015. return;
  54016. }
  54017. var tags = tagsString.split(" ");
  54018. tags.forEach(function (tag, index, array) {
  54019. Tags._AddTagTo(obj, tag);
  54020. });
  54021. };
  54022. Tags._AddTagTo = function (obj, tag) {
  54023. tag = tag.trim();
  54024. if (tag === "" || tag === "true" || tag === "false") {
  54025. return;
  54026. }
  54027. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  54028. return;
  54029. }
  54030. Tags.EnableFor(obj);
  54031. obj._tags[tag] = true;
  54032. };
  54033. Tags.RemoveTagsFrom = function (obj, tagsString) {
  54034. if (!Tags.HasTags(obj)) {
  54035. return;
  54036. }
  54037. var tags = tagsString.split(" ");
  54038. for (var t in tags) {
  54039. Tags._RemoveTagFrom(obj, tags[t]);
  54040. }
  54041. };
  54042. Tags._RemoveTagFrom = function (obj, tag) {
  54043. delete obj._tags[tag];
  54044. };
  54045. Tags.MatchesQuery = function (obj, tagsQuery) {
  54046. if (tagsQuery === undefined) {
  54047. return true;
  54048. }
  54049. if (tagsQuery === "") {
  54050. return Tags.HasTags(obj);
  54051. }
  54052. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  54053. };
  54054. return Tags;
  54055. }());
  54056. BABYLON.Tags = Tags;
  54057. })(BABYLON || (BABYLON = {}));
  54058. //# sourceMappingURL=babylon.tags.js.map
  54059. var BABYLON;
  54060. (function (BABYLON) {
  54061. var Internals;
  54062. (function (Internals) {
  54063. var AndOrNotEvaluator = /** @class */ (function () {
  54064. function AndOrNotEvaluator() {
  54065. }
  54066. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  54067. if (!query.match(/\([^\(\)]*\)/g)) {
  54068. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  54069. }
  54070. else {
  54071. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  54072. // remove parenthesis
  54073. r = r.slice(1, r.length - 1);
  54074. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  54075. });
  54076. }
  54077. if (query === "true") {
  54078. return true;
  54079. }
  54080. if (query === "false") {
  54081. return false;
  54082. }
  54083. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  54084. };
  54085. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  54086. evaluateCallback = evaluateCallback || (function (r) {
  54087. return r === "true" ? true : false;
  54088. });
  54089. var result;
  54090. var or = parenthesisContent.split("||");
  54091. for (var i in or) {
  54092. if (or.hasOwnProperty(i)) {
  54093. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  54094. var and = ori.split("&&");
  54095. if (and.length > 1) {
  54096. for (var j = 0; j < and.length; ++j) {
  54097. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  54098. if (andj !== "true" && andj !== "false") {
  54099. if (andj[0] === "!") {
  54100. result = !evaluateCallback(andj.substring(1));
  54101. }
  54102. else {
  54103. result = evaluateCallback(andj);
  54104. }
  54105. }
  54106. else {
  54107. result = andj === "true" ? true : false;
  54108. }
  54109. if (!result) {
  54110. ori = "false";
  54111. break;
  54112. }
  54113. }
  54114. }
  54115. if (result || ori === "true") {
  54116. result = true;
  54117. break;
  54118. }
  54119. // result equals false (or undefined)
  54120. if (ori !== "true" && ori !== "false") {
  54121. if (ori[0] === "!") {
  54122. result = !evaluateCallback(ori.substring(1));
  54123. }
  54124. else {
  54125. result = evaluateCallback(ori);
  54126. }
  54127. }
  54128. else {
  54129. result = ori === "true" ? true : false;
  54130. }
  54131. }
  54132. }
  54133. // the whole parenthesis scope is replaced by 'true' or 'false'
  54134. return result ? "true" : "false";
  54135. };
  54136. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  54137. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  54138. // remove whitespaces
  54139. r = r.replace(/[\s]/g, function () { return ""; });
  54140. return r.length % 2 ? "!" : "";
  54141. });
  54142. booleanString = booleanString.trim();
  54143. if (booleanString === "!true") {
  54144. booleanString = "false";
  54145. }
  54146. else if (booleanString === "!false") {
  54147. booleanString = "true";
  54148. }
  54149. return booleanString;
  54150. };
  54151. return AndOrNotEvaluator;
  54152. }());
  54153. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  54154. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54155. })(BABYLON || (BABYLON = {}));
  54156. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  54157. var BABYLON;
  54158. (function (BABYLON) {
  54159. var Database = /** @class */ (function () {
  54160. function Database(urlToScene, callbackManifestChecked) {
  54161. // Handling various flavors of prefixed version of IndexedDB
  54162. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  54163. this.callbackManifestChecked = callbackManifestChecked;
  54164. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  54165. this.db = null;
  54166. this._enableSceneOffline = false;
  54167. this._enableTexturesOffline = false;
  54168. this.manifestVersionFound = 0;
  54169. this.mustUpdateRessources = false;
  54170. this.hasReachedQuota = false;
  54171. if (!Database.IDBStorageEnabled) {
  54172. this.callbackManifestChecked(true);
  54173. }
  54174. else {
  54175. this.checkManifestFile();
  54176. }
  54177. }
  54178. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  54179. get: function () {
  54180. return this._enableSceneOffline;
  54181. },
  54182. enumerable: true,
  54183. configurable: true
  54184. });
  54185. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  54186. get: function () {
  54187. return this._enableTexturesOffline;
  54188. },
  54189. enumerable: true,
  54190. configurable: true
  54191. });
  54192. Database.prototype.checkManifestFile = function () {
  54193. var _this = this;
  54194. var noManifestFile = function () {
  54195. _this._enableSceneOffline = false;
  54196. _this._enableTexturesOffline = false;
  54197. _this.callbackManifestChecked(false);
  54198. };
  54199. var timeStampUsed = false;
  54200. var manifestURL = this.currentSceneUrl + ".manifest";
  54201. var xhr = new XMLHttpRequest();
  54202. if (navigator.onLine) {
  54203. // Adding a timestamp to by-pass browsers' cache
  54204. timeStampUsed = true;
  54205. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  54206. }
  54207. xhr.open("GET", manifestURL, true);
  54208. xhr.addEventListener("load", function () {
  54209. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54210. try {
  54211. var manifestFile = JSON.parse(xhr.response);
  54212. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  54213. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  54214. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  54215. _this.manifestVersionFound = manifestFile.version;
  54216. }
  54217. if (_this.callbackManifestChecked) {
  54218. _this.callbackManifestChecked(true);
  54219. }
  54220. }
  54221. catch (ex) {
  54222. noManifestFile();
  54223. }
  54224. }
  54225. else {
  54226. noManifestFile();
  54227. }
  54228. }, false);
  54229. xhr.addEventListener("error", function (event) {
  54230. if (timeStampUsed) {
  54231. timeStampUsed = false;
  54232. // Let's retry without the timeStamp
  54233. // It could fail when coupled with HTML5 Offline API
  54234. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  54235. xhr.open("GET", retryManifestURL, true);
  54236. xhr.send();
  54237. }
  54238. else {
  54239. noManifestFile();
  54240. }
  54241. }, false);
  54242. try {
  54243. xhr.send();
  54244. }
  54245. catch (ex) {
  54246. BABYLON.Tools.Error("Error on XHR send request.");
  54247. this.callbackManifestChecked(false);
  54248. }
  54249. };
  54250. Database.prototype.openAsync = function (successCallback, errorCallback) {
  54251. var _this = this;
  54252. var handleError = function () {
  54253. _this.isSupported = false;
  54254. if (errorCallback)
  54255. errorCallback();
  54256. };
  54257. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  54258. // Your browser doesn't support IndexedDB
  54259. this.isSupported = false;
  54260. if (errorCallback)
  54261. errorCallback();
  54262. }
  54263. else {
  54264. // If the DB hasn't been opened or created yet
  54265. if (!this.db) {
  54266. this.hasReachedQuota = false;
  54267. this.isSupported = true;
  54268. var request = this.idbFactory.open("babylonjs", 1);
  54269. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  54270. request.onerror = function (event) {
  54271. handleError();
  54272. };
  54273. // executes when a version change transaction cannot complete due to other active transactions
  54274. request.onblocked = function (event) {
  54275. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  54276. handleError();
  54277. };
  54278. // DB has been opened successfully
  54279. request.onsuccess = function (event) {
  54280. _this.db = request.result;
  54281. successCallback();
  54282. };
  54283. // Initialization of the DB. Creating Scenes & Textures stores
  54284. request.onupgradeneeded = function (event) {
  54285. _this.db = (event.target).result;
  54286. if (_this.db) {
  54287. try {
  54288. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  54289. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  54290. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  54291. }
  54292. catch (ex) {
  54293. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  54294. handleError();
  54295. }
  54296. }
  54297. };
  54298. }
  54299. else {
  54300. if (successCallback)
  54301. successCallback();
  54302. }
  54303. }
  54304. };
  54305. Database.prototype.loadImageFromDB = function (url, image) {
  54306. var _this = this;
  54307. var completeURL = Database.ReturnFullUrlLocation(url);
  54308. var saveAndLoadImage = function () {
  54309. if (!_this.hasReachedQuota && _this.db !== null) {
  54310. // the texture is not yet in the DB, let's try to save it
  54311. _this._saveImageIntoDBAsync(completeURL, image);
  54312. }
  54313. else {
  54314. image.src = url;
  54315. }
  54316. };
  54317. if (!this.mustUpdateRessources) {
  54318. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  54319. }
  54320. else {
  54321. saveAndLoadImage();
  54322. }
  54323. };
  54324. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  54325. if (this.isSupported && this.db !== null) {
  54326. var texture;
  54327. var transaction = this.db.transaction(["textures"]);
  54328. transaction.onabort = function (event) {
  54329. image.src = url;
  54330. };
  54331. transaction.oncomplete = function (event) {
  54332. var blobTextureURL;
  54333. if (texture) {
  54334. var URL = window.URL || window.webkitURL;
  54335. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  54336. image.onerror = function () {
  54337. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  54338. image.src = url;
  54339. };
  54340. image.src = blobTextureURL;
  54341. }
  54342. else {
  54343. notInDBCallback();
  54344. }
  54345. };
  54346. var getRequest = transaction.objectStore("textures").get(url);
  54347. getRequest.onsuccess = function (event) {
  54348. texture = (event.target).result;
  54349. };
  54350. getRequest.onerror = function (event) {
  54351. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  54352. image.src = url;
  54353. };
  54354. }
  54355. else {
  54356. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54357. image.src = url;
  54358. }
  54359. };
  54360. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  54361. var _this = this;
  54362. if (this.isSupported) {
  54363. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  54364. var generateBlobUrl = function () {
  54365. var blobTextureURL;
  54366. if (blob) {
  54367. var URL = window.URL || window.webkitURL;
  54368. try {
  54369. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  54370. }
  54371. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  54372. catch (ex) {
  54373. blobTextureURL = URL.createObjectURL(blob);
  54374. }
  54375. }
  54376. if (blobTextureURL) {
  54377. image.src = blobTextureURL;
  54378. }
  54379. };
  54380. if (Database.IsUASupportingBlobStorage) {
  54381. var xhr = new XMLHttpRequest(), blob;
  54382. xhr.open("GET", url, true);
  54383. xhr.responseType = "blob";
  54384. xhr.addEventListener("load", function () {
  54385. if (xhr.status === 200 && _this.db) {
  54386. // Blob as response (XHR2)
  54387. blob = xhr.response;
  54388. var transaction = _this.db.transaction(["textures"], "readwrite");
  54389. // the transaction could abort because of a QuotaExceededError error
  54390. transaction.onabort = function (event) {
  54391. try {
  54392. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  54393. var srcElement = (event.srcElement || event.target);
  54394. var error = srcElement.error;
  54395. if (error && error.name === "QuotaExceededError") {
  54396. _this.hasReachedQuota = true;
  54397. }
  54398. }
  54399. catch (ex) { }
  54400. generateBlobUrl();
  54401. };
  54402. transaction.oncomplete = function (event) {
  54403. generateBlobUrl();
  54404. };
  54405. var newTexture = { textureUrl: url, data: blob };
  54406. try {
  54407. // Put the blob into the dabase
  54408. var addRequest = transaction.objectStore("textures").put(newTexture);
  54409. addRequest.onsuccess = function (event) {
  54410. };
  54411. addRequest.onerror = function (event) {
  54412. generateBlobUrl();
  54413. };
  54414. }
  54415. catch (ex) {
  54416. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  54417. if (ex.code === 25) {
  54418. Database.IsUASupportingBlobStorage = false;
  54419. }
  54420. image.src = url;
  54421. }
  54422. }
  54423. else {
  54424. image.src = url;
  54425. }
  54426. }, false);
  54427. xhr.addEventListener("error", function (event) {
  54428. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  54429. image.src = url;
  54430. }, false);
  54431. xhr.send();
  54432. }
  54433. else {
  54434. image.src = url;
  54435. }
  54436. }
  54437. else {
  54438. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54439. image.src = url;
  54440. }
  54441. };
  54442. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  54443. var _this = this;
  54444. var updateVersion = function () {
  54445. // the version is not yet in the DB or we need to update it
  54446. _this._saveVersionIntoDBAsync(url, versionLoaded);
  54447. };
  54448. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  54449. };
  54450. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  54451. var _this = this;
  54452. if (this.isSupported && this.db) {
  54453. var version;
  54454. try {
  54455. var transaction = this.db.transaction(["versions"]);
  54456. transaction.oncomplete = function (event) {
  54457. if (version) {
  54458. // If the version in the JSON file is > than the version in DB
  54459. if (_this.manifestVersionFound > version.data) {
  54460. _this.mustUpdateRessources = true;
  54461. updateInDBCallback();
  54462. }
  54463. else {
  54464. callback(version.data);
  54465. }
  54466. }
  54467. else {
  54468. _this.mustUpdateRessources = true;
  54469. updateInDBCallback();
  54470. }
  54471. };
  54472. transaction.onabort = function (event) {
  54473. callback(-1);
  54474. };
  54475. var getRequest = transaction.objectStore("versions").get(url);
  54476. getRequest.onsuccess = function (event) {
  54477. version = (event.target).result;
  54478. };
  54479. getRequest.onerror = function (event) {
  54480. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  54481. callback(-1);
  54482. };
  54483. }
  54484. catch (ex) {
  54485. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  54486. callback(-1);
  54487. }
  54488. }
  54489. else {
  54490. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54491. callback(-1);
  54492. }
  54493. };
  54494. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  54495. var _this = this;
  54496. if (this.isSupported && !this.hasReachedQuota && this.db) {
  54497. try {
  54498. // Open a transaction to the database
  54499. var transaction = this.db.transaction(["versions"], "readwrite");
  54500. // the transaction could abort because of a QuotaExceededError error
  54501. transaction.onabort = function (event) {
  54502. try {
  54503. var error = event.srcElement['error'];
  54504. if (error && error.name === "QuotaExceededError") {
  54505. _this.hasReachedQuota = true;
  54506. }
  54507. }
  54508. catch (ex) { }
  54509. callback(-1);
  54510. };
  54511. transaction.oncomplete = function (event) {
  54512. callback(_this.manifestVersionFound);
  54513. };
  54514. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  54515. // Put the scene into the database
  54516. var addRequest = transaction.objectStore("versions").put(newVersion);
  54517. addRequest.onsuccess = function (event) {
  54518. };
  54519. addRequest.onerror = function (event) {
  54520. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  54521. };
  54522. }
  54523. catch (ex) {
  54524. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  54525. callback(-1);
  54526. }
  54527. }
  54528. else {
  54529. callback(-1);
  54530. }
  54531. };
  54532. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  54533. var _this = this;
  54534. var completeUrl = Database.ReturnFullUrlLocation(url);
  54535. var saveAndLoadFile = function () {
  54536. // the scene is not yet in the DB, let's try to save it
  54537. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  54538. };
  54539. this._checkVersionFromDB(completeUrl, function (version) {
  54540. if (version !== -1) {
  54541. if (!_this.mustUpdateRessources) {
  54542. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  54543. }
  54544. else {
  54545. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  54546. }
  54547. }
  54548. else {
  54549. if (errorCallback) {
  54550. errorCallback();
  54551. }
  54552. }
  54553. });
  54554. };
  54555. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  54556. if (this.isSupported && this.db) {
  54557. var targetStore;
  54558. if (url.indexOf(".babylon") !== -1) {
  54559. targetStore = "scenes";
  54560. }
  54561. else {
  54562. targetStore = "textures";
  54563. }
  54564. var file;
  54565. var transaction = this.db.transaction([targetStore]);
  54566. transaction.oncomplete = function (event) {
  54567. if (file) {
  54568. callback(file.data);
  54569. }
  54570. else {
  54571. notInDBCallback();
  54572. }
  54573. };
  54574. transaction.onabort = function (event) {
  54575. notInDBCallback();
  54576. };
  54577. var getRequest = transaction.objectStore(targetStore).get(url);
  54578. getRequest.onsuccess = function (event) {
  54579. file = (event.target).result;
  54580. };
  54581. getRequest.onerror = function (event) {
  54582. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  54583. notInDBCallback();
  54584. };
  54585. }
  54586. else {
  54587. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54588. callback();
  54589. }
  54590. };
  54591. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  54592. var _this = this;
  54593. if (this.isSupported) {
  54594. var targetStore;
  54595. if (url.indexOf(".babylon") !== -1) {
  54596. targetStore = "scenes";
  54597. }
  54598. else {
  54599. targetStore = "textures";
  54600. }
  54601. // Create XHR
  54602. var xhr = new XMLHttpRequest();
  54603. var fileData;
  54604. xhr.open("GET", url, true);
  54605. if (useArrayBuffer) {
  54606. xhr.responseType = "arraybuffer";
  54607. }
  54608. if (progressCallback) {
  54609. xhr.onprogress = progressCallback;
  54610. }
  54611. xhr.addEventListener("load", function () {
  54612. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  54613. // Blob as response (XHR2)
  54614. //fileData = xhr.responseText;
  54615. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  54616. if (!_this.hasReachedQuota && _this.db) {
  54617. // Open a transaction to the database
  54618. var transaction = _this.db.transaction([targetStore], "readwrite");
  54619. // the transaction could abort because of a QuotaExceededError error
  54620. transaction.onabort = function (event) {
  54621. try {
  54622. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  54623. var error = event.srcElement['error'];
  54624. if (error && error.name === "QuotaExceededError") {
  54625. _this.hasReachedQuota = true;
  54626. }
  54627. }
  54628. catch (ex) { }
  54629. callback(fileData);
  54630. };
  54631. transaction.oncomplete = function (event) {
  54632. callback(fileData);
  54633. };
  54634. var newFile;
  54635. if (targetStore === "scenes") {
  54636. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  54637. }
  54638. else {
  54639. newFile = { textureUrl: url, data: fileData };
  54640. }
  54641. try {
  54642. // Put the scene into the database
  54643. var addRequest = transaction.objectStore(targetStore).put(newFile);
  54644. addRequest.onsuccess = function (event) {
  54645. };
  54646. addRequest.onerror = function (event) {
  54647. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  54648. };
  54649. }
  54650. catch (ex) {
  54651. callback(fileData);
  54652. }
  54653. }
  54654. else {
  54655. callback(fileData);
  54656. }
  54657. }
  54658. else {
  54659. callback();
  54660. }
  54661. }, false);
  54662. xhr.addEventListener("error", function (event) {
  54663. BABYLON.Tools.Error("error on XHR request.");
  54664. callback();
  54665. }, false);
  54666. xhr.send();
  54667. }
  54668. else {
  54669. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54670. callback();
  54671. }
  54672. };
  54673. Database.IsUASupportingBlobStorage = true;
  54674. Database.IDBStorageEnabled = true;
  54675. Database.parseURL = function (url) {
  54676. var a = document.createElement('a');
  54677. a.href = url;
  54678. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  54679. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  54680. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  54681. return absLocation;
  54682. };
  54683. Database.ReturnFullUrlLocation = function (url) {
  54684. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  54685. return (Database.parseURL(window.location.href) + url);
  54686. }
  54687. else {
  54688. return url;
  54689. }
  54690. };
  54691. return Database;
  54692. }());
  54693. BABYLON.Database = Database;
  54694. })(BABYLON || (BABYLON = {}));
  54695. //# sourceMappingURL=babylon.database.js.map
  54696. var BABYLON;
  54697. (function (BABYLON) {
  54698. var FresnelParameters = /** @class */ (function () {
  54699. function FresnelParameters() {
  54700. this._isEnabled = true;
  54701. this.leftColor = BABYLON.Color3.White();
  54702. this.rightColor = BABYLON.Color3.Black();
  54703. this.bias = 0;
  54704. this.power = 1;
  54705. }
  54706. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  54707. get: function () {
  54708. return this._isEnabled;
  54709. },
  54710. set: function (value) {
  54711. if (this._isEnabled === value) {
  54712. return;
  54713. }
  54714. this._isEnabled = value;
  54715. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  54716. },
  54717. enumerable: true,
  54718. configurable: true
  54719. });
  54720. FresnelParameters.prototype.clone = function () {
  54721. var newFresnelParameters = new FresnelParameters();
  54722. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  54723. return newFresnelParameters;
  54724. };
  54725. FresnelParameters.prototype.serialize = function () {
  54726. var serializationObject = {};
  54727. serializationObject.isEnabled = this.isEnabled;
  54728. serializationObject.leftColor = this.leftColor;
  54729. serializationObject.rightColor = this.rightColor;
  54730. serializationObject.bias = this.bias;
  54731. serializationObject.power = this.power;
  54732. return serializationObject;
  54733. };
  54734. FresnelParameters.Parse = function (parsedFresnelParameters) {
  54735. var fresnelParameters = new FresnelParameters();
  54736. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  54737. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  54738. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  54739. fresnelParameters.bias = parsedFresnelParameters.bias;
  54740. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  54741. return fresnelParameters;
  54742. };
  54743. return FresnelParameters;
  54744. }());
  54745. BABYLON.FresnelParameters = FresnelParameters;
  54746. })(BABYLON || (BABYLON = {}));
  54747. //# sourceMappingURL=babylon.fresnelParameters.js.map
  54748. var BABYLON;
  54749. (function (BABYLON) {
  54750. var MultiMaterial = /** @class */ (function (_super) {
  54751. __extends(MultiMaterial, _super);
  54752. function MultiMaterial(name, scene) {
  54753. var _this = _super.call(this, name, scene, true) || this;
  54754. scene.multiMaterials.push(_this);
  54755. _this.subMaterials = new Array();
  54756. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  54757. return _this;
  54758. }
  54759. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  54760. get: function () {
  54761. return this._subMaterials;
  54762. },
  54763. set: function (value) {
  54764. this._subMaterials = value;
  54765. this._hookArray(value);
  54766. },
  54767. enumerable: true,
  54768. configurable: true
  54769. });
  54770. MultiMaterial.prototype._hookArray = function (array) {
  54771. var _this = this;
  54772. var oldPush = array.push;
  54773. array.push = function () {
  54774. var items = [];
  54775. for (var _i = 0; _i < arguments.length; _i++) {
  54776. items[_i] = arguments[_i];
  54777. }
  54778. var result = oldPush.apply(array, items);
  54779. _this._markAllSubMeshesAsTexturesDirty();
  54780. return result;
  54781. };
  54782. var oldSplice = array.splice;
  54783. array.splice = function (index, deleteCount) {
  54784. var deleted = oldSplice.apply(array, [index, deleteCount]);
  54785. _this._markAllSubMeshesAsTexturesDirty();
  54786. return deleted;
  54787. };
  54788. };
  54789. // Properties
  54790. MultiMaterial.prototype.getSubMaterial = function (index) {
  54791. if (index < 0 || index >= this.subMaterials.length) {
  54792. return this.getScene().defaultMaterial;
  54793. }
  54794. return this.subMaterials[index];
  54795. };
  54796. MultiMaterial.prototype.getActiveTextures = function () {
  54797. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  54798. if (subMaterial) {
  54799. return subMaterial.getActiveTextures();
  54800. }
  54801. else {
  54802. return [];
  54803. }
  54804. }));
  54805. var _a;
  54806. };
  54807. // Methods
  54808. MultiMaterial.prototype.getClassName = function () {
  54809. return "MultiMaterial";
  54810. };
  54811. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  54812. for (var index = 0; index < this.subMaterials.length; index++) {
  54813. var subMaterial = this.subMaterials[index];
  54814. if (subMaterial) {
  54815. if (subMaterial.storeEffectOnSubMeshes) {
  54816. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  54817. return false;
  54818. }
  54819. continue;
  54820. }
  54821. if (!subMaterial.isReady(mesh)) {
  54822. return false;
  54823. }
  54824. }
  54825. }
  54826. return true;
  54827. };
  54828. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  54829. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  54830. for (var index = 0; index < this.subMaterials.length; index++) {
  54831. var subMaterial = null;
  54832. var current = this.subMaterials[index];
  54833. if (cloneChildren && current) {
  54834. subMaterial = current.clone(name + "-" + current.name);
  54835. }
  54836. else {
  54837. subMaterial = this.subMaterials[index];
  54838. }
  54839. newMultiMaterial.subMaterials.push(subMaterial);
  54840. }
  54841. return newMultiMaterial;
  54842. };
  54843. MultiMaterial.prototype.serialize = function () {
  54844. var serializationObject = {};
  54845. serializationObject.name = this.name;
  54846. serializationObject.id = this.id;
  54847. serializationObject.tags = BABYLON.Tags.GetTags(this);
  54848. serializationObject.materials = [];
  54849. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  54850. var subMat = this.subMaterials[matIndex];
  54851. if (subMat) {
  54852. serializationObject.materials.push(subMat.id);
  54853. }
  54854. else {
  54855. serializationObject.materials.push(null);
  54856. }
  54857. }
  54858. return serializationObject;
  54859. };
  54860. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54861. var scene = this.getScene();
  54862. if (!scene) {
  54863. return;
  54864. }
  54865. var index = scene.multiMaterials.indexOf(this);
  54866. if (index >= 0) {
  54867. scene.multiMaterials.splice(index, 1);
  54868. }
  54869. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54870. };
  54871. return MultiMaterial;
  54872. }(BABYLON.Material));
  54873. BABYLON.MultiMaterial = MultiMaterial;
  54874. })(BABYLON || (BABYLON = {}));
  54875. //# sourceMappingURL=babylon.multiMaterial.js.map
  54876. var BABYLON;
  54877. (function (BABYLON) {
  54878. var FreeCameraTouchInput = /** @class */ (function () {
  54879. function FreeCameraTouchInput() {
  54880. this._offsetX = null;
  54881. this._offsetY = null;
  54882. this._pointerPressed = new Array();
  54883. this.touchAngularSensibility = 200000.0;
  54884. this.touchMoveSensibility = 250.0;
  54885. }
  54886. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  54887. var _this = this;
  54888. var previousPosition = null;
  54889. if (this._pointerInput === undefined) {
  54890. this._onLostFocus = function (evt) {
  54891. _this._offsetX = null;
  54892. _this._offsetY = null;
  54893. };
  54894. this._pointerInput = function (p, s) {
  54895. var evt = p.event;
  54896. if (evt.pointerType === "mouse") {
  54897. return;
  54898. }
  54899. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  54900. if (!noPreventDefault) {
  54901. evt.preventDefault();
  54902. }
  54903. _this._pointerPressed.push(evt.pointerId);
  54904. if (_this._pointerPressed.length !== 1) {
  54905. return;
  54906. }
  54907. previousPosition = {
  54908. x: evt.clientX,
  54909. y: evt.clientY
  54910. };
  54911. }
  54912. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  54913. if (!noPreventDefault) {
  54914. evt.preventDefault();
  54915. }
  54916. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54917. if (index === -1) {
  54918. return;
  54919. }
  54920. _this._pointerPressed.splice(index, 1);
  54921. if (index != 0) {
  54922. return;
  54923. }
  54924. previousPosition = null;
  54925. _this._offsetX = null;
  54926. _this._offsetY = null;
  54927. }
  54928. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  54929. if (!noPreventDefault) {
  54930. evt.preventDefault();
  54931. }
  54932. if (!previousPosition) {
  54933. return;
  54934. }
  54935. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54936. if (index != 0) {
  54937. return;
  54938. }
  54939. _this._offsetX = evt.clientX - previousPosition.x;
  54940. _this._offsetY = -(evt.clientY - previousPosition.y);
  54941. }
  54942. };
  54943. }
  54944. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  54945. if (this._onLostFocus) {
  54946. element.addEventListener("blur", this._onLostFocus);
  54947. }
  54948. };
  54949. FreeCameraTouchInput.prototype.detachControl = function (element) {
  54950. if (this._pointerInput && element) {
  54951. if (this._observer) {
  54952. this.camera.getScene().onPointerObservable.remove(this._observer);
  54953. this._observer = null;
  54954. }
  54955. if (this._onLostFocus) {
  54956. element.removeEventListener("blur", this._onLostFocus);
  54957. this._onLostFocus = null;
  54958. }
  54959. this._pointerPressed = [];
  54960. this._offsetX = null;
  54961. this._offsetY = null;
  54962. }
  54963. };
  54964. FreeCameraTouchInput.prototype.checkInputs = function () {
  54965. if (this._offsetX && this._offsetY) {
  54966. var camera = this.camera;
  54967. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  54968. if (this._pointerPressed.length > 1) {
  54969. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  54970. }
  54971. else {
  54972. var speed = camera._computeLocalCameraSpeed();
  54973. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  54974. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  54975. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  54976. }
  54977. }
  54978. };
  54979. FreeCameraTouchInput.prototype.getClassName = function () {
  54980. return "FreeCameraTouchInput";
  54981. };
  54982. FreeCameraTouchInput.prototype.getSimpleName = function () {
  54983. return "touch";
  54984. };
  54985. __decorate([
  54986. BABYLON.serialize()
  54987. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  54988. __decorate([
  54989. BABYLON.serialize()
  54990. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  54991. return FreeCameraTouchInput;
  54992. }());
  54993. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  54994. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  54995. })(BABYLON || (BABYLON = {}));
  54996. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  54997. var BABYLON;
  54998. (function (BABYLON) {
  54999. // We're mainly based on the logic defined into the FreeCamera code
  55000. var TouchCamera = /** @class */ (function (_super) {
  55001. __extends(TouchCamera, _super);
  55002. //-- end properties for backward compatibility for inputs
  55003. function TouchCamera(name, position, scene) {
  55004. var _this = _super.call(this, name, position, scene) || this;
  55005. _this.inputs.addTouch();
  55006. _this._setupInputs();
  55007. return _this;
  55008. }
  55009. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  55010. //-- Begin properties for backward compatibility for inputs
  55011. get: function () {
  55012. var touch = this.inputs.attached["touch"];
  55013. if (touch)
  55014. return touch.touchAngularSensibility;
  55015. return 0;
  55016. },
  55017. set: function (value) {
  55018. var touch = this.inputs.attached["touch"];
  55019. if (touch)
  55020. touch.touchAngularSensibility = value;
  55021. },
  55022. enumerable: true,
  55023. configurable: true
  55024. });
  55025. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  55026. get: function () {
  55027. var touch = this.inputs.attached["touch"];
  55028. if (touch)
  55029. return touch.touchMoveSensibility;
  55030. return 0;
  55031. },
  55032. set: function (value) {
  55033. var touch = this.inputs.attached["touch"];
  55034. if (touch)
  55035. touch.touchMoveSensibility = value;
  55036. },
  55037. enumerable: true,
  55038. configurable: true
  55039. });
  55040. TouchCamera.prototype.getClassName = function () {
  55041. return "TouchCamera";
  55042. };
  55043. TouchCamera.prototype._setupInputs = function () {
  55044. var mouse = this.inputs.attached["mouse"];
  55045. if (mouse) {
  55046. mouse.touchEnabled = false;
  55047. }
  55048. };
  55049. return TouchCamera;
  55050. }(BABYLON.FreeCamera));
  55051. BABYLON.TouchCamera = TouchCamera;
  55052. })(BABYLON || (BABYLON = {}));
  55053. //# sourceMappingURL=babylon.touchCamera.js.map
  55054. var BABYLON;
  55055. (function (BABYLON) {
  55056. var ProceduralTexture = /** @class */ (function (_super) {
  55057. __extends(ProceduralTexture, _super);
  55058. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  55059. if (fallbackTexture === void 0) { fallbackTexture = null; }
  55060. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55061. if (isCube === void 0) { isCube = false; }
  55062. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  55063. _this.isCube = isCube;
  55064. _this.isEnabled = true;
  55065. _this._currentRefreshId = -1;
  55066. _this._refreshRate = 1;
  55067. _this._vertexBuffers = {};
  55068. _this._uniforms = new Array();
  55069. _this._samplers = new Array();
  55070. _this._textures = {};
  55071. _this._floats = {};
  55072. _this._floatsArrays = {};
  55073. _this._colors3 = {};
  55074. _this._colors4 = {};
  55075. _this._vectors2 = {};
  55076. _this._vectors3 = {};
  55077. _this._matrices = {};
  55078. _this._fallbackTextureUsed = false;
  55079. scene._proceduralTextures.push(_this);
  55080. _this._engine = scene.getEngine();
  55081. _this.name = name;
  55082. _this.isRenderTarget = true;
  55083. _this._size = size;
  55084. _this._generateMipMaps = generateMipMaps;
  55085. _this.setFragment(fragment);
  55086. _this._fallbackTexture = fallbackTexture;
  55087. if (isCube) {
  55088. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  55089. _this.setFloat("face", 0);
  55090. }
  55091. else {
  55092. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  55093. }
  55094. // VBO
  55095. var vertices = [];
  55096. vertices.push(1, 1);
  55097. vertices.push(-1, 1);
  55098. vertices.push(-1, -1);
  55099. vertices.push(1, -1);
  55100. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  55101. _this._createIndexBuffer();
  55102. return _this;
  55103. }
  55104. ProceduralTexture.prototype._createIndexBuffer = function () {
  55105. var engine = this._engine;
  55106. // Indices
  55107. var indices = [];
  55108. indices.push(0);
  55109. indices.push(1);
  55110. indices.push(2);
  55111. indices.push(0);
  55112. indices.push(2);
  55113. indices.push(3);
  55114. this._indexBuffer = engine.createIndexBuffer(indices);
  55115. };
  55116. ProceduralTexture.prototype._rebuild = function () {
  55117. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55118. if (vb) {
  55119. vb._rebuild();
  55120. }
  55121. this._createIndexBuffer();
  55122. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  55123. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  55124. }
  55125. };
  55126. ProceduralTexture.prototype.reset = function () {
  55127. if (this._effect === undefined) {
  55128. return;
  55129. }
  55130. var engine = this._engine;
  55131. engine._releaseEffect(this._effect);
  55132. };
  55133. ProceduralTexture.prototype.isReady = function () {
  55134. var _this = this;
  55135. var engine = this._engine;
  55136. var shaders;
  55137. if (!this._fragment) {
  55138. return false;
  55139. }
  55140. if (this._fallbackTextureUsed) {
  55141. return true;
  55142. }
  55143. if (this._fragment.fragmentElement !== undefined) {
  55144. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  55145. }
  55146. else {
  55147. shaders = { vertex: "procedural", fragment: this._fragment };
  55148. }
  55149. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  55150. _this.releaseInternalTexture();
  55151. if (_this._fallbackTexture) {
  55152. _this._texture = _this._fallbackTexture._texture;
  55153. if (_this._texture) {
  55154. _this._texture.incrementReferences();
  55155. }
  55156. }
  55157. _this._fallbackTextureUsed = true;
  55158. });
  55159. return this._effect.isReady();
  55160. };
  55161. ProceduralTexture.prototype.resetRefreshCounter = function () {
  55162. this._currentRefreshId = -1;
  55163. };
  55164. ProceduralTexture.prototype.setFragment = function (fragment) {
  55165. this._fragment = fragment;
  55166. };
  55167. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  55168. get: function () {
  55169. return this._refreshRate;
  55170. },
  55171. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  55172. set: function (value) {
  55173. this._refreshRate = value;
  55174. this.resetRefreshCounter();
  55175. },
  55176. enumerable: true,
  55177. configurable: true
  55178. });
  55179. ProceduralTexture.prototype._shouldRender = function () {
  55180. if (!this.isEnabled || !this.isReady() || !this._texture) {
  55181. return false;
  55182. }
  55183. if (this._fallbackTextureUsed) {
  55184. return false;
  55185. }
  55186. if (this._currentRefreshId === -1) {
  55187. this._currentRefreshId = 1;
  55188. return true;
  55189. }
  55190. if (this.refreshRate === this._currentRefreshId) {
  55191. this._currentRefreshId = 1;
  55192. return true;
  55193. }
  55194. this._currentRefreshId++;
  55195. return false;
  55196. };
  55197. ProceduralTexture.prototype.getRenderSize = function () {
  55198. return this._size;
  55199. };
  55200. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  55201. if (this._fallbackTextureUsed) {
  55202. return;
  55203. }
  55204. this.releaseInternalTexture();
  55205. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  55206. };
  55207. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  55208. if (this._uniforms.indexOf(uniformName) === -1) {
  55209. this._uniforms.push(uniformName);
  55210. }
  55211. };
  55212. ProceduralTexture.prototype.setTexture = function (name, texture) {
  55213. if (this._samplers.indexOf(name) === -1) {
  55214. this._samplers.push(name);
  55215. }
  55216. this._textures[name] = texture;
  55217. return this;
  55218. };
  55219. ProceduralTexture.prototype.setFloat = function (name, value) {
  55220. this._checkUniform(name);
  55221. this._floats[name] = value;
  55222. return this;
  55223. };
  55224. ProceduralTexture.prototype.setFloats = function (name, value) {
  55225. this._checkUniform(name);
  55226. this._floatsArrays[name] = value;
  55227. return this;
  55228. };
  55229. ProceduralTexture.prototype.setColor3 = function (name, value) {
  55230. this._checkUniform(name);
  55231. this._colors3[name] = value;
  55232. return this;
  55233. };
  55234. ProceduralTexture.prototype.setColor4 = function (name, value) {
  55235. this._checkUniform(name);
  55236. this._colors4[name] = value;
  55237. return this;
  55238. };
  55239. ProceduralTexture.prototype.setVector2 = function (name, value) {
  55240. this._checkUniform(name);
  55241. this._vectors2[name] = value;
  55242. return this;
  55243. };
  55244. ProceduralTexture.prototype.setVector3 = function (name, value) {
  55245. this._checkUniform(name);
  55246. this._vectors3[name] = value;
  55247. return this;
  55248. };
  55249. ProceduralTexture.prototype.setMatrix = function (name, value) {
  55250. this._checkUniform(name);
  55251. this._matrices[name] = value;
  55252. return this;
  55253. };
  55254. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  55255. var scene = this.getScene();
  55256. if (!scene) {
  55257. return;
  55258. }
  55259. var engine = this._engine;
  55260. // Render
  55261. engine.enableEffect(this._effect);
  55262. engine.setState(false);
  55263. // Texture
  55264. for (var name in this._textures) {
  55265. this._effect.setTexture(name, this._textures[name]);
  55266. }
  55267. // Float
  55268. for (name in this._floats) {
  55269. this._effect.setFloat(name, this._floats[name]);
  55270. }
  55271. // Floats
  55272. for (name in this._floatsArrays) {
  55273. this._effect.setArray(name, this._floatsArrays[name]);
  55274. }
  55275. // Color3
  55276. for (name in this._colors3) {
  55277. this._effect.setColor3(name, this._colors3[name]);
  55278. }
  55279. // Color4
  55280. for (name in this._colors4) {
  55281. var color = this._colors4[name];
  55282. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55283. }
  55284. // Vector2
  55285. for (name in this._vectors2) {
  55286. this._effect.setVector2(name, this._vectors2[name]);
  55287. }
  55288. // Vector3
  55289. for (name in this._vectors3) {
  55290. this._effect.setVector3(name, this._vectors3[name]);
  55291. }
  55292. // Matrix
  55293. for (name in this._matrices) {
  55294. this._effect.setMatrix(name, this._matrices[name]);
  55295. }
  55296. if (!this._texture) {
  55297. return;
  55298. }
  55299. if (this.isCube) {
  55300. for (var face = 0; face < 6; face++) {
  55301. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  55302. // VBOs
  55303. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  55304. this._effect.setFloat("face", face);
  55305. // Clear
  55306. engine.clear(scene.clearColor, true, true, true);
  55307. // Draw order
  55308. engine.draw(true, 0, 6);
  55309. // Mipmaps
  55310. if (face === 5) {
  55311. engine.generateMipMapsForCubemap(this._texture);
  55312. }
  55313. }
  55314. }
  55315. else {
  55316. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  55317. // VBOs
  55318. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  55319. // Clear
  55320. engine.clear(scene.clearColor, true, true, true);
  55321. // Draw order
  55322. engine.draw(true, 0, 6);
  55323. }
  55324. // Unbind
  55325. engine.unBindFramebuffer(this._texture, this.isCube);
  55326. if (this.onGenerated) {
  55327. this.onGenerated();
  55328. }
  55329. };
  55330. ProceduralTexture.prototype.clone = function () {
  55331. var textureSize = this.getSize();
  55332. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  55333. // Base texture
  55334. newTexture.hasAlpha = this.hasAlpha;
  55335. newTexture.level = this.level;
  55336. // RenderTarget Texture
  55337. newTexture.coordinatesMode = this.coordinatesMode;
  55338. return newTexture;
  55339. };
  55340. ProceduralTexture.prototype.dispose = function () {
  55341. var scene = this.getScene();
  55342. if (!scene) {
  55343. return;
  55344. }
  55345. var index = scene._proceduralTextures.indexOf(this);
  55346. if (index >= 0) {
  55347. scene._proceduralTextures.splice(index, 1);
  55348. }
  55349. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55350. if (vertexBuffer) {
  55351. vertexBuffer.dispose();
  55352. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  55353. }
  55354. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  55355. this._indexBuffer = null;
  55356. }
  55357. _super.prototype.dispose.call(this);
  55358. };
  55359. return ProceduralTexture;
  55360. }(BABYLON.Texture));
  55361. BABYLON.ProceduralTexture = ProceduralTexture;
  55362. })(BABYLON || (BABYLON = {}));
  55363. //# sourceMappingURL=babylon.proceduralTexture.js.map
  55364. var BABYLON;
  55365. (function (BABYLON) {
  55366. var CustomProceduralTexture = /** @class */ (function (_super) {
  55367. __extends(CustomProceduralTexture, _super);
  55368. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  55369. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  55370. _this._animate = true;
  55371. _this._time = 0;
  55372. _this._texturePath = texturePath;
  55373. //Try to load json
  55374. _this.loadJson(texturePath);
  55375. _this.refreshRate = 1;
  55376. return _this;
  55377. }
  55378. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  55379. var _this = this;
  55380. var noConfigFile = function () {
  55381. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  55382. try {
  55383. _this.setFragment(_this._texturePath);
  55384. }
  55385. catch (ex) {
  55386. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  55387. }
  55388. };
  55389. var configFileUrl = jsonUrl + "/config.json";
  55390. var xhr = new XMLHttpRequest();
  55391. xhr.open("GET", configFileUrl, true);
  55392. xhr.addEventListener("load", function () {
  55393. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  55394. try {
  55395. _this._config = JSON.parse(xhr.response);
  55396. _this.updateShaderUniforms();
  55397. _this.updateTextures();
  55398. _this.setFragment(_this._texturePath + "/custom");
  55399. _this._animate = _this._config.animate;
  55400. _this.refreshRate = _this._config.refreshrate;
  55401. }
  55402. catch (ex) {
  55403. noConfigFile();
  55404. }
  55405. }
  55406. else {
  55407. noConfigFile();
  55408. }
  55409. }, false);
  55410. xhr.addEventListener("error", function () {
  55411. noConfigFile();
  55412. }, false);
  55413. try {
  55414. xhr.send();
  55415. }
  55416. catch (ex) {
  55417. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  55418. }
  55419. };
  55420. CustomProceduralTexture.prototype.isReady = function () {
  55421. if (!_super.prototype.isReady.call(this)) {
  55422. return false;
  55423. }
  55424. for (var name in this._textures) {
  55425. var texture = this._textures[name];
  55426. if (!texture.isReady()) {
  55427. return false;
  55428. }
  55429. }
  55430. return true;
  55431. };
  55432. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  55433. var scene = this.getScene();
  55434. if (this._animate && scene) {
  55435. this._time += scene.getAnimationRatio() * 0.03;
  55436. this.updateShaderUniforms();
  55437. }
  55438. _super.prototype.render.call(this, useCameraPostProcess);
  55439. };
  55440. CustomProceduralTexture.prototype.updateTextures = function () {
  55441. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  55442. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  55443. }
  55444. };
  55445. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  55446. if (this._config) {
  55447. for (var j = 0; j < this._config.uniforms.length; j++) {
  55448. var uniform = this._config.uniforms[j];
  55449. switch (uniform.type) {
  55450. case "float":
  55451. this.setFloat(uniform.name, uniform.value);
  55452. break;
  55453. case "color3":
  55454. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  55455. break;
  55456. case "color4":
  55457. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  55458. break;
  55459. case "vector2":
  55460. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  55461. break;
  55462. case "vector3":
  55463. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  55464. break;
  55465. }
  55466. }
  55467. }
  55468. this.setFloat("time", this._time);
  55469. };
  55470. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  55471. get: function () {
  55472. return this._animate;
  55473. },
  55474. set: function (value) {
  55475. this._animate = value;
  55476. },
  55477. enumerable: true,
  55478. configurable: true
  55479. });
  55480. return CustomProceduralTexture;
  55481. }(BABYLON.ProceduralTexture));
  55482. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  55483. })(BABYLON || (BABYLON = {}));
  55484. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  55485. var BABYLON;
  55486. (function (BABYLON) {
  55487. var FreeCameraGamepadInput = /** @class */ (function () {
  55488. function FreeCameraGamepadInput() {
  55489. this.gamepadAngularSensibility = 200;
  55490. this.gamepadMoveSensibility = 40;
  55491. // private members
  55492. this._cameraTransform = BABYLON.Matrix.Identity();
  55493. this._deltaTransform = BABYLON.Vector3.Zero();
  55494. this._vector3 = BABYLON.Vector3.Zero();
  55495. this._vector2 = BABYLON.Vector2.Zero();
  55496. }
  55497. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  55498. var _this = this;
  55499. var manager = this.camera.getScene().gamepadManager;
  55500. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  55501. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  55502. // prioritize XBOX gamepads.
  55503. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  55504. _this.gamepad = gamepad;
  55505. }
  55506. }
  55507. });
  55508. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  55509. if (_this.gamepad === gamepad) {
  55510. _this.gamepad = null;
  55511. }
  55512. });
  55513. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  55514. };
  55515. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  55516. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  55517. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  55518. this.gamepad = null;
  55519. };
  55520. FreeCameraGamepadInput.prototype.checkInputs = function () {
  55521. if (this.gamepad && this.gamepad.leftStick) {
  55522. var camera = this.camera;
  55523. var LSValues = this.gamepad.leftStick;
  55524. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  55525. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  55526. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  55527. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  55528. var RSValues = this.gamepad.rightStick;
  55529. if (RSValues) {
  55530. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  55531. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  55532. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  55533. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  55534. }
  55535. else {
  55536. RSValues = { x: 0, y: 0 };
  55537. }
  55538. if (!camera.rotationQuaternion) {
  55539. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  55540. }
  55541. else {
  55542. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  55543. }
  55544. var speed = camera._computeLocalCameraSpeed() * 50.0;
  55545. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  55546. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  55547. camera.cameraDirection.addInPlace(this._deltaTransform);
  55548. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  55549. camera.cameraRotation.addInPlace(this._vector2);
  55550. }
  55551. };
  55552. FreeCameraGamepadInput.prototype.getClassName = function () {
  55553. return "FreeCameraGamepadInput";
  55554. };
  55555. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  55556. return "gamepad";
  55557. };
  55558. __decorate([
  55559. BABYLON.serialize()
  55560. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  55561. __decorate([
  55562. BABYLON.serialize()
  55563. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  55564. return FreeCameraGamepadInput;
  55565. }());
  55566. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  55567. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  55568. })(BABYLON || (BABYLON = {}));
  55569. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  55570. var BABYLON;
  55571. (function (BABYLON) {
  55572. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  55573. function ArcRotateCameraGamepadInput() {
  55574. this.gamepadRotationSensibility = 80;
  55575. this.gamepadMoveSensibility = 40;
  55576. }
  55577. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  55578. var _this = this;
  55579. var manager = this.camera.getScene().gamepadManager;
  55580. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  55581. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  55582. // prioritize XBOX gamepads.
  55583. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  55584. _this.gamepad = gamepad;
  55585. }
  55586. }
  55587. });
  55588. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  55589. if (_this.gamepad === gamepad) {
  55590. _this.gamepad = null;
  55591. }
  55592. });
  55593. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  55594. };
  55595. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  55596. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  55597. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  55598. this.gamepad = null;
  55599. };
  55600. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  55601. if (this.gamepad) {
  55602. var camera = this.camera;
  55603. var RSValues = this.gamepad.rightStick;
  55604. if (RSValues) {
  55605. if (RSValues.x != 0) {
  55606. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  55607. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  55608. camera.inertialAlphaOffset += normalizedRX;
  55609. }
  55610. }
  55611. if (RSValues.y != 0) {
  55612. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  55613. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  55614. camera.inertialBetaOffset += normalizedRY;
  55615. }
  55616. }
  55617. }
  55618. var LSValues = this.gamepad.leftStick;
  55619. if (LSValues && LSValues.y != 0) {
  55620. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  55621. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  55622. this.camera.inertialRadiusOffset -= normalizedLY;
  55623. }
  55624. }
  55625. }
  55626. };
  55627. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  55628. return "ArcRotateCameraGamepadInput";
  55629. };
  55630. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  55631. return "gamepad";
  55632. };
  55633. __decorate([
  55634. BABYLON.serialize()
  55635. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  55636. __decorate([
  55637. BABYLON.serialize()
  55638. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  55639. return ArcRotateCameraGamepadInput;
  55640. }());
  55641. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  55642. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  55643. })(BABYLON || (BABYLON = {}));
  55644. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  55645. var BABYLON;
  55646. (function (BABYLON) {
  55647. var GamepadManager = /** @class */ (function () {
  55648. function GamepadManager() {
  55649. var _this = this;
  55650. this._babylonGamepads = [];
  55651. this._oneGamepadConnected = false;
  55652. this._isMonitoring = false;
  55653. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  55654. if (!BABYLON.Tools.IsWindowObjectExist()) {
  55655. this._gamepadEventSupported = false;
  55656. }
  55657. else {
  55658. this._gamepadEventSupported = 'GamepadEvent' in window;
  55659. this._gamepadSupport = (navigator.getGamepads ||
  55660. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  55661. }
  55662. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  55663. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  55664. for (var i in _this._babylonGamepads) {
  55665. var gamepad = _this._babylonGamepads[i];
  55666. if (gamepad && gamepad._isConnected) {
  55667. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  55668. }
  55669. }
  55670. });
  55671. this._onGamepadConnectedEvent = function (evt) {
  55672. var gamepad = evt.gamepad;
  55673. if (gamepad.index in _this._babylonGamepads) {
  55674. if (_this._babylonGamepads[gamepad.index].isConnected) {
  55675. return;
  55676. }
  55677. }
  55678. var newGamepad;
  55679. if (_this._babylonGamepads[gamepad.index]) {
  55680. newGamepad = _this._babylonGamepads[gamepad.index];
  55681. newGamepad.browserGamepad = gamepad;
  55682. newGamepad._isConnected = true;
  55683. }
  55684. else {
  55685. newGamepad = _this._addNewGamepad(gamepad);
  55686. }
  55687. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  55688. _this._startMonitoringGamepads();
  55689. };
  55690. this._onGamepadDisconnectedEvent = function (evt) {
  55691. var gamepad = evt.gamepad;
  55692. // Remove the gamepad from the list of gamepads to monitor.
  55693. for (var i in _this._babylonGamepads) {
  55694. if (_this._babylonGamepads[i].index === gamepad.index) {
  55695. var disconnectedGamepad = _this._babylonGamepads[i];
  55696. disconnectedGamepad._isConnected = false;
  55697. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  55698. break;
  55699. }
  55700. }
  55701. };
  55702. if (this._gamepadSupport) {
  55703. //first add already-connected gamepads
  55704. this._updateGamepadObjects();
  55705. if (this._babylonGamepads.length) {
  55706. this._startMonitoringGamepads();
  55707. }
  55708. // Checking if the gamepad connected event is supported (like in Firefox)
  55709. if (this._gamepadEventSupported) {
  55710. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  55711. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  55712. }
  55713. else {
  55714. this._startMonitoringGamepads();
  55715. }
  55716. }
  55717. }
  55718. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  55719. get: function () {
  55720. return this._babylonGamepads;
  55721. },
  55722. enumerable: true,
  55723. configurable: true
  55724. });
  55725. GamepadManager.prototype.getGamepadByType = function (type) {
  55726. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  55727. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  55728. var gamepad = _a[_i];
  55729. if (gamepad && gamepad.type === type) {
  55730. return gamepad;
  55731. }
  55732. }
  55733. return null;
  55734. };
  55735. GamepadManager.prototype.dispose = function () {
  55736. if (this._gamepadEventSupported) {
  55737. if (this._onGamepadConnectedEvent) {
  55738. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  55739. }
  55740. if (this._onGamepadDisconnectedEvent) {
  55741. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  55742. }
  55743. this._onGamepadConnectedEvent = null;
  55744. this._onGamepadDisconnectedEvent = null;
  55745. }
  55746. this._babylonGamepads.forEach(function (gamepad) {
  55747. gamepad.dispose();
  55748. });
  55749. this.onGamepadConnectedObservable.clear();
  55750. this.onGamepadDisconnectedObservable.clear();
  55751. this._oneGamepadConnected = false;
  55752. this._stopMonitoringGamepads();
  55753. this._babylonGamepads = [];
  55754. };
  55755. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  55756. if (!this._oneGamepadConnected) {
  55757. this._oneGamepadConnected = true;
  55758. }
  55759. var newGamepad;
  55760. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  55761. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  55762. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  55763. }
  55764. else if (gamepad.pose) {
  55765. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  55766. }
  55767. else {
  55768. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  55769. }
  55770. this._babylonGamepads[newGamepad.index] = newGamepad;
  55771. return newGamepad;
  55772. };
  55773. GamepadManager.prototype._startMonitoringGamepads = function () {
  55774. if (!this._isMonitoring) {
  55775. this._isMonitoring = true;
  55776. this._checkGamepadsStatus();
  55777. }
  55778. };
  55779. GamepadManager.prototype._stopMonitoringGamepads = function () {
  55780. this._isMonitoring = false;
  55781. };
  55782. GamepadManager.prototype._checkGamepadsStatus = function () {
  55783. var _this = this;
  55784. // Hack to be compatible Chrome
  55785. this._updateGamepadObjects();
  55786. for (var i in this._babylonGamepads) {
  55787. var gamepad = this._babylonGamepads[i];
  55788. if (!gamepad || !gamepad.isConnected) {
  55789. continue;
  55790. }
  55791. gamepad.update();
  55792. }
  55793. if (this._isMonitoring) {
  55794. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  55795. }
  55796. };
  55797. // This function is called only on Chrome, which does not properly support
  55798. // connection/disconnection events and forces you to recopy again the gamepad object
  55799. GamepadManager.prototype._updateGamepadObjects = function () {
  55800. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  55801. for (var i = 0; i < gamepads.length; i++) {
  55802. if (gamepads[i]) {
  55803. if (!this._babylonGamepads[gamepads[i].index]) {
  55804. var newGamepad = this._addNewGamepad(gamepads[i]);
  55805. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  55806. }
  55807. else {
  55808. // Forced to copy again this object for Chrome for unknown reason
  55809. this._babylonGamepads[i].browserGamepad = gamepads[i];
  55810. if (!this._babylonGamepads[i].isConnected) {
  55811. this._babylonGamepads[i]._isConnected = true;
  55812. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  55813. }
  55814. }
  55815. }
  55816. }
  55817. };
  55818. return GamepadManager;
  55819. }());
  55820. BABYLON.GamepadManager = GamepadManager;
  55821. })(BABYLON || (BABYLON = {}));
  55822. //# sourceMappingURL=babylon.gamepadManager.js.map
  55823. var BABYLON;
  55824. (function (BABYLON) {
  55825. var StickValues = /** @class */ (function () {
  55826. function StickValues(x, y) {
  55827. this.x = x;
  55828. this.y = y;
  55829. }
  55830. return StickValues;
  55831. }());
  55832. BABYLON.StickValues = StickValues;
  55833. var Gamepad = /** @class */ (function () {
  55834. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  55835. if (leftStickX === void 0) { leftStickX = 0; }
  55836. if (leftStickY === void 0) { leftStickY = 1; }
  55837. if (rightStickX === void 0) { rightStickX = 2; }
  55838. if (rightStickY === void 0) { rightStickY = 3; }
  55839. this.id = id;
  55840. this.index = index;
  55841. this.browserGamepad = browserGamepad;
  55842. this._isConnected = true;
  55843. this.type = Gamepad.GAMEPAD;
  55844. this._leftStickAxisX = leftStickX;
  55845. this._leftStickAxisY = leftStickY;
  55846. this._rightStickAxisX = rightStickX;
  55847. this._rightStickAxisY = rightStickY;
  55848. if (this.browserGamepad.axes.length >= 2) {
  55849. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55850. }
  55851. if (this.browserGamepad.axes.length >= 4) {
  55852. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55853. }
  55854. }
  55855. Object.defineProperty(Gamepad.prototype, "isConnected", {
  55856. get: function () {
  55857. return this._isConnected;
  55858. },
  55859. enumerable: true,
  55860. configurable: true
  55861. });
  55862. Gamepad.prototype.onleftstickchanged = function (callback) {
  55863. this._onleftstickchanged = callback;
  55864. };
  55865. Gamepad.prototype.onrightstickchanged = function (callback) {
  55866. this._onrightstickchanged = callback;
  55867. };
  55868. Object.defineProperty(Gamepad.prototype, "leftStick", {
  55869. get: function () {
  55870. return this._leftStick;
  55871. },
  55872. set: function (newValues) {
  55873. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  55874. this._onleftstickchanged(newValues);
  55875. }
  55876. this._leftStick = newValues;
  55877. },
  55878. enumerable: true,
  55879. configurable: true
  55880. });
  55881. Object.defineProperty(Gamepad.prototype, "rightStick", {
  55882. get: function () {
  55883. return this._rightStick;
  55884. },
  55885. set: function (newValues) {
  55886. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  55887. this._onrightstickchanged(newValues);
  55888. }
  55889. this._rightStick = newValues;
  55890. },
  55891. enumerable: true,
  55892. configurable: true
  55893. });
  55894. Gamepad.prototype.update = function () {
  55895. if (this._leftStick) {
  55896. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55897. }
  55898. if (this._rightStick) {
  55899. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55900. }
  55901. };
  55902. Gamepad.prototype.dispose = function () {
  55903. };
  55904. Gamepad.GAMEPAD = 0;
  55905. Gamepad.GENERIC = 1;
  55906. Gamepad.XBOX = 2;
  55907. Gamepad.POSE_ENABLED = 3;
  55908. return Gamepad;
  55909. }());
  55910. BABYLON.Gamepad = Gamepad;
  55911. var GenericPad = /** @class */ (function (_super) {
  55912. __extends(GenericPad, _super);
  55913. function GenericPad(id, index, browserGamepad) {
  55914. var _this = _super.call(this, id, index, browserGamepad) || this;
  55915. _this.onButtonDownObservable = new BABYLON.Observable();
  55916. _this.onButtonUpObservable = new BABYLON.Observable();
  55917. _this.type = Gamepad.GENERIC;
  55918. _this._buttons = new Array(browserGamepad.buttons.length);
  55919. return _this;
  55920. }
  55921. GenericPad.prototype.onbuttondown = function (callback) {
  55922. this._onbuttondown = callback;
  55923. };
  55924. GenericPad.prototype.onbuttonup = function (callback) {
  55925. this._onbuttonup = callback;
  55926. };
  55927. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  55928. if (newValue !== currentValue) {
  55929. if (newValue === 1) {
  55930. if (this._onbuttondown) {
  55931. this._onbuttondown(buttonIndex);
  55932. }
  55933. this.onButtonDownObservable.notifyObservers(buttonIndex);
  55934. }
  55935. if (newValue === 0) {
  55936. if (this._onbuttonup) {
  55937. this._onbuttonup(buttonIndex);
  55938. }
  55939. this.onButtonUpObservable.notifyObservers(buttonIndex);
  55940. }
  55941. }
  55942. return newValue;
  55943. };
  55944. GenericPad.prototype.update = function () {
  55945. _super.prototype.update.call(this);
  55946. for (var index = 0; index < this._buttons.length; index++) {
  55947. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  55948. }
  55949. };
  55950. return GenericPad;
  55951. }(Gamepad));
  55952. BABYLON.GenericPad = GenericPad;
  55953. })(BABYLON || (BABYLON = {}));
  55954. //# sourceMappingURL=babylon.gamepad.js.map
  55955. var BABYLON;
  55956. (function (BABYLON) {
  55957. var Xbox360Button;
  55958. (function (Xbox360Button) {
  55959. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  55960. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  55961. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  55962. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  55963. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  55964. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  55965. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  55966. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  55967. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  55968. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  55969. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  55970. var Xbox360Dpad;
  55971. (function (Xbox360Dpad) {
  55972. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  55973. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  55974. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  55975. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  55976. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  55977. var Xbox360Pad = /** @class */ (function (_super) {
  55978. __extends(Xbox360Pad, _super);
  55979. function Xbox360Pad(id, index, gamepad, xboxOne) {
  55980. if (xboxOne === void 0) { xboxOne = false; }
  55981. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  55982. _this._leftTrigger = 0;
  55983. _this._rightTrigger = 0;
  55984. _this.onButtonDownObservable = new BABYLON.Observable();
  55985. _this.onButtonUpObservable = new BABYLON.Observable();
  55986. _this.onPadDownObservable = new BABYLON.Observable();
  55987. _this.onPadUpObservable = new BABYLON.Observable();
  55988. _this._buttonA = 0;
  55989. _this._buttonB = 0;
  55990. _this._buttonX = 0;
  55991. _this._buttonY = 0;
  55992. _this._buttonBack = 0;
  55993. _this._buttonStart = 0;
  55994. _this._buttonLB = 0;
  55995. _this._buttonRB = 0;
  55996. _this._buttonLeftStick = 0;
  55997. _this._buttonRightStick = 0;
  55998. _this._dPadUp = 0;
  55999. _this._dPadDown = 0;
  56000. _this._dPadLeft = 0;
  56001. _this._dPadRight = 0;
  56002. _this._isXboxOnePad = false;
  56003. _this.type = BABYLON.Gamepad.XBOX;
  56004. _this._isXboxOnePad = xboxOne;
  56005. return _this;
  56006. }
  56007. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  56008. this._onlefttriggerchanged = callback;
  56009. };
  56010. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  56011. this._onrighttriggerchanged = callback;
  56012. };
  56013. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  56014. get: function () {
  56015. return this._leftTrigger;
  56016. },
  56017. set: function (newValue) {
  56018. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  56019. this._onlefttriggerchanged(newValue);
  56020. }
  56021. this._leftTrigger = newValue;
  56022. },
  56023. enumerable: true,
  56024. configurable: true
  56025. });
  56026. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  56027. get: function () {
  56028. return this._rightTrigger;
  56029. },
  56030. set: function (newValue) {
  56031. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  56032. this._onrighttriggerchanged(newValue);
  56033. }
  56034. this._rightTrigger = newValue;
  56035. },
  56036. enumerable: true,
  56037. configurable: true
  56038. });
  56039. Xbox360Pad.prototype.onbuttondown = function (callback) {
  56040. this._onbuttondown = callback;
  56041. };
  56042. Xbox360Pad.prototype.onbuttonup = function (callback) {
  56043. this._onbuttonup = callback;
  56044. };
  56045. Xbox360Pad.prototype.ondpaddown = function (callback) {
  56046. this._ondpaddown = callback;
  56047. };
  56048. Xbox360Pad.prototype.ondpadup = function (callback) {
  56049. this._ondpadup = callback;
  56050. };
  56051. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  56052. if (newValue !== currentValue) {
  56053. if (newValue === 1) {
  56054. if (this._onbuttondown) {
  56055. this._onbuttondown(buttonType);
  56056. }
  56057. this.onButtonDownObservable.notifyObservers(buttonType);
  56058. }
  56059. if (newValue === 0) {
  56060. if (this._onbuttonup) {
  56061. this._onbuttonup(buttonType);
  56062. }
  56063. this.onButtonUpObservable.notifyObservers(buttonType);
  56064. }
  56065. }
  56066. return newValue;
  56067. };
  56068. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  56069. if (newValue !== currentValue) {
  56070. if (newValue === 1) {
  56071. if (this._ondpaddown) {
  56072. this._ondpaddown(buttonType);
  56073. }
  56074. this.onPadDownObservable.notifyObservers(buttonType);
  56075. }
  56076. if (newValue === 0) {
  56077. if (this._ondpadup) {
  56078. this._ondpadup(buttonType);
  56079. }
  56080. this.onPadUpObservable.notifyObservers(buttonType);
  56081. }
  56082. }
  56083. return newValue;
  56084. };
  56085. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  56086. get: function () {
  56087. return this._buttonA;
  56088. },
  56089. set: function (value) {
  56090. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  56091. },
  56092. enumerable: true,
  56093. configurable: true
  56094. });
  56095. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  56096. get: function () {
  56097. return this._buttonB;
  56098. },
  56099. set: function (value) {
  56100. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  56101. },
  56102. enumerable: true,
  56103. configurable: true
  56104. });
  56105. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  56106. get: function () {
  56107. return this._buttonX;
  56108. },
  56109. set: function (value) {
  56110. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  56111. },
  56112. enumerable: true,
  56113. configurable: true
  56114. });
  56115. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  56116. get: function () {
  56117. return this._buttonY;
  56118. },
  56119. set: function (value) {
  56120. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  56121. },
  56122. enumerable: true,
  56123. configurable: true
  56124. });
  56125. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  56126. get: function () {
  56127. return this._buttonStart;
  56128. },
  56129. set: function (value) {
  56130. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  56131. },
  56132. enumerable: true,
  56133. configurable: true
  56134. });
  56135. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  56136. get: function () {
  56137. return this._buttonBack;
  56138. },
  56139. set: function (value) {
  56140. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  56141. },
  56142. enumerable: true,
  56143. configurable: true
  56144. });
  56145. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  56146. get: function () {
  56147. return this._buttonLB;
  56148. },
  56149. set: function (value) {
  56150. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  56151. },
  56152. enumerable: true,
  56153. configurable: true
  56154. });
  56155. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  56156. get: function () {
  56157. return this._buttonRB;
  56158. },
  56159. set: function (value) {
  56160. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  56161. },
  56162. enumerable: true,
  56163. configurable: true
  56164. });
  56165. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  56166. get: function () {
  56167. return this._buttonLeftStick;
  56168. },
  56169. set: function (value) {
  56170. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  56171. },
  56172. enumerable: true,
  56173. configurable: true
  56174. });
  56175. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  56176. get: function () {
  56177. return this._buttonRightStick;
  56178. },
  56179. set: function (value) {
  56180. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  56181. },
  56182. enumerable: true,
  56183. configurable: true
  56184. });
  56185. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  56186. get: function () {
  56187. return this._dPadUp;
  56188. },
  56189. set: function (value) {
  56190. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  56191. },
  56192. enumerable: true,
  56193. configurable: true
  56194. });
  56195. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  56196. get: function () {
  56197. return this._dPadDown;
  56198. },
  56199. set: function (value) {
  56200. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  56201. },
  56202. enumerable: true,
  56203. configurable: true
  56204. });
  56205. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  56206. get: function () {
  56207. return this._dPadLeft;
  56208. },
  56209. set: function (value) {
  56210. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  56211. },
  56212. enumerable: true,
  56213. configurable: true
  56214. });
  56215. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  56216. get: function () {
  56217. return this._dPadRight;
  56218. },
  56219. set: function (value) {
  56220. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  56221. },
  56222. enumerable: true,
  56223. configurable: true
  56224. });
  56225. Xbox360Pad.prototype.update = function () {
  56226. _super.prototype.update.call(this);
  56227. if (this._isXboxOnePad) {
  56228. this.buttonA = this.browserGamepad.buttons[0].value;
  56229. this.buttonB = this.browserGamepad.buttons[1].value;
  56230. this.buttonX = this.browserGamepad.buttons[2].value;
  56231. this.buttonY = this.browserGamepad.buttons[3].value;
  56232. this.buttonLB = this.browserGamepad.buttons[4].value;
  56233. this.buttonRB = this.browserGamepad.buttons[5].value;
  56234. this.leftTrigger = this.browserGamepad.axes[2];
  56235. this.rightTrigger = this.browserGamepad.axes[5];
  56236. this.buttonBack = this.browserGamepad.buttons[9].value;
  56237. this.buttonStart = this.browserGamepad.buttons[8].value;
  56238. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  56239. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  56240. this.dPadUp = this.browserGamepad.buttons[11].value;
  56241. this.dPadDown = this.browserGamepad.buttons[12].value;
  56242. this.dPadLeft = this.browserGamepad.buttons[13].value;
  56243. this.dPadRight = this.browserGamepad.buttons[14].value;
  56244. }
  56245. else {
  56246. this.buttonA = this.browserGamepad.buttons[0].value;
  56247. this.buttonB = this.browserGamepad.buttons[1].value;
  56248. this.buttonX = this.browserGamepad.buttons[2].value;
  56249. this.buttonY = this.browserGamepad.buttons[3].value;
  56250. this.buttonLB = this.browserGamepad.buttons[4].value;
  56251. this.buttonRB = this.browserGamepad.buttons[5].value;
  56252. this.leftTrigger = this.browserGamepad.buttons[6].value;
  56253. this.rightTrigger = this.browserGamepad.buttons[7].value;
  56254. this.buttonBack = this.browserGamepad.buttons[8].value;
  56255. this.buttonStart = this.browserGamepad.buttons[9].value;
  56256. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  56257. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  56258. this.dPadUp = this.browserGamepad.buttons[12].value;
  56259. this.dPadDown = this.browserGamepad.buttons[13].value;
  56260. this.dPadLeft = this.browserGamepad.buttons[14].value;
  56261. this.dPadRight = this.browserGamepad.buttons[15].value;
  56262. }
  56263. };
  56264. return Xbox360Pad;
  56265. }(BABYLON.Gamepad));
  56266. BABYLON.Xbox360Pad = Xbox360Pad;
  56267. })(BABYLON || (BABYLON = {}));
  56268. //# sourceMappingURL=babylon.xboxGamepad.js.map
  56269. var BABYLON;
  56270. (function (BABYLON) {
  56271. var PoseEnabledControllerType;
  56272. (function (PoseEnabledControllerType) {
  56273. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  56274. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  56275. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  56276. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  56277. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  56278. var PoseEnabledControllerHelper = /** @class */ (function () {
  56279. function PoseEnabledControllerHelper() {
  56280. }
  56281. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  56282. // Oculus Touch
  56283. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  56284. return new BABYLON.OculusTouchController(vrGamepad);
  56285. }
  56286. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  56287. return new BABYLON.WindowsMotionController(vrGamepad);
  56288. }
  56289. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  56290. return new BABYLON.ViveController(vrGamepad);
  56291. }
  56292. else {
  56293. return new BABYLON.GenericController(vrGamepad);
  56294. }
  56295. };
  56296. return PoseEnabledControllerHelper;
  56297. }());
  56298. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  56299. var PoseEnabledController = /** @class */ (function (_super) {
  56300. __extends(PoseEnabledController, _super);
  56301. function PoseEnabledController(browserGamepad) {
  56302. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  56303. _this.deviceScaleFactor = 1;
  56304. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  56305. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  56306. _this.controllerType = PoseEnabledControllerType.GENERIC;
  56307. _this.position = BABYLON.Vector3.Zero();
  56308. _this.rotationQuaternion = new BABYLON.Quaternion();
  56309. _this.devicePosition = BABYLON.Vector3.Zero();
  56310. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  56311. _this._calculatedPosition = BABYLON.Vector3.Zero();
  56312. _this._calculatedRotation = new BABYLON.Quaternion();
  56313. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  56314. return _this;
  56315. }
  56316. PoseEnabledController.prototype.update = function () {
  56317. _super.prototype.update.call(this);
  56318. var pose = this.browserGamepad.pose;
  56319. this.updateFromDevice(pose);
  56320. if (this._mesh) {
  56321. this._mesh.position.copyFrom(this._calculatedPosition);
  56322. if (this._mesh.rotationQuaternion) {
  56323. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  56324. }
  56325. }
  56326. };
  56327. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  56328. if (poseData) {
  56329. this.rawPose = poseData;
  56330. if (poseData.position) {
  56331. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  56332. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  56333. this.devicePosition.z *= -1;
  56334. }
  56335. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  56336. this._calculatedPosition.addInPlace(this.position);
  56337. }
  56338. var pose = this.rawPose;
  56339. if (poseData.orientation && pose.orientation) {
  56340. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  56341. if (this._mesh) {
  56342. if (this._mesh.getScene().useRightHandedSystem) {
  56343. this.deviceRotationQuaternion.z *= -1;
  56344. this.deviceRotationQuaternion.w *= -1;
  56345. }
  56346. else {
  56347. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  56348. }
  56349. }
  56350. // if the camera is set, rotate to the camera's rotation
  56351. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  56352. }
  56353. }
  56354. };
  56355. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  56356. if (this._mesh) {
  56357. this._mesh.parent = null;
  56358. }
  56359. this._mesh = mesh;
  56360. if (this._poseControlledCamera) {
  56361. this._mesh.parent = this._poseControlledCamera;
  56362. }
  56363. if (!this._mesh.rotationQuaternion) {
  56364. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  56365. }
  56366. };
  56367. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  56368. this._poseControlledCamera = camera;
  56369. if (this._mesh) {
  56370. this._mesh.parent = this._poseControlledCamera;
  56371. }
  56372. };
  56373. PoseEnabledController.prototype.dispose = function () {
  56374. if (this._mesh) {
  56375. this._mesh.dispose();
  56376. }
  56377. this._mesh = null;
  56378. _super.prototype.dispose.call(this);
  56379. };
  56380. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  56381. get: function () {
  56382. return this._mesh;
  56383. },
  56384. enumerable: true,
  56385. configurable: true
  56386. });
  56387. PoseEnabledController.prototype.getForwardRay = function (length) {
  56388. if (length === void 0) { length = 100; }
  56389. if (!this.mesh) {
  56390. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  56391. }
  56392. var m = this.mesh.getWorldMatrix();
  56393. var origin = m.getTranslation();
  56394. var forward = new BABYLON.Vector3(0, 0, -1);
  56395. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56396. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56397. return new BABYLON.Ray(origin, direction, length);
  56398. };
  56399. return PoseEnabledController;
  56400. }(BABYLON.Gamepad));
  56401. BABYLON.PoseEnabledController = PoseEnabledController;
  56402. })(BABYLON || (BABYLON = {}));
  56403. //# sourceMappingURL=babylon.poseEnabledController.js.map
  56404. var BABYLON;
  56405. (function (BABYLON) {
  56406. var WebVRController = /** @class */ (function (_super) {
  56407. __extends(WebVRController, _super);
  56408. function WebVRController(vrGamepad) {
  56409. var _this = _super.call(this, vrGamepad) || this;
  56410. // Observables
  56411. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  56412. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  56413. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  56414. _this.onPadStateChangedObservable = new BABYLON.Observable();
  56415. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  56416. _this.pad = { x: 0, y: 0 };
  56417. // avoid GC, store state in a tmp object
  56418. _this._changes = {
  56419. pressChanged: false,
  56420. touchChanged: false,
  56421. valueChanged: false,
  56422. changed: false
  56423. };
  56424. _this._buttons = new Array(vrGamepad.buttons.length);
  56425. _this.hand = vrGamepad.hand;
  56426. return _this;
  56427. }
  56428. WebVRController.prototype.onButtonStateChange = function (callback) {
  56429. this._onButtonStateChange = callback;
  56430. };
  56431. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  56432. get: function () {
  56433. return this._defaultModel;
  56434. },
  56435. enumerable: true,
  56436. configurable: true
  56437. });
  56438. WebVRController.prototype.update = function () {
  56439. _super.prototype.update.call(this);
  56440. for (var index = 0; index < this._buttons.length; index++) {
  56441. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  56442. }
  56443. ;
  56444. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  56445. this.pad.x = this.leftStick.x;
  56446. this.pad.y = this.leftStick.y;
  56447. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  56448. }
  56449. };
  56450. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  56451. if (!newState) {
  56452. newState = {
  56453. pressed: false,
  56454. touched: false,
  56455. value: 0
  56456. };
  56457. }
  56458. if (!currentState) {
  56459. this._buttons[buttonIndex] = {
  56460. pressed: newState.pressed,
  56461. touched: newState.touched,
  56462. value: newState.value
  56463. };
  56464. return;
  56465. }
  56466. this._checkChanges(newState, currentState);
  56467. if (this._changes.changed) {
  56468. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  56469. this.handleButtonChange(buttonIndex, newState, this._changes);
  56470. }
  56471. this._buttons[buttonIndex].pressed = newState.pressed;
  56472. this._buttons[buttonIndex].touched = newState.touched;
  56473. // oculus triggers are never 0, thou not touched.
  56474. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  56475. };
  56476. WebVRController.prototype._checkChanges = function (newState, currentState) {
  56477. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  56478. this._changes.touchChanged = newState.touched !== currentState.touched;
  56479. this._changes.valueChanged = newState.value !== currentState.value;
  56480. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  56481. return this._changes;
  56482. };
  56483. WebVRController.prototype.dispose = function () {
  56484. _super.prototype.dispose.call(this);
  56485. this.onTriggerStateChangedObservable.clear();
  56486. this.onMainButtonStateChangedObservable.clear();
  56487. this.onSecondaryButtonStateChangedObservable.clear();
  56488. this.onPadStateChangedObservable.clear();
  56489. this.onPadValuesChangedObservable.clear();
  56490. };
  56491. return WebVRController;
  56492. }(BABYLON.PoseEnabledController));
  56493. BABYLON.WebVRController = WebVRController;
  56494. })(BABYLON || (BABYLON = {}));
  56495. //# sourceMappingURL=babylon.webVRController.js.map
  56496. var BABYLON;
  56497. (function (BABYLON) {
  56498. var OculusTouchController = /** @class */ (function (_super) {
  56499. __extends(OculusTouchController, _super);
  56500. function OculusTouchController(vrGamepad) {
  56501. var _this = _super.call(this, vrGamepad) || this;
  56502. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  56503. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  56504. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  56505. return _this;
  56506. }
  56507. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56508. var _this = this;
  56509. var meshName;
  56510. // Hand
  56511. if (this.hand === 'left') {
  56512. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  56513. }
  56514. else {
  56515. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  56516. }
  56517. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  56518. /*
  56519. Parent Mesh name: oculus_touch_left
  56520. - body
  56521. - trigger
  56522. - thumbstick
  56523. - grip
  56524. - button_y
  56525. - button_x
  56526. - button_enter
  56527. */
  56528. _this._defaultModel = newMeshes[1];
  56529. _this.attachToMesh(_this._defaultModel);
  56530. if (meshLoaded) {
  56531. meshLoaded(_this._defaultModel);
  56532. }
  56533. });
  56534. };
  56535. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  56536. // helper getters for left and right hand.
  56537. get: function () {
  56538. if (this.hand === 'right') {
  56539. return this.onMainButtonStateChangedObservable;
  56540. }
  56541. else {
  56542. throw new Error('No A button on left hand');
  56543. }
  56544. },
  56545. enumerable: true,
  56546. configurable: true
  56547. });
  56548. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  56549. get: function () {
  56550. if (this.hand === 'right') {
  56551. return this.onSecondaryButtonStateChangedObservable;
  56552. }
  56553. else {
  56554. throw new Error('No B button on left hand');
  56555. }
  56556. },
  56557. enumerable: true,
  56558. configurable: true
  56559. });
  56560. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  56561. get: function () {
  56562. if (this.hand === 'left') {
  56563. return this.onMainButtonStateChangedObservable;
  56564. }
  56565. else {
  56566. throw new Error('No X button on right hand');
  56567. }
  56568. },
  56569. enumerable: true,
  56570. configurable: true
  56571. });
  56572. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  56573. get: function () {
  56574. if (this.hand === 'left') {
  56575. return this.onSecondaryButtonStateChangedObservable;
  56576. }
  56577. else {
  56578. throw new Error('No Y button on right hand');
  56579. }
  56580. },
  56581. enumerable: true,
  56582. configurable: true
  56583. });
  56584. /*
  56585. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  56586. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  56587. 2) secondary trigger (same)
  56588. 3) A (right) X (left), touch, pressed = value
  56589. 4) B / Y
  56590. 5) thumb rest
  56591. */
  56592. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56593. var notifyObject = state; //{ state: state, changes: changes };
  56594. var triggerDirection = this.hand === 'right' ? -1 : 1;
  56595. switch (buttonIdx) {
  56596. case 0:
  56597. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  56598. return;
  56599. case 1:// index trigger
  56600. if (this._defaultModel) {
  56601. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  56602. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  56603. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  56604. }
  56605. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56606. return;
  56607. case 2:// secondary trigger
  56608. if (this._defaultModel) {
  56609. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  56610. }
  56611. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  56612. return;
  56613. case 3:
  56614. if (this._defaultModel) {
  56615. if (notifyObject.pressed) {
  56616. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  56617. }
  56618. else {
  56619. (this._defaultModel.getChildren()[1]).position.y = 0;
  56620. }
  56621. }
  56622. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56623. return;
  56624. case 4:
  56625. if (this._defaultModel) {
  56626. if (notifyObject.pressed) {
  56627. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56628. }
  56629. else {
  56630. (this._defaultModel.getChildren()[2]).position.y = 0;
  56631. }
  56632. }
  56633. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56634. return;
  56635. case 5:
  56636. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  56637. return;
  56638. }
  56639. };
  56640. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  56641. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  56642. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  56643. return OculusTouchController;
  56644. }(BABYLON.WebVRController));
  56645. BABYLON.OculusTouchController = OculusTouchController;
  56646. })(BABYLON || (BABYLON = {}));
  56647. //# sourceMappingURL=babylon.oculusTouchController.js.map
  56648. var BABYLON;
  56649. (function (BABYLON) {
  56650. var ViveController = /** @class */ (function (_super) {
  56651. __extends(ViveController, _super);
  56652. function ViveController(vrGamepad) {
  56653. var _this = _super.call(this, vrGamepad) || this;
  56654. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  56655. return _this;
  56656. }
  56657. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56658. var _this = this;
  56659. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  56660. /*
  56661. Parent Mesh name: ViveWand
  56662. - body
  56663. - r_gripper
  56664. - l_gripper
  56665. - menu_button
  56666. - system_button
  56667. - trackpad
  56668. - trigger
  56669. - LED
  56670. */
  56671. _this._defaultModel = newMeshes[1];
  56672. _this.attachToMesh(_this._defaultModel);
  56673. if (meshLoaded) {
  56674. meshLoaded(_this._defaultModel);
  56675. }
  56676. });
  56677. };
  56678. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  56679. get: function () {
  56680. return this.onMainButtonStateChangedObservable;
  56681. },
  56682. enumerable: true,
  56683. configurable: true
  56684. });
  56685. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  56686. get: function () {
  56687. return this.onMainButtonStateChangedObservable;
  56688. },
  56689. enumerable: true,
  56690. configurable: true
  56691. });
  56692. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  56693. get: function () {
  56694. return this.onSecondaryButtonStateChangedObservable;
  56695. },
  56696. enumerable: true,
  56697. configurable: true
  56698. });
  56699. /**
  56700. * Vive mapping:
  56701. * 0: touchpad
  56702. * 1: trigger
  56703. * 2: left AND right buttons
  56704. * 3: menu button
  56705. */
  56706. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56707. var notifyObject = state; //{ state: state, changes: changes };
  56708. switch (buttonIdx) {
  56709. case 0:
  56710. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  56711. return;
  56712. case 1:// index trigger
  56713. if (this._defaultModel) {
  56714. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  56715. }
  56716. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56717. return;
  56718. case 2:// left AND right button
  56719. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56720. return;
  56721. case 3:
  56722. if (this._defaultModel) {
  56723. if (notifyObject.pressed) {
  56724. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56725. }
  56726. else {
  56727. (this._defaultModel.getChildren()[2]).position.y = 0;
  56728. }
  56729. }
  56730. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56731. return;
  56732. }
  56733. };
  56734. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  56735. ViveController.MODEL_FILENAME = 'wand.babylon';
  56736. return ViveController;
  56737. }(BABYLON.WebVRController));
  56738. BABYLON.ViveController = ViveController;
  56739. })(BABYLON || (BABYLON = {}));
  56740. //# sourceMappingURL=babylon.viveController.js.map
  56741. var BABYLON;
  56742. (function (BABYLON) {
  56743. var GenericController = /** @class */ (function (_super) {
  56744. __extends(GenericController, _super);
  56745. function GenericController(vrGamepad) {
  56746. return _super.call(this, vrGamepad) || this;
  56747. }
  56748. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56749. var _this = this;
  56750. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  56751. _this._defaultModel = newMeshes[1];
  56752. _this.attachToMesh(_this._defaultModel);
  56753. if (meshLoaded) {
  56754. meshLoaded(_this._defaultModel);
  56755. }
  56756. });
  56757. };
  56758. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56759. console.log("Button id: " + buttonIdx + "state: ");
  56760. console.dir(state);
  56761. };
  56762. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  56763. GenericController.MODEL_FILENAME = 'generic.babylon';
  56764. return GenericController;
  56765. }(BABYLON.WebVRController));
  56766. BABYLON.GenericController = GenericController;
  56767. })(BABYLON || (BABYLON = {}));
  56768. //# sourceMappingURL=babylon.genericController.js.map
  56769. var BABYLON;
  56770. (function (BABYLON) {
  56771. var LoadedMeshInfo = /** @class */ (function () {
  56772. function LoadedMeshInfo() {
  56773. this.buttonMeshes = {};
  56774. this.axisMeshes = {};
  56775. }
  56776. return LoadedMeshInfo;
  56777. }());
  56778. var WindowsMotionController = /** @class */ (function (_super) {
  56779. __extends(WindowsMotionController, _super);
  56780. function WindowsMotionController(vrGamepad) {
  56781. var _this = _super.call(this, vrGamepad) || this;
  56782. _this._mapping = {
  56783. // Semantic button names
  56784. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  56785. // A mapping of the button name to glTF model node name
  56786. // that should be transformed by button value.
  56787. buttonMeshNames: {
  56788. 'trigger': 'SELECT',
  56789. 'menu': 'MENU',
  56790. 'grip': 'GRASP',
  56791. 'thumbstick': 'THUMBSTICK_PRESS',
  56792. 'trackpad': 'TOUCHPAD_PRESS'
  56793. },
  56794. // This mapping is used to translate from the Motion Controller to Babylon semantics
  56795. buttonObservableNames: {
  56796. 'trigger': 'onTriggerStateChangedObservable',
  56797. 'menu': 'onSecondaryButtonStateChangedObservable',
  56798. 'grip': 'onMainButtonStateChangedObservable',
  56799. 'thumbstick': 'onPadStateChangedObservable',
  56800. 'trackpad': 'onTrackpadChangedObservable'
  56801. },
  56802. // A mapping of the axis name to glTF model node name
  56803. // that should be transformed by axis value.
  56804. // This array mirrors the browserGamepad.axes array, such that
  56805. // the mesh corresponding to axis 0 is in this array index 0.
  56806. axisMeshNames: [
  56807. 'THUMBSTICK_X',
  56808. 'THUMBSTICK_Y',
  56809. 'TOUCHPAD_TOUCH_X',
  56810. 'TOUCHPAD_TOUCH_Y'
  56811. ],
  56812. pointingPoseMeshName: 'POINTING_POSE'
  56813. };
  56814. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  56815. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  56816. _this._loadedMeshInfo = null;
  56817. return _this;
  56818. }
  56819. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  56820. get: function () {
  56821. return this.onTriggerStateChangedObservable;
  56822. },
  56823. enumerable: true,
  56824. configurable: true
  56825. });
  56826. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  56827. get: function () {
  56828. return this.onSecondaryButtonStateChangedObservable;
  56829. },
  56830. enumerable: true,
  56831. configurable: true
  56832. });
  56833. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  56834. get: function () {
  56835. return this.onMainButtonStateChangedObservable;
  56836. },
  56837. enumerable: true,
  56838. configurable: true
  56839. });
  56840. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  56841. get: function () {
  56842. return this.onPadStateChangedObservable;
  56843. },
  56844. enumerable: true,
  56845. configurable: true
  56846. });
  56847. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  56848. get: function () {
  56849. return this.onTrackpadChangedObservable;
  56850. },
  56851. enumerable: true,
  56852. configurable: true
  56853. });
  56854. /**
  56855. * Called once per frame by the engine.
  56856. */
  56857. WindowsMotionController.prototype.update = function () {
  56858. _super.prototype.update.call(this);
  56859. // Only need to animate axes if there is a loaded mesh
  56860. if (this._loadedMeshInfo) {
  56861. if (this.browserGamepad.axes) {
  56862. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  56863. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  56864. }
  56865. }
  56866. }
  56867. };
  56868. /**
  56869. * Called once for each button that changed state since the last frame
  56870. * @param buttonIdx Which button index changed
  56871. * @param state New state of the button
  56872. * @param changes Which properties on the state changed since last frame
  56873. */
  56874. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56875. var buttonName = this._mapping.buttons[buttonIdx];
  56876. if (!buttonName) {
  56877. return;
  56878. }
  56879. // Only emit events for buttons that we know how to map from index to name
  56880. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  56881. if (observable) {
  56882. observable.notifyObservers(state);
  56883. }
  56884. this.lerpButtonTransform(buttonName, state.value);
  56885. };
  56886. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  56887. // If there is no loaded mesh, there is nothing to transform.
  56888. if (!this._loadedMeshInfo) {
  56889. return;
  56890. }
  56891. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  56892. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56893. return;
  56894. }
  56895. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  56896. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  56897. };
  56898. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  56899. if (!this._loadedMeshInfo) {
  56900. return;
  56901. }
  56902. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  56903. if (!meshInfo) {
  56904. return;
  56905. }
  56906. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56907. return;
  56908. }
  56909. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  56910. var lerpValue = axisValue * 0.5 + 0.5;
  56911. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  56912. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  56913. };
  56914. /**
  56915. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  56916. * @param scene scene in which to add meshes
  56917. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  56918. */
  56919. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  56920. var _this = this;
  56921. if (forceDefault === void 0) { forceDefault = false; }
  56922. var path;
  56923. var filename;
  56924. // Checking if GLB loader is present
  56925. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  56926. // Determine the device specific folder based on the ID suffix
  56927. var device = 'default';
  56928. if (this.id && !forceDefault) {
  56929. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  56930. device = ((match && match[0]) || device);
  56931. }
  56932. // Hand
  56933. if (this.hand === 'left') {
  56934. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  56935. }
  56936. else {
  56937. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  56938. }
  56939. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  56940. }
  56941. else {
  56942. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  56943. path = BABYLON.GenericController.MODEL_BASE_URL;
  56944. filename = BABYLON.GenericController.MODEL_FILENAME;
  56945. }
  56946. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  56947. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  56948. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  56949. if (!_this._loadedMeshInfo) {
  56950. return;
  56951. }
  56952. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  56953. _this.attachToMesh(_this._defaultModel);
  56954. if (meshLoaded) {
  56955. meshLoaded(_this._defaultModel);
  56956. }
  56957. }, null, function (scene, message) {
  56958. BABYLON.Tools.Log(message);
  56959. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  56960. if (!forceDefault) {
  56961. _this.initControllerMesh(scene, meshLoaded, true);
  56962. }
  56963. });
  56964. };
  56965. /**
  56966. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  56967. * can be transformed by button presses and axes values, based on this._mapping.
  56968. *
  56969. * @param scene scene in which the meshes exist
  56970. * @param meshes list of meshes that make up the controller model to process
  56971. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  56972. */
  56973. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  56974. var loadedMeshInfo = null;
  56975. // Create a new mesh to contain the glTF hierarchy
  56976. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  56977. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  56978. var childMesh = null;
  56979. for (var i = 0; i < meshes.length; i++) {
  56980. var mesh = meshes[i];
  56981. if (!mesh.parent) {
  56982. // Exclude controller meshes from picking results
  56983. mesh.isPickable = false;
  56984. // Handle root node, attach to the new parentMesh
  56985. childMesh = mesh;
  56986. break;
  56987. }
  56988. }
  56989. if (childMesh) {
  56990. childMesh.setParent(parentMesh);
  56991. // Create our mesh info. Note that this method will always return non-null.
  56992. loadedMeshInfo = this.createMeshInfo(parentMesh);
  56993. }
  56994. else {
  56995. BABYLON.Tools.Warn('Could not find root node in model file.');
  56996. }
  56997. return loadedMeshInfo;
  56998. };
  56999. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  57000. var loadedMeshInfo = new LoadedMeshInfo();
  57001. var i;
  57002. loadedMeshInfo.rootNode = rootNode;
  57003. // Reset the caches
  57004. loadedMeshInfo.buttonMeshes = {};
  57005. loadedMeshInfo.axisMeshes = {};
  57006. // Button Meshes
  57007. for (i = 0; i < this._mapping.buttons.length; i++) {
  57008. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  57009. if (!buttonMeshName) {
  57010. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  57011. continue;
  57012. }
  57013. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  57014. if (!buttonMesh) {
  57015. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  57016. continue;
  57017. }
  57018. var buttonMeshInfo = {
  57019. index: i,
  57020. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  57021. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  57022. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  57023. };
  57024. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  57025. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  57026. }
  57027. else {
  57028. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  57029. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  57030. '(VALUE: ' + !!buttonMeshInfo.value +
  57031. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  57032. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  57033. ')');
  57034. }
  57035. }
  57036. // Axis Meshes
  57037. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  57038. var axisMeshName = this._mapping.axisMeshNames[i];
  57039. if (!axisMeshName) {
  57040. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  57041. continue;
  57042. }
  57043. var axisMesh = getChildByName(rootNode, axisMeshName);
  57044. if (!axisMesh) {
  57045. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  57046. continue;
  57047. }
  57048. var axisMeshInfo = {
  57049. index: i,
  57050. value: getImmediateChildByName(axisMesh, 'VALUE'),
  57051. min: getImmediateChildByName(axisMesh, 'MIN'),
  57052. max: getImmediateChildByName(axisMesh, 'MAX')
  57053. };
  57054. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  57055. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  57056. }
  57057. else {
  57058. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  57059. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  57060. '(VALUE: ' + !!axisMeshInfo.value +
  57061. ', MIN: ' + !!axisMeshInfo.min +
  57062. ', MAX:' + !!axisMeshInfo.max +
  57063. ')');
  57064. }
  57065. }
  57066. // Pointing Ray
  57067. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  57068. if (!loadedMeshInfo.pointingPoseNode) {
  57069. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  57070. }
  57071. return loadedMeshInfo;
  57072. // Look through all children recursively. This will return null if no mesh exists with the given name.
  57073. function getChildByName(node, name) {
  57074. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  57075. }
  57076. // Look through only immediate children. This will return null if no mesh exists with the given name.
  57077. function getImmediateChildByName(node, name) {
  57078. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  57079. }
  57080. };
  57081. WindowsMotionController.prototype.getForwardRay = function (length) {
  57082. if (length === void 0) { length = 100; }
  57083. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  57084. return _super.prototype.getForwardRay.call(this, length);
  57085. }
  57086. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  57087. var origin = m.getTranslation();
  57088. var forward = new BABYLON.Vector3(0, 0, -1);
  57089. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  57090. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  57091. return new BABYLON.Ray(origin, direction, length);
  57092. };
  57093. WindowsMotionController.prototype.dispose = function () {
  57094. _super.prototype.dispose.call(this);
  57095. this.onTrackpadChangedObservable.clear();
  57096. };
  57097. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  57098. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  57099. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  57100. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  57101. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  57102. return WindowsMotionController;
  57103. }(BABYLON.WebVRController));
  57104. BABYLON.WindowsMotionController = WindowsMotionController;
  57105. })(BABYLON || (BABYLON = {}));
  57106. //# sourceMappingURL=babylon.windowsMotionController.js.map
  57107. var BABYLON;
  57108. (function (BABYLON) {
  57109. var FollowCamera = /** @class */ (function (_super) {
  57110. __extends(FollowCamera, _super);
  57111. function FollowCamera(name, position, scene, lockedTarget) {
  57112. if (lockedTarget === void 0) { lockedTarget = null; }
  57113. var _this = _super.call(this, name, position, scene) || this;
  57114. _this.radius = 12;
  57115. _this.rotationOffset = 0;
  57116. _this.heightOffset = 4;
  57117. _this.cameraAcceleration = 0.05;
  57118. _this.maxCameraSpeed = 20;
  57119. _this.lockedTarget = lockedTarget;
  57120. return _this;
  57121. }
  57122. FollowCamera.prototype.getRadians = function (degrees) {
  57123. return degrees * Math.PI / 180;
  57124. };
  57125. FollowCamera.prototype.follow = function (cameraTarget) {
  57126. if (!cameraTarget)
  57127. return;
  57128. var yRotation;
  57129. if (cameraTarget.rotationQuaternion) {
  57130. var rotMatrix = new BABYLON.Matrix();
  57131. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  57132. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  57133. }
  57134. else {
  57135. yRotation = cameraTarget.rotation.y;
  57136. }
  57137. var radians = this.getRadians(this.rotationOffset) + yRotation;
  57138. var targetPosition = cameraTarget.getAbsolutePosition();
  57139. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  57140. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  57141. var dx = targetX - this.position.x;
  57142. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  57143. var dz = (targetZ) - this.position.z;
  57144. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  57145. var vy = dy * this.cameraAcceleration;
  57146. var vz = dz * this.cameraAcceleration * 2;
  57147. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  57148. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57149. }
  57150. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  57151. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57152. }
  57153. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  57154. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57155. }
  57156. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  57157. this.setTarget(targetPosition);
  57158. };
  57159. FollowCamera.prototype._checkInputs = function () {
  57160. _super.prototype._checkInputs.call(this);
  57161. if (this.lockedTarget) {
  57162. this.follow(this.lockedTarget);
  57163. }
  57164. };
  57165. FollowCamera.prototype.getClassName = function () {
  57166. return "FollowCamera";
  57167. };
  57168. __decorate([
  57169. BABYLON.serialize()
  57170. ], FollowCamera.prototype, "radius", void 0);
  57171. __decorate([
  57172. BABYLON.serialize()
  57173. ], FollowCamera.prototype, "rotationOffset", void 0);
  57174. __decorate([
  57175. BABYLON.serialize()
  57176. ], FollowCamera.prototype, "heightOffset", void 0);
  57177. __decorate([
  57178. BABYLON.serialize()
  57179. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  57180. __decorate([
  57181. BABYLON.serialize()
  57182. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  57183. __decorate([
  57184. BABYLON.serializeAsMeshReference("lockedTargetId")
  57185. ], FollowCamera.prototype, "lockedTarget", void 0);
  57186. return FollowCamera;
  57187. }(BABYLON.TargetCamera));
  57188. BABYLON.FollowCamera = FollowCamera;
  57189. var ArcFollowCamera = /** @class */ (function (_super) {
  57190. __extends(ArcFollowCamera, _super);
  57191. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  57192. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  57193. _this.alpha = alpha;
  57194. _this.beta = beta;
  57195. _this.radius = radius;
  57196. _this.target = target;
  57197. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  57198. _this.follow();
  57199. return _this;
  57200. }
  57201. ArcFollowCamera.prototype.follow = function () {
  57202. if (!this.target) {
  57203. return;
  57204. }
  57205. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  57206. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  57207. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  57208. var targetPosition = this.target.getAbsolutePosition();
  57209. this.position = targetPosition.add(this._cartesianCoordinates);
  57210. this.setTarget(targetPosition);
  57211. };
  57212. ArcFollowCamera.prototype._checkInputs = function () {
  57213. _super.prototype._checkInputs.call(this);
  57214. this.follow();
  57215. };
  57216. ArcFollowCamera.prototype.getClassName = function () {
  57217. return "ArcFollowCamera";
  57218. };
  57219. return ArcFollowCamera;
  57220. }(BABYLON.TargetCamera));
  57221. BABYLON.ArcFollowCamera = ArcFollowCamera;
  57222. })(BABYLON || (BABYLON = {}));
  57223. //# sourceMappingURL=babylon.followCamera.js.map
  57224. var BABYLON;
  57225. (function (BABYLON) {
  57226. // We're mainly based on the logic defined into the FreeCamera code
  57227. var UniversalCamera = /** @class */ (function (_super) {
  57228. __extends(UniversalCamera, _super);
  57229. //-- end properties for backward compatibility for inputs
  57230. function UniversalCamera(name, position, scene) {
  57231. var _this = _super.call(this, name, position, scene) || this;
  57232. _this.inputs.addGamepad();
  57233. return _this;
  57234. }
  57235. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  57236. //-- Begin properties for backward compatibility for inputs
  57237. get: function () {
  57238. var gamepad = this.inputs.attached["gamepad"];
  57239. if (gamepad)
  57240. return gamepad.gamepadAngularSensibility;
  57241. return 0;
  57242. },
  57243. set: function (value) {
  57244. var gamepad = this.inputs.attached["gamepad"];
  57245. if (gamepad)
  57246. gamepad.gamepadAngularSensibility = value;
  57247. },
  57248. enumerable: true,
  57249. configurable: true
  57250. });
  57251. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  57252. get: function () {
  57253. var gamepad = this.inputs.attached["gamepad"];
  57254. if (gamepad)
  57255. return gamepad.gamepadMoveSensibility;
  57256. return 0;
  57257. },
  57258. set: function (value) {
  57259. var gamepad = this.inputs.attached["gamepad"];
  57260. if (gamepad)
  57261. gamepad.gamepadMoveSensibility = value;
  57262. },
  57263. enumerable: true,
  57264. configurable: true
  57265. });
  57266. UniversalCamera.prototype.getClassName = function () {
  57267. return "UniversalCamera";
  57268. };
  57269. return UniversalCamera;
  57270. }(BABYLON.TouchCamera));
  57271. BABYLON.UniversalCamera = UniversalCamera;
  57272. })(BABYLON || (BABYLON = {}));
  57273. //# sourceMappingURL=babylon.universalCamera.js.map
  57274. var BABYLON;
  57275. (function (BABYLON) {
  57276. // We're mainly based on the logic defined into the FreeCamera code
  57277. var GamepadCamera = /** @class */ (function (_super) {
  57278. __extends(GamepadCamera, _super);
  57279. //-- end properties for backward compatibility for inputs
  57280. function GamepadCamera(name, position, scene) {
  57281. return _super.call(this, name, position, scene) || this;
  57282. }
  57283. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  57284. //-- Begin properties for backward compatibility for inputs
  57285. get: function () {
  57286. var gamepad = this.inputs.attached["gamepad"];
  57287. if (gamepad)
  57288. return gamepad.gamepadAngularSensibility;
  57289. return 0;
  57290. },
  57291. set: function (value) {
  57292. var gamepad = this.inputs.attached["gamepad"];
  57293. if (gamepad)
  57294. gamepad.gamepadAngularSensibility = value;
  57295. },
  57296. enumerable: true,
  57297. configurable: true
  57298. });
  57299. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  57300. get: function () {
  57301. var gamepad = this.inputs.attached["gamepad"];
  57302. if (gamepad)
  57303. return gamepad.gamepadMoveSensibility;
  57304. return 0;
  57305. },
  57306. set: function (value) {
  57307. var gamepad = this.inputs.attached["gamepad"];
  57308. if (gamepad)
  57309. gamepad.gamepadMoveSensibility = value;
  57310. },
  57311. enumerable: true,
  57312. configurable: true
  57313. });
  57314. GamepadCamera.prototype.getClassName = function () {
  57315. return "GamepadCamera";
  57316. };
  57317. return GamepadCamera;
  57318. }(BABYLON.UniversalCamera));
  57319. BABYLON.GamepadCamera = GamepadCamera;
  57320. })(BABYLON || (BABYLON = {}));
  57321. //# sourceMappingURL=babylon.gamepadCamera.js.map
  57322. var BABYLON;
  57323. (function (BABYLON) {
  57324. var PostProcessRenderPipelineManager = /** @class */ (function () {
  57325. function PostProcessRenderPipelineManager() {
  57326. this._renderPipelines = {};
  57327. }
  57328. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  57329. this._renderPipelines[renderPipeline._name] = renderPipeline;
  57330. };
  57331. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  57332. if (unique === void 0) { unique = false; }
  57333. var renderPipeline = this._renderPipelines[renderPipelineName];
  57334. if (!renderPipeline) {
  57335. return;
  57336. }
  57337. renderPipeline._attachCameras(cameras, unique);
  57338. };
  57339. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  57340. var renderPipeline = this._renderPipelines[renderPipelineName];
  57341. if (!renderPipeline) {
  57342. return;
  57343. }
  57344. renderPipeline._detachCameras(cameras);
  57345. };
  57346. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  57347. var renderPipeline = this._renderPipelines[renderPipelineName];
  57348. if (!renderPipeline) {
  57349. return;
  57350. }
  57351. renderPipeline._enableEffect(renderEffectName, cameras);
  57352. };
  57353. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  57354. var renderPipeline = this._renderPipelines[renderPipelineName];
  57355. if (!renderPipeline) {
  57356. return;
  57357. }
  57358. renderPipeline._disableEffect(renderEffectName, cameras);
  57359. };
  57360. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  57361. var renderPipeline = this._renderPipelines[renderPipelineName];
  57362. if (!renderPipeline) {
  57363. return;
  57364. }
  57365. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  57366. };
  57367. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  57368. var renderPipeline = this._renderPipelines[renderPipelineName];
  57369. if (!renderPipeline) {
  57370. return;
  57371. }
  57372. renderPipeline._disableDisplayOnlyPass(cameras);
  57373. };
  57374. PostProcessRenderPipelineManager.prototype.update = function () {
  57375. for (var renderPipelineName in this._renderPipelines) {
  57376. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57377. var pipeline = this._renderPipelines[renderPipelineName];
  57378. if (!pipeline.isSupported) {
  57379. pipeline.dispose();
  57380. delete this._renderPipelines[renderPipelineName];
  57381. }
  57382. else {
  57383. pipeline._update();
  57384. }
  57385. }
  57386. }
  57387. };
  57388. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  57389. for (var renderPipelineName in this._renderPipelines) {
  57390. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57391. var pipeline = this._renderPipelines[renderPipelineName];
  57392. pipeline._rebuild();
  57393. }
  57394. }
  57395. };
  57396. PostProcessRenderPipelineManager.prototype.dispose = function () {
  57397. for (var renderPipelineName in this._renderPipelines) {
  57398. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57399. var pipeline = this._renderPipelines[renderPipelineName];
  57400. pipeline.dispose();
  57401. }
  57402. }
  57403. };
  57404. return PostProcessRenderPipelineManager;
  57405. }());
  57406. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  57407. })(BABYLON || (BABYLON = {}));
  57408. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  57409. var BABYLON;
  57410. (function (BABYLON) {
  57411. var PostProcessRenderPass = /** @class */ (function () {
  57412. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  57413. this._refCount = 0;
  57414. this._name = name;
  57415. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  57416. this.setRenderList(renderList);
  57417. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  57418. this._renderTexture.onAfterRenderObservable.add(afterRender);
  57419. this._scene = scene;
  57420. this._renderList = renderList;
  57421. }
  57422. // private
  57423. PostProcessRenderPass.prototype._incRefCount = function () {
  57424. if (this._refCount === 0) {
  57425. this._scene.customRenderTargets.push(this._renderTexture);
  57426. }
  57427. return ++this._refCount;
  57428. };
  57429. PostProcessRenderPass.prototype._decRefCount = function () {
  57430. this._refCount--;
  57431. if (this._refCount <= 0) {
  57432. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  57433. }
  57434. return this._refCount;
  57435. };
  57436. PostProcessRenderPass.prototype._update = function () {
  57437. this.setRenderList(this._renderList);
  57438. };
  57439. // public
  57440. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  57441. this._renderTexture.renderList = renderList;
  57442. };
  57443. PostProcessRenderPass.prototype.getRenderTexture = function () {
  57444. return this._renderTexture;
  57445. };
  57446. return PostProcessRenderPass;
  57447. }());
  57448. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  57449. })(BABYLON || (BABYLON = {}));
  57450. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  57451. var BABYLON;
  57452. (function (BABYLON) {
  57453. var PostProcessRenderEffect = /** @class */ (function () {
  57454. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  57455. this._name = name;
  57456. this._singleInstance = singleInstance || true;
  57457. this._getPostProcess = getPostProcess;
  57458. this._cameras = {};
  57459. this._indicesForCamera = {};
  57460. this._postProcesses = {};
  57461. this._renderPasses = {};
  57462. this._renderEffectAsPasses = {};
  57463. }
  57464. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  57465. get: function () {
  57466. for (var index in this._postProcesses) {
  57467. if (!this._postProcesses[index].isSupported) {
  57468. return false;
  57469. }
  57470. }
  57471. return true;
  57472. },
  57473. enumerable: true,
  57474. configurable: true
  57475. });
  57476. PostProcessRenderEffect.prototype._update = function () {
  57477. for (var renderPassName in this._renderPasses) {
  57478. this._renderPasses[renderPassName]._update();
  57479. }
  57480. };
  57481. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  57482. this._renderPasses[renderPass._name] = renderPass;
  57483. this._linkParameters();
  57484. };
  57485. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  57486. delete this._renderPasses[renderPass._name];
  57487. this._linkParameters();
  57488. };
  57489. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  57490. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  57491. this._linkParameters();
  57492. };
  57493. PostProcessRenderEffect.prototype.getPass = function (passName) {
  57494. for (var renderPassName in this._renderPasses) {
  57495. if (renderPassName === passName) {
  57496. return this._renderPasses[passName];
  57497. }
  57498. }
  57499. return null;
  57500. };
  57501. PostProcessRenderEffect.prototype.emptyPasses = function () {
  57502. this._renderPasses = {};
  57503. this._linkParameters();
  57504. };
  57505. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  57506. var cameraKey;
  57507. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57508. if (!cams) {
  57509. return;
  57510. }
  57511. for (var i = 0; i < cams.length; i++) {
  57512. var camera = cams[i];
  57513. var cameraName = camera.name;
  57514. if (this._singleInstance) {
  57515. cameraKey = 0;
  57516. }
  57517. else {
  57518. cameraKey = cameraName;
  57519. }
  57520. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  57521. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  57522. if (!this._indicesForCamera[cameraName]) {
  57523. this._indicesForCamera[cameraName] = [];
  57524. }
  57525. this._indicesForCamera[cameraName].push(index);
  57526. if (!this._cameras[cameraName]) {
  57527. this._cameras[cameraName] = camera;
  57528. }
  57529. for (var passName in this._renderPasses) {
  57530. this._renderPasses[passName]._incRefCount();
  57531. }
  57532. }
  57533. this._linkParameters();
  57534. };
  57535. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  57536. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57537. if (!cams) {
  57538. return;
  57539. }
  57540. for (var i = 0; i < cams.length; i++) {
  57541. var camera = cams[i];
  57542. var cameraName = camera.name;
  57543. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  57544. if (this._cameras[cameraName]) {
  57545. //this._indicesForCamera.splice(index, 1);
  57546. this._cameras[cameraName] = null;
  57547. }
  57548. for (var passName in this._renderPasses) {
  57549. this._renderPasses[passName]._decRefCount();
  57550. }
  57551. }
  57552. };
  57553. PostProcessRenderEffect.prototype._enable = function (cameras) {
  57554. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57555. if (!cams) {
  57556. return;
  57557. }
  57558. for (var i = 0; i < cams.length; i++) {
  57559. var camera = cams[i];
  57560. var cameraName = camera.name;
  57561. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  57562. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  57563. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  57564. }
  57565. }
  57566. for (var passName in this._renderPasses) {
  57567. this._renderPasses[passName]._incRefCount();
  57568. }
  57569. }
  57570. };
  57571. PostProcessRenderEffect.prototype._disable = function (cameras) {
  57572. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57573. if (!cams) {
  57574. return;
  57575. }
  57576. for (var i = 0; i < cams.length; i++) {
  57577. var camera = cams[i];
  57578. var cameraName = camera.Name;
  57579. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  57580. for (var passName in this._renderPasses) {
  57581. this._renderPasses[passName]._decRefCount();
  57582. }
  57583. }
  57584. };
  57585. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  57586. if (this._singleInstance) {
  57587. return this._postProcesses[0];
  57588. }
  57589. else {
  57590. if (!camera) {
  57591. return null;
  57592. }
  57593. return this._postProcesses[camera.name];
  57594. }
  57595. };
  57596. PostProcessRenderEffect.prototype._linkParameters = function () {
  57597. var _this = this;
  57598. for (var index in this._postProcesses) {
  57599. if (this.applyParameters) {
  57600. this.applyParameters(this._postProcesses[index]);
  57601. }
  57602. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  57603. _this._linkTextures(effect);
  57604. });
  57605. }
  57606. };
  57607. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  57608. for (var renderPassName in this._renderPasses) {
  57609. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  57610. }
  57611. for (var renderEffectName in this._renderEffectAsPasses) {
  57612. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  57613. }
  57614. };
  57615. return PostProcessRenderEffect;
  57616. }());
  57617. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  57618. })(BABYLON || (BABYLON = {}));
  57619. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  57620. var BABYLON;
  57621. (function (BABYLON) {
  57622. var PostProcessRenderPipeline = /** @class */ (function () {
  57623. function PostProcessRenderPipeline(engine, name) {
  57624. this._engine = engine;
  57625. this._name = name;
  57626. this._renderEffects = {};
  57627. this._renderEffectsForIsolatedPass = new Array();
  57628. this._cameras = [];
  57629. }
  57630. PostProcessRenderPipeline.prototype.getClassName = function () {
  57631. return "PostProcessRenderPipeline";
  57632. };
  57633. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  57634. get: function () {
  57635. for (var renderEffectName in this._renderEffects) {
  57636. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57637. if (!this._renderEffects[renderEffectName].isSupported) {
  57638. return false;
  57639. }
  57640. }
  57641. }
  57642. return true;
  57643. },
  57644. enumerable: true,
  57645. configurable: true
  57646. });
  57647. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  57648. this._renderEffects[renderEffect._name] = renderEffect;
  57649. };
  57650. // private
  57651. PostProcessRenderPipeline.prototype._rebuild = function () {
  57652. };
  57653. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  57654. var renderEffects = this._renderEffects[renderEffectName];
  57655. if (!renderEffects) {
  57656. return;
  57657. }
  57658. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  57659. };
  57660. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  57661. var renderEffects = this._renderEffects[renderEffectName];
  57662. if (!renderEffects) {
  57663. return;
  57664. }
  57665. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  57666. };
  57667. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  57668. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57669. if (!cams) {
  57670. return;
  57671. }
  57672. var indicesToDelete = [];
  57673. var i;
  57674. for (i = 0; i < cams.length; i++) {
  57675. var camera = cams[i];
  57676. var cameraName = camera.name;
  57677. if (this._cameras.indexOf(camera) === -1) {
  57678. this._cameras[cameraName] = camera;
  57679. }
  57680. else if (unique) {
  57681. indicesToDelete.push(i);
  57682. }
  57683. }
  57684. for (i = 0; i < indicesToDelete.length; i++) {
  57685. cameras.splice(indicesToDelete[i], 1);
  57686. }
  57687. for (var renderEffectName in this._renderEffects) {
  57688. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57689. this._renderEffects[renderEffectName]._attachCameras(cams);
  57690. }
  57691. }
  57692. };
  57693. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  57694. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57695. if (!cams) {
  57696. return;
  57697. }
  57698. for (var renderEffectName in this._renderEffects) {
  57699. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57700. this._renderEffects[renderEffectName]._detachCameras(cams);
  57701. }
  57702. }
  57703. for (var i = 0; i < cams.length; i++) {
  57704. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  57705. }
  57706. };
  57707. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  57708. var _this = this;
  57709. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57710. if (!cams) {
  57711. return;
  57712. }
  57713. var pass = null;
  57714. var renderEffectName;
  57715. for (renderEffectName in this._renderEffects) {
  57716. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57717. pass = this._renderEffects[renderEffectName].getPass(passName);
  57718. if (pass != null) {
  57719. break;
  57720. }
  57721. }
  57722. }
  57723. if (pass === null) {
  57724. return;
  57725. }
  57726. for (renderEffectName in this._renderEffects) {
  57727. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57728. this._renderEffects[renderEffectName]._disable(cams);
  57729. }
  57730. }
  57731. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  57732. for (var i = 0; i < cams.length; i++) {
  57733. var camera = cams[i];
  57734. var cameraName = camera.name;
  57735. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  57736. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  57737. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  57738. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  57739. }
  57740. };
  57741. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  57742. var _this = this;
  57743. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57744. if (!cams) {
  57745. return;
  57746. }
  57747. for (var i = 0; i < cams.length; i++) {
  57748. var camera = cams[i];
  57749. var cameraName = camera.name;
  57750. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  57751. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  57752. }
  57753. for (var renderEffectName in this._renderEffects) {
  57754. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57755. this._renderEffects[renderEffectName]._enable(cams);
  57756. }
  57757. }
  57758. };
  57759. PostProcessRenderPipeline.prototype._update = function () {
  57760. for (var renderEffectName in this._renderEffects) {
  57761. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57762. this._renderEffects[renderEffectName]._update();
  57763. }
  57764. }
  57765. for (var i = 0; i < this._cameras.length; i++) {
  57766. var cameraName = this._cameras[i].name;
  57767. if (this._renderEffectsForIsolatedPass[cameraName]) {
  57768. this._renderEffectsForIsolatedPass[cameraName]._update();
  57769. }
  57770. }
  57771. };
  57772. PostProcessRenderPipeline.prototype._reset = function () {
  57773. this._renderEffects = {};
  57774. this._renderEffectsForIsolatedPass = new Array();
  57775. };
  57776. PostProcessRenderPipeline.prototype.dispose = function () {
  57777. // Must be implemented by children
  57778. };
  57779. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  57780. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  57781. __decorate([
  57782. BABYLON.serialize()
  57783. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  57784. return PostProcessRenderPipeline;
  57785. }());
  57786. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  57787. })(BABYLON || (BABYLON = {}));
  57788. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  57789. var BABYLON;
  57790. (function (BABYLON) {
  57791. var DepthRenderer = /** @class */ (function () {
  57792. function DepthRenderer(scene, type) {
  57793. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  57794. var _this = this;
  57795. this._scene = scene;
  57796. var engine = scene.getEngine();
  57797. // Render target
  57798. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  57799. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57800. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57801. this._depthMap.refreshRate = 1;
  57802. this._depthMap.renderParticles = false;
  57803. this._depthMap.renderList = null;
  57804. // set default depth value to 1.0 (far away)
  57805. this._depthMap.onClearObservable.add(function (engine) {
  57806. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  57807. });
  57808. // Custom render function
  57809. var renderSubMesh = function (subMesh) {
  57810. var mesh = subMesh.getRenderingMesh();
  57811. var scene = _this._scene;
  57812. var engine = scene.getEngine();
  57813. var material = subMesh.getMaterial();
  57814. if (!material) {
  57815. return;
  57816. }
  57817. // Culling and reverse (right handed system)
  57818. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  57819. // Managing instances
  57820. var batch = mesh._getInstancesRenderList(subMesh._id);
  57821. if (batch.mustReturn) {
  57822. return;
  57823. }
  57824. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  57825. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  57826. engine.enableEffect(_this._effect);
  57827. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  57828. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  57829. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  57830. // Alpha test
  57831. if (material && material.needAlphaTesting()) {
  57832. var alphaTexture = material.getAlphaTestTexture();
  57833. if (alphaTexture) {
  57834. _this._effect.setTexture("diffuseSampler", alphaTexture);
  57835. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  57836. }
  57837. }
  57838. // Bones
  57839. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57840. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  57841. }
  57842. // Draw
  57843. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  57844. }
  57845. };
  57846. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  57847. var index;
  57848. if (depthOnlySubMeshes.length) {
  57849. engine.setColorWrite(false);
  57850. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  57851. renderSubMesh(depthOnlySubMeshes.data[index]);
  57852. }
  57853. engine.setColorWrite(true);
  57854. }
  57855. for (index = 0; index < opaqueSubMeshes.length; index++) {
  57856. renderSubMesh(opaqueSubMeshes.data[index]);
  57857. }
  57858. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  57859. renderSubMesh(alphaTestSubMeshes.data[index]);
  57860. }
  57861. };
  57862. }
  57863. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  57864. var material = subMesh.getMaterial();
  57865. if (material.disableDepthWrite) {
  57866. return false;
  57867. }
  57868. var defines = [];
  57869. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57870. var mesh = subMesh.getMesh();
  57871. // Alpha test
  57872. if (material && material.needAlphaTesting()) {
  57873. defines.push("#define ALPHATEST");
  57874. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57875. attribs.push(BABYLON.VertexBuffer.UVKind);
  57876. defines.push("#define UV1");
  57877. }
  57878. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57879. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57880. defines.push("#define UV2");
  57881. }
  57882. }
  57883. // Bones
  57884. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57885. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57886. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57887. if (mesh.numBoneInfluencers > 4) {
  57888. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57889. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57890. }
  57891. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57892. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  57893. }
  57894. else {
  57895. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57896. }
  57897. // Instances
  57898. if (useInstances) {
  57899. defines.push("#define INSTANCES");
  57900. attribs.push("world0");
  57901. attribs.push("world1");
  57902. attribs.push("world2");
  57903. attribs.push("world3");
  57904. }
  57905. // Get correct effect
  57906. var join = defines.join("\n");
  57907. if (this._cachedDefines !== join) {
  57908. this._cachedDefines = join;
  57909. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  57910. }
  57911. return this._effect.isReady();
  57912. };
  57913. DepthRenderer.prototype.getDepthMap = function () {
  57914. return this._depthMap;
  57915. };
  57916. // Methods
  57917. DepthRenderer.prototype.dispose = function () {
  57918. this._depthMap.dispose();
  57919. };
  57920. return DepthRenderer;
  57921. }());
  57922. BABYLON.DepthRenderer = DepthRenderer;
  57923. })(BABYLON || (BABYLON = {}));
  57924. //# sourceMappingURL=babylon.depthRenderer.js.map
  57925. var BABYLON;
  57926. (function (BABYLON) {
  57927. var SSAORenderingPipeline = /** @class */ (function (_super) {
  57928. __extends(SSAORenderingPipeline, _super);
  57929. /**
  57930. * @constructor
  57931. * @param {string} name - The rendering pipeline name
  57932. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57933. * @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 }
  57934. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57935. */
  57936. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  57937. var _this = _super.call(this, scene.getEngine(), name) || this;
  57938. // Members
  57939. /**
  57940. * The PassPostProcess id in the pipeline that contains the original scene color
  57941. * @type {string}
  57942. */
  57943. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57944. /**
  57945. * The SSAO PostProcess id in the pipeline
  57946. * @type {string}
  57947. */
  57948. _this.SSAORenderEffect = "SSAORenderEffect";
  57949. /**
  57950. * The horizontal blur PostProcess id in the pipeline
  57951. * @type {string}
  57952. */
  57953. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57954. /**
  57955. * The vertical blur PostProcess id in the pipeline
  57956. * @type {string}
  57957. */
  57958. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57959. /**
  57960. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57961. * @type {string}
  57962. */
  57963. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57964. /**
  57965. * The output strength of the SSAO post-process. Default value is 1.0.
  57966. * @type {number}
  57967. */
  57968. _this.totalStrength = 1.0;
  57969. /**
  57970. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  57971. * @type {number}
  57972. */
  57973. _this.radius = 0.0001;
  57974. /**
  57975. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  57976. * Must not be equal to fallOff and superior to fallOff.
  57977. * Default value is 0.975
  57978. * @type {number}
  57979. */
  57980. _this.area = 0.0075;
  57981. /**
  57982. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  57983. * Must not be equal to area and inferior to area.
  57984. * Default value is 0.0
  57985. * @type {number}
  57986. */
  57987. _this.fallOff = 0.000001;
  57988. /**
  57989. * The base color of the SSAO post-process
  57990. * The final result is "base + ssao" between [0, 1]
  57991. * @type {number}
  57992. */
  57993. _this.base = 0.5;
  57994. _this._firstUpdate = true;
  57995. _this._scene = scene;
  57996. // Set up assets
  57997. _this._createRandomTexture();
  57998. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57999. var ssaoRatio = ratio.ssaoRatio || ratio;
  58000. var combineRatio = ratio.combineRatio || ratio;
  58001. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  58002. _this._createSSAOPostProcess(ssaoRatio);
  58003. _this._createBlurPostProcess(ssaoRatio);
  58004. _this._createSSAOCombinePostProcess(combineRatio);
  58005. // Set up pipeline
  58006. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  58007. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  58008. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  58009. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  58010. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  58011. // Finish
  58012. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58013. if (cameras)
  58014. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58015. return _this;
  58016. }
  58017. // Public Methods
  58018. /**
  58019. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  58020. */
  58021. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  58022. if (disableDepthRender === void 0) { disableDepthRender = false; }
  58023. for (var i = 0; i < this._scene.cameras.length; i++) {
  58024. var camera = this._scene.cameras[i];
  58025. this._originalColorPostProcess.dispose(camera);
  58026. this._ssaoPostProcess.dispose(camera);
  58027. this._blurHPostProcess.dispose(camera);
  58028. this._blurVPostProcess.dispose(camera);
  58029. this._ssaoCombinePostProcess.dispose(camera);
  58030. }
  58031. this._randomTexture.dispose();
  58032. if (disableDepthRender)
  58033. this._scene.disableDepthRenderer();
  58034. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58035. _super.prototype.dispose.call(this);
  58036. };
  58037. // Private Methods
  58038. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  58039. var _this = this;
  58040. var size = 16;
  58041. 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);
  58042. 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);
  58043. this._blurHPostProcess.onActivateObservable.add(function () {
  58044. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  58045. _this._blurHPostProcess.kernel = size * dw;
  58046. });
  58047. this._blurVPostProcess.onActivateObservable.add(function () {
  58048. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  58049. _this._blurVPostProcess.kernel = size * dw;
  58050. });
  58051. };
  58052. SSAORenderingPipeline.prototype._rebuild = function () {
  58053. this._firstUpdate = true;
  58054. _super.prototype._rebuild.call(this);
  58055. };
  58056. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  58057. var _this = this;
  58058. var numSamples = 16;
  58059. var sampleSphere = [
  58060. 0.5381, 0.1856, -0.4319,
  58061. 0.1379, 0.2486, 0.4430,
  58062. 0.3371, 0.5679, -0.0057,
  58063. -0.6999, -0.0451, -0.0019,
  58064. 0.0689, -0.1598, -0.8547,
  58065. 0.0560, 0.0069, -0.1843,
  58066. -0.0146, 0.1402, 0.0762,
  58067. 0.0100, -0.1924, -0.0344,
  58068. -0.3577, -0.5301, -0.4358,
  58069. -0.3169, 0.1063, 0.0158,
  58070. 0.0103, -0.5869, 0.0046,
  58071. -0.0897, -0.4940, 0.3287,
  58072. 0.7119, -0.0154, -0.0918,
  58073. -0.0533, 0.0596, -0.5411,
  58074. 0.0352, -0.0631, 0.5460,
  58075. -0.4776, 0.2847, -0.0271
  58076. ];
  58077. var samplesFactor = 1.0 / numSamples;
  58078. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  58079. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  58080. "area", "fallOff", "base", "range", "viewport"
  58081. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  58082. this._ssaoPostProcess.onApply = function (effect) {
  58083. if (_this._firstUpdate) {
  58084. effect.setArray3("sampleSphere", sampleSphere);
  58085. effect.setFloat("samplesFactor", samplesFactor);
  58086. effect.setFloat("randTextureTiles", 4.0);
  58087. }
  58088. effect.setFloat("totalStrength", _this.totalStrength);
  58089. effect.setFloat("radius", _this.radius);
  58090. effect.setFloat("area", _this.area);
  58091. effect.setFloat("fallOff", _this.fallOff);
  58092. effect.setFloat("base", _this.base);
  58093. effect.setTexture("textureSampler", _this._depthTexture);
  58094. effect.setTexture("randomSampler", _this._randomTexture);
  58095. };
  58096. };
  58097. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58098. var _this = this;
  58099. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58100. this._ssaoCombinePostProcess.onApply = function (effect) {
  58101. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58102. };
  58103. };
  58104. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  58105. var size = 512;
  58106. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58107. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58108. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58109. var context = this._randomTexture.getContext();
  58110. var rand = function (min, max) {
  58111. return Math.random() * (max - min) + min;
  58112. };
  58113. var randVector = BABYLON.Vector3.Zero();
  58114. for (var x = 0; x < size; x++) {
  58115. for (var y = 0; y < size; y++) {
  58116. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  58117. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  58118. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  58119. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  58120. context.fillRect(x, y, 1, 1);
  58121. }
  58122. }
  58123. this._randomTexture.update(false);
  58124. };
  58125. __decorate([
  58126. BABYLON.serialize()
  58127. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  58128. __decorate([
  58129. BABYLON.serialize()
  58130. ], SSAORenderingPipeline.prototype, "radius", void 0);
  58131. __decorate([
  58132. BABYLON.serialize()
  58133. ], SSAORenderingPipeline.prototype, "area", void 0);
  58134. __decorate([
  58135. BABYLON.serialize()
  58136. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  58137. __decorate([
  58138. BABYLON.serialize()
  58139. ], SSAORenderingPipeline.prototype, "base", void 0);
  58140. return SSAORenderingPipeline;
  58141. }(BABYLON.PostProcessRenderPipeline));
  58142. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  58143. })(BABYLON || (BABYLON = {}));
  58144. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  58145. var BABYLON;
  58146. (function (BABYLON) {
  58147. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  58148. __extends(SSAO2RenderingPipeline, _super);
  58149. /**
  58150. * @constructor
  58151. * @param {string} name - The rendering pipeline name
  58152. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58153. * @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 }
  58154. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58155. */
  58156. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  58157. var _this = _super.call(this, scene.getEngine(), name) || this;
  58158. // Members
  58159. /**
  58160. * The PassPostProcess id in the pipeline that contains the original scene color
  58161. * @type {string}
  58162. */
  58163. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  58164. /**
  58165. * The SSAO PostProcess id in the pipeline
  58166. * @type {string}
  58167. */
  58168. _this.SSAORenderEffect = "SSAORenderEffect";
  58169. /**
  58170. * The horizontal blur PostProcess id in the pipeline
  58171. * @type {string}
  58172. */
  58173. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  58174. /**
  58175. * The vertical blur PostProcess id in the pipeline
  58176. * @type {string}
  58177. */
  58178. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  58179. /**
  58180. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  58181. * @type {string}
  58182. */
  58183. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  58184. /**
  58185. * The output strength of the SSAO post-process. Default value is 1.0.
  58186. * @type {number}
  58187. */
  58188. _this.totalStrength = 1.0;
  58189. /**
  58190. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  58191. * @type {number}
  58192. */
  58193. _this.maxZ = 100.0;
  58194. /**
  58195. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  58196. * @type {number}
  58197. */
  58198. _this.minZAspect = 0.2;
  58199. /**
  58200. * Number of samples used for the SSAO calculations. Default value is 8
  58201. * @type {number}
  58202. */
  58203. _this._samples = 8;
  58204. /**
  58205. * Are we using bilateral blur ?
  58206. * @type {boolean}
  58207. */
  58208. _this._expensiveBlur = true;
  58209. /**
  58210. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  58211. * @type {number}
  58212. */
  58213. _this.radius = 2.0;
  58214. /**
  58215. * The base color of the SSAO post-process
  58216. * The final result is "base + ssao" between [0, 1]
  58217. * @type {number}
  58218. */
  58219. _this.base = 0.1;
  58220. _this._firstUpdate = true;
  58221. _this._scene = scene;
  58222. if (!_this.isSupported) {
  58223. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  58224. return _this;
  58225. }
  58226. var ssaoRatio = ratio.ssaoRatio || ratio;
  58227. var blurRatio = ratio.blurRatio || ratio;
  58228. // Set up assets
  58229. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  58230. _this._createRandomTexture();
  58231. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  58232. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  58233. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  58234. _this._createSSAOPostProcess(1.0);
  58235. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  58236. _this._createSSAOCombinePostProcess(blurRatio);
  58237. // Set up pipeline
  58238. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  58239. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  58240. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  58241. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  58242. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  58243. // Finish
  58244. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58245. if (cameras)
  58246. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58247. return _this;
  58248. }
  58249. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  58250. get: function () {
  58251. return this._samples;
  58252. },
  58253. set: function (n) {
  58254. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  58255. this._samples = n;
  58256. this._sampleSphere = this._generateHemisphere();
  58257. this._firstUpdate = true;
  58258. },
  58259. enumerable: true,
  58260. configurable: true
  58261. });
  58262. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  58263. get: function () {
  58264. return this._expensiveBlur;
  58265. },
  58266. set: function (b) {
  58267. 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"]);
  58268. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  58269. this._expensiveBlur = b;
  58270. this._firstUpdate = true;
  58271. },
  58272. enumerable: true,
  58273. configurable: true
  58274. });
  58275. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  58276. /**
  58277. * Support test.
  58278. * @type {boolean}
  58279. */
  58280. get: function () {
  58281. var engine = BABYLON.Engine.LastCreatedEngine;
  58282. if (!engine) {
  58283. return false;
  58284. }
  58285. return engine.getCaps().drawBuffersExtension;
  58286. },
  58287. enumerable: true,
  58288. configurable: true
  58289. });
  58290. // Public Methods
  58291. /**
  58292. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  58293. */
  58294. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  58295. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  58296. for (var i = 0; i < this._scene.cameras.length; i++) {
  58297. var camera = this._scene.cameras[i];
  58298. this._originalColorPostProcess.dispose(camera);
  58299. this._ssaoPostProcess.dispose(camera);
  58300. this._blurHPostProcess.dispose(camera);
  58301. this._blurVPostProcess.dispose(camera);
  58302. this._ssaoCombinePostProcess.dispose(camera);
  58303. }
  58304. this._randomTexture.dispose();
  58305. if (disableGeometryBufferRenderer)
  58306. this._scene.disableGeometryBufferRenderer();
  58307. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58308. _super.prototype.dispose.call(this);
  58309. };
  58310. // Private Methods
  58311. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  58312. var _this = this;
  58313. this._samplerOffsets = [];
  58314. var expensive = this.expensiveBlur;
  58315. for (var i = -8; i < 8; i++) {
  58316. this._samplerOffsets.push(i * 2 + 0.5);
  58317. }
  58318. 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");
  58319. this._blurHPostProcess.onApply = function (effect) {
  58320. if (!_this._scene.activeCamera) {
  58321. return;
  58322. }
  58323. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  58324. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58325. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58326. effect.setFloat("radius", _this.radius);
  58327. effect.setTexture("depthSampler", _this._depthTexture);
  58328. if (_this._firstUpdate) {
  58329. effect.setArray("samplerOffsets", _this._samplerOffsets);
  58330. }
  58331. };
  58332. 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");
  58333. this._blurVPostProcess.onApply = function (effect) {
  58334. if (!_this._scene.activeCamera) {
  58335. return;
  58336. }
  58337. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  58338. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58339. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58340. effect.setFloat("radius", _this.radius);
  58341. effect.setTexture("depthSampler", _this._depthTexture);
  58342. if (_this._firstUpdate) {
  58343. effect.setArray("samplerOffsets", _this._samplerOffsets);
  58344. _this._firstUpdate = false;
  58345. }
  58346. };
  58347. };
  58348. SSAO2RenderingPipeline.prototype._rebuild = function () {
  58349. this._firstUpdate = true;
  58350. _super.prototype._rebuild.call(this);
  58351. };
  58352. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  58353. var numSamples = this.samples;
  58354. var result = [];
  58355. var vector, scale;
  58356. var rand = function (min, max) {
  58357. return Math.random() * (max - min) + min;
  58358. };
  58359. var i = 0;
  58360. while (i < numSamples) {
  58361. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  58362. vector.normalize();
  58363. scale = i / numSamples;
  58364. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  58365. vector.scaleInPlace(scale);
  58366. result.push(vector.x, vector.y, vector.z);
  58367. i++;
  58368. }
  58369. return result;
  58370. };
  58371. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  58372. var _this = this;
  58373. var numSamples = this.samples;
  58374. this._sampleSphere = this._generateHemisphere();
  58375. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  58376. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  58377. "base", "range", "projection", "near", "far", "texelSize",
  58378. "xViewport", "yViewport", "maxZ", "minZAspect"
  58379. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  58380. this._ssaoPostProcess.onApply = function (effect) {
  58381. if (_this._firstUpdate) {
  58382. effect.setArray3("sampleSphere", _this._sampleSphere);
  58383. effect.setFloat("randTextureTiles", 4.0);
  58384. }
  58385. if (!_this._scene.activeCamera) {
  58386. return;
  58387. }
  58388. effect.setFloat("samplesFactor", 1 / _this.samples);
  58389. effect.setFloat("totalStrength", _this.totalStrength);
  58390. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  58391. effect.setFloat("radius", _this.radius);
  58392. effect.setFloat("maxZ", _this.maxZ);
  58393. effect.setFloat("minZAspect", _this.minZAspect);
  58394. effect.setFloat("base", _this.base);
  58395. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58396. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58397. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  58398. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  58399. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  58400. effect.setTexture("textureSampler", _this._depthTexture);
  58401. effect.setTexture("normalSampler", _this._normalTexture);
  58402. effect.setTexture("randomSampler", _this._randomTexture);
  58403. };
  58404. };
  58405. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58406. var _this = this;
  58407. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58408. this._ssaoCombinePostProcess.onApply = function (effect) {
  58409. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58410. };
  58411. };
  58412. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  58413. var size = 512;
  58414. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58415. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58416. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58417. var context = this._randomTexture.getContext();
  58418. var rand = function (min, max) {
  58419. return Math.random() * (max - min) + min;
  58420. };
  58421. var randVector = BABYLON.Vector3.Zero();
  58422. for (var x = 0; x < size; x++) {
  58423. for (var y = 0; y < size; y++) {
  58424. randVector.x = rand(0.0, 1.0);
  58425. randVector.y = rand(0.0, 1.0);
  58426. randVector.z = 0.0;
  58427. randVector.normalize();
  58428. randVector.scaleInPlace(255);
  58429. randVector.x = Math.floor(randVector.x);
  58430. randVector.y = Math.floor(randVector.y);
  58431. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  58432. context.fillRect(x, y, 1, 1);
  58433. }
  58434. }
  58435. this._randomTexture.update(false);
  58436. };
  58437. __decorate([
  58438. BABYLON.serialize()
  58439. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  58440. __decorate([
  58441. BABYLON.serialize()
  58442. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  58443. __decorate([
  58444. BABYLON.serialize()
  58445. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  58446. __decorate([
  58447. BABYLON.serialize("samples")
  58448. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  58449. __decorate([
  58450. BABYLON.serialize("expensiveBlur")
  58451. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  58452. __decorate([
  58453. BABYLON.serialize()
  58454. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  58455. __decorate([
  58456. BABYLON.serialize()
  58457. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  58458. return SSAO2RenderingPipeline;
  58459. }(BABYLON.PostProcessRenderPipeline));
  58460. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  58461. })(BABYLON || (BABYLON = {}));
  58462. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  58463. // BABYLON.JS Chromatic Aberration GLSL Shader
  58464. // Author: Olivier Guyot
  58465. // Separates very slightly R, G and B colors on the edges of the screen
  58466. // Inspired by Francois Tarlier & Martins Upitis
  58467. var BABYLON;
  58468. (function (BABYLON) {
  58469. var LensRenderingPipeline = /** @class */ (function (_super) {
  58470. __extends(LensRenderingPipeline, _super);
  58471. /**
  58472. * @constructor
  58473. *
  58474. * Effect parameters are as follow:
  58475. * {
  58476. * chromatic_aberration: number; // from 0 to x (1 for realism)
  58477. * edge_blur: number; // from 0 to x (1 for realism)
  58478. * distortion: number; // from 0 to x (1 for realism)
  58479. * grain_amount: number; // from 0 to 1
  58480. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  58481. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  58482. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  58483. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  58484. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  58485. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  58486. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  58487. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  58488. * }
  58489. * Note: if an effect parameter is unset, effect is disabled
  58490. *
  58491. * @param {string} name - The rendering pipeline name
  58492. * @param {object} parameters - An object containing all parameters (see above)
  58493. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58494. * @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)
  58495. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58496. */
  58497. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  58498. if (ratio === void 0) { ratio = 1.0; }
  58499. var _this = _super.call(this, scene.getEngine(), name) || this;
  58500. // Lens effects can be of the following:
  58501. // - chromatic aberration (slight shift of RGB colors)
  58502. // - blur on the edge of the lens
  58503. // - lens distortion
  58504. // - depth-of-field blur & highlights enhancing
  58505. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  58506. // - grain effect (noise or custom texture)
  58507. // Two additional texture samplers are needed:
  58508. // - depth map (for depth-of-field)
  58509. // - grain texture
  58510. /**
  58511. * The chromatic aberration PostProcess id in the pipeline
  58512. * @type {string}
  58513. */
  58514. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  58515. /**
  58516. * The highlights enhancing PostProcess id in the pipeline
  58517. * @type {string}
  58518. */
  58519. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  58520. /**
  58521. * The depth-of-field PostProcess id in the pipeline
  58522. * @type {string}
  58523. */
  58524. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  58525. _this._scene = scene;
  58526. // Fetch texture samplers
  58527. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  58528. if (parameters.grain_texture) {
  58529. _this._grainTexture = parameters.grain_texture;
  58530. }
  58531. else {
  58532. _this._createGrainTexture();
  58533. }
  58534. // save parameters
  58535. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  58536. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  58537. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  58538. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  58539. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  58540. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  58541. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  58542. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  58543. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  58544. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  58545. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  58546. // Create effects
  58547. _this._createChromaticAberrationPostProcess(ratio);
  58548. _this._createHighlightsPostProcess(ratio);
  58549. _this._createDepthOfFieldPostProcess(ratio / 4);
  58550. // Set up pipeline
  58551. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  58552. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  58553. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  58554. if (_this._highlightsGain === -1) {
  58555. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  58556. }
  58557. // Finish
  58558. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58559. if (cameras) {
  58560. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58561. }
  58562. return _this;
  58563. }
  58564. // public methods (self explanatory)
  58565. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  58566. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  58567. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  58568. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  58569. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  58570. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  58571. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  58572. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  58573. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  58574. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  58575. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  58576. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  58577. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  58578. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  58579. };
  58580. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  58581. this._highlightsPostProcess.updateEffect();
  58582. };
  58583. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  58584. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  58585. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  58586. this._highlightsGain = amount;
  58587. };
  58588. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  58589. if (this._highlightsGain === -1) {
  58590. this._highlightsGain = 1.0;
  58591. }
  58592. this._highlightsThreshold = amount;
  58593. };
  58594. LensRenderingPipeline.prototype.disableHighlights = function () {
  58595. this._highlightsGain = -1;
  58596. };
  58597. /**
  58598. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  58599. */
  58600. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  58601. if (disableDepthRender === void 0) { disableDepthRender = false; }
  58602. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58603. this._chromaticAberrationPostProcess = null;
  58604. this._highlightsPostProcess = null;
  58605. this._depthOfFieldPostProcess = null;
  58606. this._grainTexture.dispose();
  58607. if (disableDepthRender)
  58608. this._scene.disableDepthRenderer();
  58609. };
  58610. // colors shifting and distortion
  58611. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  58612. var _this = this;
  58613. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  58614. [], // samplers
  58615. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58616. this._chromaticAberrationPostProcess.onApply = function (effect) {
  58617. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  58618. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58619. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58620. };
  58621. };
  58622. // highlights enhancing
  58623. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  58624. var _this = this;
  58625. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  58626. [], // samplers
  58627. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  58628. this._highlightsPostProcess.onApply = function (effect) {
  58629. effect.setFloat('gain', _this._highlightsGain);
  58630. effect.setFloat('threshold', _this._highlightsThreshold);
  58631. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  58632. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58633. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58634. };
  58635. };
  58636. // colors shifting and distortion
  58637. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  58638. var _this = this;
  58639. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  58640. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  58641. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  58642. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58643. this._depthOfFieldPostProcess.onApply = function (effect) {
  58644. effect.setTexture("depthSampler", _this._depthTexture);
  58645. effect.setTexture("grainSampler", _this._grainTexture);
  58646. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  58647. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  58648. effect.setFloat('grain_amount', _this._grainAmount);
  58649. effect.setBool('blur_noise', _this._blurNoise);
  58650. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58651. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58652. effect.setFloat('distortion', _this._distortion);
  58653. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  58654. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  58655. effect.setFloat('aperture', _this._dofAperture);
  58656. effect.setFloat('darken', _this._dofDarken);
  58657. effect.setFloat('edge_blur', _this._edgeBlur);
  58658. effect.setBool('highlights', (_this._highlightsGain !== -1));
  58659. if (_this._scene.activeCamera) {
  58660. effect.setFloat('near', _this._scene.activeCamera.minZ);
  58661. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  58662. }
  58663. };
  58664. };
  58665. // creates a black and white random noise texture, 512x512
  58666. LensRenderingPipeline.prototype._createGrainTexture = function () {
  58667. var size = 512;
  58668. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58669. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58670. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58671. var context = this._grainTexture.getContext();
  58672. var rand = function (min, max) {
  58673. return Math.random() * (max - min) + min;
  58674. };
  58675. var value;
  58676. for (var x = 0; x < size; x++) {
  58677. for (var y = 0; y < size; y++) {
  58678. value = Math.floor(rand(0.42, 0.58) * 255);
  58679. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  58680. context.fillRect(x, y, 1, 1);
  58681. }
  58682. }
  58683. this._grainTexture.update(false);
  58684. };
  58685. return LensRenderingPipeline;
  58686. }(BABYLON.PostProcessRenderPipeline));
  58687. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  58688. })(BABYLON || (BABYLON = {}));
  58689. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  58690. var BABYLON;
  58691. (function (BABYLON) {
  58692. var StandardRenderingPipeline = /** @class */ (function (_super) {
  58693. __extends(StandardRenderingPipeline, _super);
  58694. /**
  58695. * @constructor
  58696. * @param {string} name - The rendering pipeline name
  58697. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58698. * @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)
  58699. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  58700. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58701. */
  58702. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  58703. if (originalPostProcess === void 0) { originalPostProcess = null; }
  58704. var _this = _super.call(this, scene.getEngine(), name) || this;
  58705. _this.downSampleX4PostProcess = null;
  58706. _this.brightPassPostProcess = null;
  58707. _this.blurHPostProcesses = [];
  58708. _this.blurVPostProcesses = [];
  58709. _this.textureAdderPostProcess = null;
  58710. _this.volumetricLightPostProcess = null;
  58711. _this.volumetricLightSmoothXPostProcess = null;
  58712. _this.volumetricLightSmoothYPostProcess = null;
  58713. _this.volumetricLightMergePostProces = null;
  58714. _this.volumetricLightFinalPostProcess = null;
  58715. _this.luminancePostProcess = null;
  58716. _this.luminanceDownSamplePostProcesses = [];
  58717. _this.hdrPostProcess = null;
  58718. _this.textureAdderFinalPostProcess = null;
  58719. _this.lensFlareFinalPostProcess = null;
  58720. _this.hdrFinalPostProcess = null;
  58721. _this.lensFlarePostProcess = null;
  58722. _this.lensFlareComposePostProcess = null;
  58723. _this.motionBlurPostProcess = null;
  58724. _this.depthOfFieldPostProcess = null;
  58725. // Values
  58726. _this.brightThreshold = 1.0;
  58727. _this.blurWidth = 512.0;
  58728. _this.horizontalBlur = false;
  58729. _this.exposure = 1.0;
  58730. _this.lensTexture = null;
  58731. _this.volumetricLightCoefficient = 0.2;
  58732. _this.volumetricLightPower = 4.0;
  58733. _this.volumetricLightBlurScale = 64.0;
  58734. _this.sourceLight = null;
  58735. _this.hdrMinimumLuminance = 1.0;
  58736. _this.hdrDecreaseRate = 0.5;
  58737. _this.hdrIncreaseRate = 0.5;
  58738. _this.lensColorTexture = null;
  58739. _this.lensFlareStrength = 20.0;
  58740. _this.lensFlareGhostDispersal = 1.4;
  58741. _this.lensFlareHaloWidth = 0.7;
  58742. _this.lensFlareDistortionStrength = 16.0;
  58743. _this.lensStarTexture = null;
  58744. _this.lensFlareDirtTexture = null;
  58745. _this.depthOfFieldDistance = 10.0;
  58746. _this.depthOfFieldBlurWidth = 64.0;
  58747. _this.motionStrength = 1.0;
  58748. // IAnimatable
  58749. _this.animations = [];
  58750. _this._currentDepthOfFieldSource = null;
  58751. _this._hdrCurrentLuminance = 1.0;
  58752. // Getters and setters
  58753. _this._bloomEnabled = true;
  58754. _this._depthOfFieldEnabled = false;
  58755. _this._vlsEnabled = false;
  58756. _this._lensFlareEnabled = false;
  58757. _this._hdrEnabled = false;
  58758. _this._motionBlurEnabled = false;
  58759. _this._motionBlurSamples = 64.0;
  58760. _this._volumetricLightStepsCount = 50.0;
  58761. _this._cameras = cameras || [];
  58762. // Initialize
  58763. _this._scene = scene;
  58764. _this._basePostProcess = originalPostProcess;
  58765. _this._ratio = ratio;
  58766. // Misc
  58767. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58768. // Finish
  58769. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58770. _this._buildPipeline();
  58771. return _this;
  58772. }
  58773. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  58774. get: function () {
  58775. return this._bloomEnabled;
  58776. },
  58777. set: function (enabled) {
  58778. if (this._bloomEnabled === enabled) {
  58779. return;
  58780. }
  58781. this._bloomEnabled = enabled;
  58782. this._buildPipeline();
  58783. },
  58784. enumerable: true,
  58785. configurable: true
  58786. });
  58787. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  58788. get: function () {
  58789. return this._depthOfFieldEnabled;
  58790. },
  58791. set: function (enabled) {
  58792. if (this._depthOfFieldEnabled === enabled) {
  58793. return;
  58794. }
  58795. this._depthOfFieldEnabled = enabled;
  58796. this._buildPipeline();
  58797. },
  58798. enumerable: true,
  58799. configurable: true
  58800. });
  58801. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  58802. get: function () {
  58803. return this._lensFlareEnabled;
  58804. },
  58805. set: function (enabled) {
  58806. if (this._lensFlareEnabled === enabled) {
  58807. return;
  58808. }
  58809. this._lensFlareEnabled = enabled;
  58810. this._buildPipeline();
  58811. },
  58812. enumerable: true,
  58813. configurable: true
  58814. });
  58815. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  58816. get: function () {
  58817. return this._hdrEnabled;
  58818. },
  58819. set: function (enabled) {
  58820. if (this._hdrEnabled === enabled) {
  58821. return;
  58822. }
  58823. this._hdrEnabled = enabled;
  58824. this._buildPipeline();
  58825. },
  58826. enumerable: true,
  58827. configurable: true
  58828. });
  58829. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  58830. get: function () {
  58831. return this._vlsEnabled;
  58832. },
  58833. set: function (enabled) {
  58834. if (this._vlsEnabled === enabled) {
  58835. return;
  58836. }
  58837. if (enabled) {
  58838. var geometry = this._scene.enableGeometryBufferRenderer();
  58839. if (!geometry) {
  58840. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  58841. return;
  58842. }
  58843. }
  58844. this._vlsEnabled = enabled;
  58845. this._buildPipeline();
  58846. },
  58847. enumerable: true,
  58848. configurable: true
  58849. });
  58850. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  58851. get: function () {
  58852. return this._motionBlurEnabled;
  58853. },
  58854. set: function (enabled) {
  58855. if (this._motionBlurEnabled === enabled) {
  58856. return;
  58857. }
  58858. this._motionBlurEnabled = enabled;
  58859. this._buildPipeline();
  58860. },
  58861. enumerable: true,
  58862. configurable: true
  58863. });
  58864. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  58865. get: function () {
  58866. return this._volumetricLightStepsCount;
  58867. },
  58868. set: function (count) {
  58869. if (this.volumetricLightPostProcess) {
  58870. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  58871. }
  58872. this._volumetricLightStepsCount = count;
  58873. },
  58874. enumerable: true,
  58875. configurable: true
  58876. });
  58877. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  58878. get: function () {
  58879. return this._motionBlurSamples;
  58880. },
  58881. set: function (samples) {
  58882. if (this.motionBlurPostProcess) {
  58883. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  58884. }
  58885. this._motionBlurSamples = samples;
  58886. },
  58887. enumerable: true,
  58888. configurable: true
  58889. });
  58890. StandardRenderingPipeline.prototype._buildPipeline = function () {
  58891. var _this = this;
  58892. var ratio = this._ratio;
  58893. var scene = this._scene;
  58894. this._disposePostProcesses();
  58895. this._reset();
  58896. // Create pass post-process
  58897. if (!this._basePostProcess) {
  58898. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  58899. this.originalPostProcess.onApply = function (effect) {
  58900. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  58901. };
  58902. }
  58903. else {
  58904. this.originalPostProcess = this._basePostProcess;
  58905. }
  58906. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  58907. this._currentDepthOfFieldSource = this.originalPostProcess;
  58908. if (this._vlsEnabled) {
  58909. // Create volumetric light
  58910. this._createVolumetricLightPostProcess(scene, ratio);
  58911. // Create volumetric light final post-process
  58912. 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);
  58913. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  58914. }
  58915. if (this._bloomEnabled) {
  58916. // Create down sample X4 post-process
  58917. this._createDownSampleX4PostProcess(scene, ratio / 2);
  58918. // Create bright pass post-process
  58919. this._createBrightPassPostProcess(scene, ratio / 2);
  58920. // Create gaussian blur post-processes (down sampling blurs)
  58921. this._createBlurPostProcesses(scene, ratio / 4, 1);
  58922. // Create texture adder post-process
  58923. this._createTextureAdderPostProcess(scene, ratio);
  58924. // Create depth-of-field source post-process
  58925. 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);
  58926. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  58927. }
  58928. if (this._lensFlareEnabled) {
  58929. // Create lens flare post-process
  58930. this._createLensFlarePostProcess(scene, ratio);
  58931. // Create depth-of-field source post-process post lens-flare and disable it now
  58932. 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);
  58933. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  58934. }
  58935. if (this._hdrEnabled) {
  58936. // Create luminance
  58937. this._createLuminancePostProcesses(scene, this._floatTextureType);
  58938. // Create HDR
  58939. this._createHdrPostProcess(scene, ratio);
  58940. // Create depth-of-field source post-process post hdr and disable it now
  58941. 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);
  58942. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  58943. }
  58944. if (this._depthOfFieldEnabled) {
  58945. // Create gaussian blur used by depth-of-field
  58946. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  58947. // Create depth-of-field post-process
  58948. this._createDepthOfFieldPostProcess(scene, ratio);
  58949. }
  58950. if (this._motionBlurEnabled) {
  58951. // Create motion blur post-process
  58952. this._createMotionBlurPostProcess(scene, ratio);
  58953. }
  58954. if (this._cameras !== null) {
  58955. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58956. }
  58957. };
  58958. // Down Sample X4 Post-Processs
  58959. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  58960. var _this = this;
  58961. var downSampleX4Offsets = new Array(32);
  58962. 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);
  58963. this.downSampleX4PostProcess.onApply = function (effect) {
  58964. var id = 0;
  58965. var width = _this.downSampleX4PostProcess.width;
  58966. var height = _this.downSampleX4PostProcess.height;
  58967. for (var i = -2; i < 2; i++) {
  58968. for (var j = -2; j < 2; j++) {
  58969. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  58970. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  58971. id += 2;
  58972. }
  58973. }
  58974. effect.setArray2("dsOffsets", downSampleX4Offsets);
  58975. };
  58976. // Add to pipeline
  58977. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  58978. };
  58979. // Brightpass Post-Process
  58980. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  58981. var _this = this;
  58982. var brightOffsets = new Array(8);
  58983. 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);
  58984. this.brightPassPostProcess.onApply = function (effect) {
  58985. var sU = (1.0 / _this.brightPassPostProcess.width);
  58986. var sV = (1.0 / _this.brightPassPostProcess.height);
  58987. brightOffsets[0] = -0.5 * sU;
  58988. brightOffsets[1] = 0.5 * sV;
  58989. brightOffsets[2] = 0.5 * sU;
  58990. brightOffsets[3] = 0.5 * sV;
  58991. brightOffsets[4] = -0.5 * sU;
  58992. brightOffsets[5] = -0.5 * sV;
  58993. brightOffsets[6] = 0.5 * sU;
  58994. brightOffsets[7] = -0.5 * sV;
  58995. effect.setArray2("dsOffsets", brightOffsets);
  58996. effect.setFloat("brightThreshold", _this.brightThreshold);
  58997. };
  58998. // Add to pipeline
  58999. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  59000. };
  59001. // Create blur H&V post-processes
  59002. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  59003. var _this = this;
  59004. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  59005. var engine = scene.getEngine();
  59006. 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);
  59007. 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);
  59008. blurX.onActivateObservable.add(function () {
  59009. var dw = blurX.width / engine.getRenderWidth();
  59010. blurX.kernel = _this[blurWidthKey] * dw;
  59011. });
  59012. blurY.onActivateObservable.add(function () {
  59013. var dw = blurY.height / engine.getRenderHeight();
  59014. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  59015. });
  59016. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  59017. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  59018. this.blurHPostProcesses.push(blurX);
  59019. this.blurVPostProcesses.push(blurY);
  59020. };
  59021. // Create texture adder post-process
  59022. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  59023. var _this = this;
  59024. 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);
  59025. this.textureAdderPostProcess.onApply = function (effect) {
  59026. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  59027. effect.setTexture("lensSampler", _this.lensTexture);
  59028. effect.setFloat("exposure", _this.exposure);
  59029. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  59030. };
  59031. // Add to pipeline
  59032. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  59033. };
  59034. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  59035. var _this = this;
  59036. var geometryRenderer = scene.enableGeometryBufferRenderer();
  59037. geometryRenderer.enablePosition = true;
  59038. var geometry = geometryRenderer.getGBuffer();
  59039. // Base post-process
  59040. 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));
  59041. var depthValues = BABYLON.Vector2.Zero();
  59042. this.volumetricLightPostProcess.onApply = function (effect) {
  59043. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  59044. var generator = _this.sourceLight.getShadowGenerator();
  59045. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  59046. effect.setTexture("positionSampler", geometry.textures[2]);
  59047. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  59048. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  59049. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  59050. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  59051. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  59052. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  59053. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  59054. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  59055. effect.setVector2("depthValues", depthValues);
  59056. }
  59057. };
  59058. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  59059. // Smooth
  59060. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  59061. // Merge
  59062. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  59063. this.volumetricLightMergePostProces.onApply = function (effect) {
  59064. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  59065. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  59066. };
  59067. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  59068. };
  59069. // Create luminance
  59070. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  59071. var _this = this;
  59072. // Create luminance
  59073. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  59074. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  59075. var offsets = [];
  59076. this.luminancePostProcess.onApply = function (effect) {
  59077. var sU = (1.0 / _this.luminancePostProcess.width);
  59078. var sV = (1.0 / _this.luminancePostProcess.height);
  59079. offsets[0] = -0.5 * sU;
  59080. offsets[1] = 0.5 * sV;
  59081. offsets[2] = 0.5 * sU;
  59082. offsets[3] = 0.5 * sV;
  59083. offsets[4] = -0.5 * sU;
  59084. offsets[5] = -0.5 * sV;
  59085. offsets[6] = 0.5 * sU;
  59086. offsets[7] = -0.5 * sV;
  59087. effect.setArray2("lumOffsets", offsets);
  59088. };
  59089. // Add to pipeline
  59090. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  59091. // Create down sample luminance
  59092. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  59093. var size = Math.pow(3, i);
  59094. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  59095. if (i === 0) {
  59096. defines += "#define FINAL_DOWN_SAMPLER";
  59097. }
  59098. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  59099. this.luminanceDownSamplePostProcesses.push(postProcess);
  59100. }
  59101. // Create callbacks and add effects
  59102. var lastLuminance = this.luminancePostProcess;
  59103. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  59104. var downSampleOffsets = new Array(18);
  59105. pp.onApply = function (effect) {
  59106. if (!lastLuminance) {
  59107. return;
  59108. }
  59109. var id = 0;
  59110. for (var x = -1; x < 2; x++) {
  59111. for (var y = -1; y < 2; y++) {
  59112. downSampleOffsets[id] = x / lastLuminance.width;
  59113. downSampleOffsets[id + 1] = y / lastLuminance.height;
  59114. id += 2;
  59115. }
  59116. }
  59117. effect.setArray2("dsOffsets", downSampleOffsets);
  59118. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  59119. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59120. lastLuminance = _this.luminancePostProcess;
  59121. }
  59122. else {
  59123. lastLuminance = pp;
  59124. }
  59125. };
  59126. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59127. pp.onAfterRender = function (effect) {
  59128. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  59129. 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);
  59130. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  59131. };
  59132. }
  59133. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  59134. });
  59135. };
  59136. // Create HDR post-process
  59137. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  59138. var _this = this;
  59139. 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);
  59140. var outputLiminance = 1;
  59141. var time = 0;
  59142. var lastTime = 0;
  59143. this.hdrPostProcess.onApply = function (effect) {
  59144. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  59145. time += scene.getEngine().getDeltaTime();
  59146. if (outputLiminance < 0) {
  59147. outputLiminance = _this._hdrCurrentLuminance;
  59148. }
  59149. else {
  59150. var dt = (lastTime - time) / 1000.0;
  59151. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  59152. outputLiminance += _this.hdrDecreaseRate * dt;
  59153. }
  59154. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  59155. outputLiminance -= _this.hdrIncreaseRate * dt;
  59156. }
  59157. else {
  59158. outputLiminance = _this._hdrCurrentLuminance;
  59159. }
  59160. }
  59161. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  59162. effect.setFloat("averageLuminance", outputLiminance);
  59163. lastTime = time;
  59164. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  59165. };
  59166. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  59167. };
  59168. // Create lens flare post-process
  59169. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  59170. var _this = this;
  59171. 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);
  59172. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  59173. this._createBlurPostProcesses(scene, ratio / 4, 2);
  59174. 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);
  59175. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  59176. var resolution = new BABYLON.Vector2(0, 0);
  59177. // Lens flare
  59178. this.lensFlarePostProcess.onApply = function (effect) {
  59179. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  59180. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  59181. effect.setFloat("strength", _this.lensFlareStrength);
  59182. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  59183. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  59184. // Shift
  59185. resolution.x = _this.lensFlarePostProcess.width;
  59186. resolution.y = _this.lensFlarePostProcess.height;
  59187. effect.setVector2("resolution", resolution);
  59188. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  59189. };
  59190. // Compose
  59191. 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);
  59192. 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);
  59193. this.lensFlareComposePostProcess.onApply = function (effect) {
  59194. if (!_this._scene.activeCamera) {
  59195. return;
  59196. }
  59197. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59198. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  59199. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  59200. // Lens start rotation matrix
  59201. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  59202. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  59203. 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));
  59204. camRot *= 4.0;
  59205. 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);
  59206. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  59207. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  59208. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  59209. };
  59210. };
  59211. // Create depth-of-field post-process
  59212. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  59213. var _this = this;
  59214. 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);
  59215. this.depthOfFieldPostProcess.onApply = function (effect) {
  59216. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59217. effect.setTexture("depthSampler", _this._getDepthTexture());
  59218. effect.setFloat("distance", _this.depthOfFieldDistance);
  59219. };
  59220. // Add to pipeline
  59221. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  59222. };
  59223. // Create motion blur post-process
  59224. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  59225. var _this = this;
  59226. 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);
  59227. var motionScale = 0;
  59228. var prevViewProjection = BABYLON.Matrix.Identity();
  59229. var invViewProjection = BABYLON.Matrix.Identity();
  59230. var viewProjection = BABYLON.Matrix.Identity();
  59231. var screenSize = BABYLON.Vector2.Zero();
  59232. this.motionBlurPostProcess.onApply = function (effect) {
  59233. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  59234. viewProjection.invertToRef(invViewProjection);
  59235. effect.setMatrix("inverseViewProjection", invViewProjection);
  59236. effect.setMatrix("prevViewProjection", prevViewProjection);
  59237. prevViewProjection = viewProjection;
  59238. screenSize.x = _this.motionBlurPostProcess.width;
  59239. screenSize.y = _this.motionBlurPostProcess.height;
  59240. effect.setVector2("screenSize", screenSize);
  59241. motionScale = scene.getEngine().getFps() / 60.0;
  59242. effect.setFloat("motionScale", motionScale);
  59243. effect.setFloat("motionStrength", _this.motionStrength);
  59244. effect.setTexture("depthSampler", _this._getDepthTexture());
  59245. };
  59246. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  59247. };
  59248. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  59249. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  59250. var renderer = this._scene.enableGeometryBufferRenderer();
  59251. return renderer.getGBuffer().textures[0];
  59252. }
  59253. return this._scene.enableDepthRenderer().getDepthMap();
  59254. };
  59255. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  59256. for (var i = 0; i < this._cameras.length; i++) {
  59257. var camera = this._cameras[i];
  59258. if (this.originalPostProcess) {
  59259. this.originalPostProcess.dispose(camera);
  59260. }
  59261. if (this.downSampleX4PostProcess) {
  59262. this.downSampleX4PostProcess.dispose(camera);
  59263. }
  59264. if (this.brightPassPostProcess) {
  59265. this.brightPassPostProcess.dispose(camera);
  59266. }
  59267. if (this.textureAdderPostProcess) {
  59268. this.textureAdderPostProcess.dispose(camera);
  59269. }
  59270. if (this.textureAdderFinalPostProcess) {
  59271. this.textureAdderFinalPostProcess.dispose(camera);
  59272. }
  59273. if (this.volumetricLightPostProcess) {
  59274. this.volumetricLightPostProcess.dispose(camera);
  59275. }
  59276. if (this.volumetricLightSmoothXPostProcess) {
  59277. this.volumetricLightSmoothXPostProcess.dispose(camera);
  59278. }
  59279. if (this.volumetricLightSmoothYPostProcess) {
  59280. this.volumetricLightSmoothYPostProcess.dispose(camera);
  59281. }
  59282. if (this.volumetricLightMergePostProces) {
  59283. this.volumetricLightMergePostProces.dispose(camera);
  59284. }
  59285. if (this.volumetricLightFinalPostProcess) {
  59286. this.volumetricLightFinalPostProcess.dispose(camera);
  59287. }
  59288. if (this.lensFlarePostProcess) {
  59289. this.lensFlarePostProcess.dispose(camera);
  59290. }
  59291. if (this.lensFlareComposePostProcess) {
  59292. this.lensFlareComposePostProcess.dispose(camera);
  59293. }
  59294. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  59295. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  59296. }
  59297. if (this.luminancePostProcess) {
  59298. this.luminancePostProcess.dispose(camera);
  59299. }
  59300. if (this.hdrPostProcess) {
  59301. this.hdrPostProcess.dispose(camera);
  59302. }
  59303. if (this.hdrFinalPostProcess) {
  59304. this.hdrFinalPostProcess.dispose(camera);
  59305. }
  59306. if (this.depthOfFieldPostProcess) {
  59307. this.depthOfFieldPostProcess.dispose(camera);
  59308. }
  59309. if (this.motionBlurPostProcess) {
  59310. this.motionBlurPostProcess.dispose(camera);
  59311. }
  59312. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  59313. this.blurHPostProcesses[j].dispose(camera);
  59314. }
  59315. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  59316. this.blurVPostProcesses[j].dispose(camera);
  59317. }
  59318. }
  59319. this.originalPostProcess = null;
  59320. this.downSampleX4PostProcess = null;
  59321. this.brightPassPostProcess = null;
  59322. this.textureAdderPostProcess = null;
  59323. this.textureAdderFinalPostProcess = null;
  59324. this.volumetricLightPostProcess = null;
  59325. this.volumetricLightSmoothXPostProcess = null;
  59326. this.volumetricLightSmoothYPostProcess = null;
  59327. this.volumetricLightMergePostProces = null;
  59328. this.volumetricLightFinalPostProcess = null;
  59329. this.lensFlarePostProcess = null;
  59330. this.lensFlareComposePostProcess = null;
  59331. this.luminancePostProcess = null;
  59332. this.hdrPostProcess = null;
  59333. this.hdrFinalPostProcess = null;
  59334. this.depthOfFieldPostProcess = null;
  59335. this.motionBlurPostProcess = null;
  59336. this.luminanceDownSamplePostProcesses = [];
  59337. this.blurHPostProcesses = [];
  59338. this.blurVPostProcesses = [];
  59339. };
  59340. // Dispose
  59341. StandardRenderingPipeline.prototype.dispose = function () {
  59342. this._disposePostProcesses();
  59343. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  59344. _super.prototype.dispose.call(this);
  59345. };
  59346. // Serialize rendering pipeline
  59347. StandardRenderingPipeline.prototype.serialize = function () {
  59348. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59349. serializationObject.customType = "StandardRenderingPipeline";
  59350. return serializationObject;
  59351. };
  59352. /**
  59353. * Static members
  59354. */
  59355. // Parse serialized pipeline
  59356. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59357. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  59358. };
  59359. // Luminance steps
  59360. StandardRenderingPipeline.LuminanceSteps = 6;
  59361. __decorate([
  59362. BABYLON.serialize()
  59363. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  59364. __decorate([
  59365. BABYLON.serialize()
  59366. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  59367. __decorate([
  59368. BABYLON.serialize()
  59369. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  59370. __decorate([
  59371. BABYLON.serialize()
  59372. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  59373. __decorate([
  59374. BABYLON.serializeAsTexture("lensTexture")
  59375. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  59376. __decorate([
  59377. BABYLON.serialize()
  59378. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  59379. __decorate([
  59380. BABYLON.serialize()
  59381. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  59382. __decorate([
  59383. BABYLON.serialize()
  59384. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  59385. __decorate([
  59386. BABYLON.serialize()
  59387. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  59388. __decorate([
  59389. BABYLON.serialize()
  59390. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  59391. __decorate([
  59392. BABYLON.serialize()
  59393. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  59394. __decorate([
  59395. BABYLON.serializeAsTexture("lensColorTexture")
  59396. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  59397. __decorate([
  59398. BABYLON.serialize()
  59399. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  59400. __decorate([
  59401. BABYLON.serialize()
  59402. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  59403. __decorate([
  59404. BABYLON.serialize()
  59405. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  59406. __decorate([
  59407. BABYLON.serialize()
  59408. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  59409. __decorate([
  59410. BABYLON.serializeAsTexture("lensStarTexture")
  59411. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  59412. __decorate([
  59413. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  59414. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  59415. __decorate([
  59416. BABYLON.serialize()
  59417. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  59418. __decorate([
  59419. BABYLON.serialize()
  59420. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  59421. __decorate([
  59422. BABYLON.serialize()
  59423. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  59424. __decorate([
  59425. BABYLON.serialize()
  59426. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  59427. __decorate([
  59428. BABYLON.serialize()
  59429. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  59430. __decorate([
  59431. BABYLON.serialize()
  59432. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  59433. __decorate([
  59434. BABYLON.serialize()
  59435. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  59436. __decorate([
  59437. BABYLON.serialize()
  59438. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  59439. __decorate([
  59440. BABYLON.serialize()
  59441. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  59442. __decorate([
  59443. BABYLON.serialize()
  59444. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  59445. __decorate([
  59446. BABYLON.serialize()
  59447. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  59448. return StandardRenderingPipeline;
  59449. }(BABYLON.PostProcessRenderPipeline));
  59450. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  59451. })(BABYLON || (BABYLON = {}));
  59452. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  59453. var BABYLON;
  59454. (function (BABYLON) {
  59455. var FxaaPostProcess = /** @class */ (function (_super) {
  59456. __extends(FxaaPostProcess, _super);
  59457. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59458. if (camera === void 0) { camera = null; }
  59459. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59460. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  59461. _this.onApplyObservable.add(function (effect) {
  59462. var texelSize = _this.texelSize;
  59463. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  59464. });
  59465. return _this;
  59466. }
  59467. return FxaaPostProcess;
  59468. }(BABYLON.PostProcess));
  59469. BABYLON.FxaaPostProcess = FxaaPostProcess;
  59470. })(BABYLON || (BABYLON = {}));
  59471. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  59472. var BABYLON;
  59473. (function (BABYLON) {
  59474. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  59475. __extends(DefaultRenderingPipeline, _super);
  59476. /**
  59477. * @constructor
  59478. * @param {string} name - The rendering pipeline name
  59479. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59480. * @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)
  59481. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59482. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  59483. */
  59484. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  59485. if (automaticBuild === void 0) { automaticBuild = true; }
  59486. var _this = _super.call(this, scene.getEngine(), name) || this;
  59487. _this.PassPostProcessId = "PassPostProcessEffect";
  59488. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  59489. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  59490. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  59491. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  59492. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  59493. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  59494. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  59495. // IAnimatable
  59496. _this.animations = [];
  59497. // Values
  59498. _this._bloomEnabled = false;
  59499. _this._fxaaEnabled = false;
  59500. _this._imageProcessingEnabled = true;
  59501. _this._bloomScale = 0.6;
  59502. _this._buildAllowed = true;
  59503. /**
  59504. * Specifies the size of the bloom blur kernel, relative to the final output size
  59505. */
  59506. _this.bloomKernel = 64;
  59507. /**
  59508. * Specifies the weight of the bloom in the final rendering
  59509. */
  59510. _this._bloomWeight = 0.15;
  59511. _this._cameras = cameras || [];
  59512. _this._buildAllowed = automaticBuild;
  59513. // Initialize
  59514. _this._scene = scene;
  59515. var caps = _this._scene.getEngine().getCaps();
  59516. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  59517. // Misc
  59518. if (_this._hdr) {
  59519. if (caps.textureHalfFloatRender) {
  59520. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59521. }
  59522. else if (caps.textureFloatRender) {
  59523. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59524. }
  59525. }
  59526. else {
  59527. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59528. }
  59529. // Attach
  59530. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59531. _this._buildPipeline();
  59532. return _this;
  59533. }
  59534. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  59535. get: function () {
  59536. return this._bloomWeight;
  59537. },
  59538. set: function (value) {
  59539. if (this._bloomWeight === value) {
  59540. return;
  59541. }
  59542. this._bloomWeight = value;
  59543. if (this._hdr && this.copyBack) {
  59544. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  59545. }
  59546. },
  59547. enumerable: true,
  59548. configurable: true
  59549. });
  59550. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  59551. get: function () {
  59552. return this._bloomScale;
  59553. },
  59554. set: function (value) {
  59555. if (this._bloomScale === value) {
  59556. return;
  59557. }
  59558. this._bloomScale = value;
  59559. this._buildPipeline();
  59560. },
  59561. enumerable: true,
  59562. configurable: true
  59563. });
  59564. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  59565. get: function () {
  59566. return this._bloomEnabled;
  59567. },
  59568. set: function (enabled) {
  59569. if (this._bloomEnabled === enabled) {
  59570. return;
  59571. }
  59572. this._bloomEnabled = enabled;
  59573. this._buildPipeline();
  59574. },
  59575. enumerable: true,
  59576. configurable: true
  59577. });
  59578. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  59579. get: function () {
  59580. return this._fxaaEnabled;
  59581. },
  59582. set: function (enabled) {
  59583. if (this._fxaaEnabled === enabled) {
  59584. return;
  59585. }
  59586. this._fxaaEnabled = enabled;
  59587. this._buildPipeline();
  59588. },
  59589. enumerable: true,
  59590. configurable: true
  59591. });
  59592. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  59593. get: function () {
  59594. return this._imageProcessingEnabled;
  59595. },
  59596. set: function (enabled) {
  59597. if (this._imageProcessingEnabled === enabled) {
  59598. return;
  59599. }
  59600. this._imageProcessingEnabled = enabled;
  59601. this._buildPipeline();
  59602. },
  59603. enumerable: true,
  59604. configurable: true
  59605. });
  59606. /**
  59607. * Force the compilation of the entire pipeline.
  59608. */
  59609. DefaultRenderingPipeline.prototype.prepare = function () {
  59610. var previousState = this._buildAllowed;
  59611. this._buildAllowed = true;
  59612. this._buildPipeline();
  59613. this._buildAllowed = previousState;
  59614. };
  59615. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  59616. var _this = this;
  59617. if (!this._buildAllowed) {
  59618. return;
  59619. }
  59620. var engine = this._scene.getEngine();
  59621. this._disposePostProcesses();
  59622. this._reset();
  59623. if (this.bloomEnabled) {
  59624. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59625. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  59626. if (!this._hdr) {
  59627. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59628. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  59629. this.highlights.autoClear = false;
  59630. this.highlights.alwaysForcePOT = true;
  59631. }
  59632. 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);
  59633. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  59634. this.blurX.alwaysForcePOT = true;
  59635. this.blurX.autoClear = false;
  59636. this.blurX.onActivateObservable.add(function () {
  59637. var dw = _this.blurX.width / engine.getRenderWidth(true);
  59638. _this.blurX.kernel = _this.bloomKernel * dw;
  59639. });
  59640. 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);
  59641. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  59642. this.blurY.alwaysForcePOT = true;
  59643. this.blurY.autoClear = false;
  59644. this.blurY.onActivateObservable.add(function () {
  59645. var dh = _this.blurY.height / engine.getRenderHeight(true);
  59646. _this.blurY.kernel = _this.bloomKernel * dh;
  59647. });
  59648. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59649. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  59650. this.copyBack.alwaysForcePOT = true;
  59651. if (this._hdr) {
  59652. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  59653. var w = this.bloomWeight;
  59654. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  59655. }
  59656. else {
  59657. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  59658. }
  59659. this.copyBack.autoClear = false;
  59660. }
  59661. if (this._imageProcessingEnabled) {
  59662. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59663. if (this._hdr) {
  59664. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  59665. }
  59666. else {
  59667. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  59668. }
  59669. }
  59670. if (this.fxaaEnabled) {
  59671. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59672. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  59673. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59674. }
  59675. else {
  59676. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59677. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  59678. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59679. }
  59680. if (this.bloomEnabled) {
  59681. if (this._hdr) {
  59682. this.copyBack.shareOutputWith(this.blurX);
  59683. if (this.imageProcessing) {
  59684. this.imageProcessing.shareOutputWith(this.pass);
  59685. this.imageProcessing.autoClear = false;
  59686. }
  59687. else if (this.fxaa) {
  59688. this.fxaa.shareOutputWith(this.pass);
  59689. }
  59690. else {
  59691. this.finalMerge.shareOutputWith(this.pass);
  59692. }
  59693. }
  59694. else {
  59695. if (this.fxaa) {
  59696. this.fxaa.shareOutputWith(this.pass);
  59697. }
  59698. else {
  59699. this.finalMerge.shareOutputWith(this.pass);
  59700. }
  59701. }
  59702. }
  59703. if (this._cameras !== null) {
  59704. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  59705. }
  59706. };
  59707. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  59708. for (var i = 0; i < this._cameras.length; i++) {
  59709. var camera = this._cameras[i];
  59710. if (this.pass) {
  59711. this.pass.dispose(camera);
  59712. }
  59713. if (this.highlights) {
  59714. this.highlights.dispose(camera);
  59715. }
  59716. if (this.blurX) {
  59717. this.blurX.dispose(camera);
  59718. }
  59719. if (this.blurY) {
  59720. this.blurY.dispose(camera);
  59721. }
  59722. if (this.copyBack) {
  59723. this.copyBack.dispose(camera);
  59724. }
  59725. if (this.imageProcessing) {
  59726. this.imageProcessing.dispose(camera);
  59727. }
  59728. if (this.fxaa) {
  59729. this.fxaa.dispose(camera);
  59730. }
  59731. if (this.finalMerge) {
  59732. this.finalMerge.dispose(camera);
  59733. }
  59734. }
  59735. this.pass = null;
  59736. this.highlights = null;
  59737. this.blurX = null;
  59738. this.blurY = null;
  59739. this.copyBack = null;
  59740. this.imageProcessing = null;
  59741. this.fxaa = null;
  59742. this.finalMerge = null;
  59743. };
  59744. // Dispose
  59745. DefaultRenderingPipeline.prototype.dispose = function () {
  59746. this._disposePostProcesses();
  59747. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  59748. _super.prototype.dispose.call(this);
  59749. };
  59750. // Serialize rendering pipeline
  59751. DefaultRenderingPipeline.prototype.serialize = function () {
  59752. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59753. serializationObject.customType = "DefaultRenderingPipeline";
  59754. return serializationObject;
  59755. };
  59756. // Parse serialized pipeline
  59757. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59758. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  59759. };
  59760. __decorate([
  59761. BABYLON.serialize()
  59762. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  59763. __decorate([
  59764. BABYLON.serialize()
  59765. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  59766. __decorate([
  59767. BABYLON.serialize()
  59768. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  59769. __decorate([
  59770. BABYLON.serialize()
  59771. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  59772. __decorate([
  59773. BABYLON.serialize()
  59774. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  59775. __decorate([
  59776. BABYLON.serialize()
  59777. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  59778. __decorate([
  59779. BABYLON.serialize()
  59780. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  59781. __decorate([
  59782. BABYLON.serialize()
  59783. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  59784. return DefaultRenderingPipeline;
  59785. }(BABYLON.PostProcessRenderPipeline));
  59786. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  59787. })(BABYLON || (BABYLON = {}));
  59788. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  59789. var BABYLON;
  59790. (function (BABYLON) {
  59791. var GeometryBufferRenderer = /** @class */ (function () {
  59792. function GeometryBufferRenderer(scene, ratio) {
  59793. if (ratio === void 0) { ratio = 1; }
  59794. this._enablePosition = false;
  59795. this._scene = scene;
  59796. this._ratio = ratio;
  59797. // Render target
  59798. this._createRenderTargets();
  59799. }
  59800. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  59801. set: function (meshes) {
  59802. this._multiRenderTarget.renderList = meshes;
  59803. },
  59804. enumerable: true,
  59805. configurable: true
  59806. });
  59807. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  59808. get: function () {
  59809. return this._multiRenderTarget.isSupported;
  59810. },
  59811. enumerable: true,
  59812. configurable: true
  59813. });
  59814. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  59815. get: function () {
  59816. return this._enablePosition;
  59817. },
  59818. set: function (enable) {
  59819. this._enablePosition = enable;
  59820. this.dispose();
  59821. this._createRenderTargets();
  59822. },
  59823. enumerable: true,
  59824. configurable: true
  59825. });
  59826. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  59827. var material = subMesh.getMaterial();
  59828. if (material && material.disableDepthWrite) {
  59829. return false;
  59830. }
  59831. var defines = [];
  59832. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  59833. var mesh = subMesh.getMesh();
  59834. // Alpha test
  59835. if (material && material.needAlphaTesting()) {
  59836. defines.push("#define ALPHATEST");
  59837. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59838. attribs.push(BABYLON.VertexBuffer.UVKind);
  59839. defines.push("#define UV1");
  59840. }
  59841. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59842. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59843. defines.push("#define UV2");
  59844. }
  59845. }
  59846. // Buffers
  59847. if (this._enablePosition) {
  59848. defines.push("#define POSITION");
  59849. }
  59850. // Bones
  59851. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59852. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59853. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59854. if (mesh.numBoneInfluencers > 4) {
  59855. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59856. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59857. }
  59858. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59859. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59860. }
  59861. else {
  59862. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59863. }
  59864. // Instances
  59865. if (useInstances) {
  59866. defines.push("#define INSTANCES");
  59867. attribs.push("world0");
  59868. attribs.push("world1");
  59869. attribs.push("world2");
  59870. attribs.push("world3");
  59871. }
  59872. // Get correct effect
  59873. var join = defines.join("\n");
  59874. if (this._cachedDefines !== join) {
  59875. this._cachedDefines = join;
  59876. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  59877. }
  59878. return this._effect.isReady();
  59879. };
  59880. GeometryBufferRenderer.prototype.getGBuffer = function () {
  59881. return this._multiRenderTarget;
  59882. };
  59883. // Methods
  59884. GeometryBufferRenderer.prototype.dispose = function () {
  59885. this.getGBuffer().dispose();
  59886. };
  59887. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  59888. var _this = this;
  59889. var engine = this._scene.getEngine();
  59890. var count = this._enablePosition ? 3 : 2;
  59891. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  59892. if (!this.isSupported) {
  59893. return;
  59894. }
  59895. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59896. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59897. this._multiRenderTarget.refreshRate = 1;
  59898. this._multiRenderTarget.renderParticles = false;
  59899. this._multiRenderTarget.renderList = null;
  59900. // set default depth value to 1.0 (far away)
  59901. this._multiRenderTarget.onClearObservable.add(function (engine) {
  59902. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  59903. });
  59904. // Custom render function
  59905. var renderSubMesh = function (subMesh) {
  59906. var mesh = subMesh.getRenderingMesh();
  59907. var scene = _this._scene;
  59908. var engine = scene.getEngine();
  59909. var material = subMesh.getMaterial();
  59910. if (!material) {
  59911. return;
  59912. }
  59913. // Culling
  59914. engine.setState(material.backFaceCulling);
  59915. // Managing instances
  59916. var batch = mesh._getInstancesRenderList(subMesh._id);
  59917. if (batch.mustReturn) {
  59918. return;
  59919. }
  59920. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59921. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59922. engine.enableEffect(_this._effect);
  59923. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59924. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59925. _this._effect.setMatrix("view", scene.getViewMatrix());
  59926. // Alpha test
  59927. if (material && material.needAlphaTesting()) {
  59928. var alphaTexture = material.getAlphaTestTexture();
  59929. if (alphaTexture) {
  59930. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59931. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59932. }
  59933. }
  59934. // Bones
  59935. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59936. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59937. }
  59938. // Draw
  59939. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59940. }
  59941. };
  59942. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59943. var index;
  59944. if (depthOnlySubMeshes.length) {
  59945. engine.setColorWrite(false);
  59946. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59947. renderSubMesh(depthOnlySubMeshes.data[index]);
  59948. }
  59949. engine.setColorWrite(true);
  59950. }
  59951. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59952. renderSubMesh(opaqueSubMeshes.data[index]);
  59953. }
  59954. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59955. renderSubMesh(alphaTestSubMeshes.data[index]);
  59956. }
  59957. };
  59958. };
  59959. return GeometryBufferRenderer;
  59960. }());
  59961. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  59962. })(BABYLON || (BABYLON = {}));
  59963. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  59964. var BABYLON;
  59965. (function (BABYLON) {
  59966. var RefractionPostProcess = /** @class */ (function (_super) {
  59967. __extends(RefractionPostProcess, _super);
  59968. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  59969. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  59970. _this.color = color;
  59971. _this.depth = depth;
  59972. _this.colorLevel = colorLevel;
  59973. _this.onActivateObservable.add(function (cam) {
  59974. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  59975. });
  59976. _this.onApplyObservable.add(function (effect) {
  59977. effect.setColor3("baseColor", _this.color);
  59978. effect.setFloat("depth", _this.depth);
  59979. effect.setFloat("colorLevel", _this.colorLevel);
  59980. effect.setTexture("refractionSampler", _this._refRexture);
  59981. });
  59982. return _this;
  59983. }
  59984. // Methods
  59985. RefractionPostProcess.prototype.dispose = function (camera) {
  59986. if (this._refRexture) {
  59987. this._refRexture.dispose();
  59988. }
  59989. _super.prototype.dispose.call(this, camera);
  59990. };
  59991. return RefractionPostProcess;
  59992. }(BABYLON.PostProcess));
  59993. BABYLON.RefractionPostProcess = RefractionPostProcess;
  59994. })(BABYLON || (BABYLON = {}));
  59995. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  59996. var BABYLON;
  59997. (function (BABYLON) {
  59998. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  59999. __extends(BlackAndWhitePostProcess, _super);
  60000. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  60001. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  60002. _this.degree = 1;
  60003. _this.onApplyObservable.add(function (effect) {
  60004. effect.setFloat("degree", _this.degree);
  60005. });
  60006. return _this;
  60007. }
  60008. return BlackAndWhitePostProcess;
  60009. }(BABYLON.PostProcess));
  60010. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  60011. })(BABYLON || (BABYLON = {}));
  60012. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  60013. var BABYLON;
  60014. (function (BABYLON) {
  60015. var ConvolutionPostProcess = /** @class */ (function (_super) {
  60016. __extends(ConvolutionPostProcess, _super);
  60017. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  60018. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  60019. _this.kernel = kernel;
  60020. _this.onApply = function (effect) {
  60021. effect.setFloat2("screenSize", _this.width, _this.height);
  60022. effect.setArray("kernel", _this.kernel);
  60023. };
  60024. return _this;
  60025. }
  60026. // Statics
  60027. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  60028. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  60029. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  60030. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  60031. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  60032. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  60033. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  60034. return ConvolutionPostProcess;
  60035. }(BABYLON.PostProcess));
  60036. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  60037. })(BABYLON || (BABYLON = {}));
  60038. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  60039. var BABYLON;
  60040. (function (BABYLON) {
  60041. var FilterPostProcess = /** @class */ (function (_super) {
  60042. __extends(FilterPostProcess, _super);
  60043. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  60044. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  60045. _this.kernelMatrix = kernelMatrix;
  60046. _this.onApply = function (effect) {
  60047. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  60048. };
  60049. return _this;
  60050. }
  60051. return FilterPostProcess;
  60052. }(BABYLON.PostProcess));
  60053. BABYLON.FilterPostProcess = FilterPostProcess;
  60054. })(BABYLON || (BABYLON = {}));
  60055. //# sourceMappingURL=babylon.filterPostProcess.js.map
  60056. var BABYLON;
  60057. (function (BABYLON) {
  60058. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  60059. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  60060. __extends(VolumetricLightScatteringPostProcess, _super);
  60061. /**
  60062. * @constructor
  60063. * @param {string} name - The post-process name
  60064. * @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)
  60065. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  60066. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  60067. * @param {number} samples - The post-process quality, default 100
  60068. * @param {number} samplingMode - The post-process filtering mode
  60069. * @param {BABYLON.Engine} engine - The babylon engine
  60070. * @param {boolean} reusable - If the post-process is reusable
  60071. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  60072. */
  60073. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  60074. if (samples === void 0) { samples = 100; }
  60075. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60076. 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;
  60077. _this._screenCoordinates = BABYLON.Vector2.Zero();
  60078. /**
  60079. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  60080. * @type {Vector3}
  60081. */
  60082. _this.customMeshPosition = BABYLON.Vector3.Zero();
  60083. /**
  60084. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  60085. * @type {boolean}
  60086. */
  60087. _this.useCustomMeshPosition = false;
  60088. /**
  60089. * If the post-process should inverse the light scattering direction
  60090. * @type {boolean}
  60091. */
  60092. _this.invert = true;
  60093. /**
  60094. * Array containing the excluded meshes not rendered in the internal pass
  60095. */
  60096. _this.excludedMeshes = new Array();
  60097. /**
  60098. * Controls the overall intensity of the post-process
  60099. * @type {number}
  60100. */
  60101. _this.exposure = 0.3;
  60102. /**
  60103. * Dissipates each sample's contribution in range [0, 1]
  60104. * @type {number}
  60105. */
  60106. _this.decay = 0.96815;
  60107. /**
  60108. * Controls the overall intensity of each sample
  60109. * @type {number}
  60110. */
  60111. _this.weight = 0.58767;
  60112. /**
  60113. * Controls the density of each sample
  60114. * @type {number}
  60115. */
  60116. _this.density = 0.926;
  60117. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  60118. engine = scene.getEngine();
  60119. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  60120. // Configure mesh
  60121. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  60122. // Configure
  60123. _this._createPass(scene, ratio.passRatio || ratio);
  60124. _this.onActivate = function (camera) {
  60125. if (!_this.isSupported) {
  60126. _this.dispose(camera);
  60127. }
  60128. _this.onActivate = null;
  60129. };
  60130. _this.onApplyObservable.add(function (effect) {
  60131. _this._updateMeshScreenCoordinates(scene);
  60132. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  60133. effect.setFloat("exposure", _this.exposure);
  60134. effect.setFloat("decay", _this.decay);
  60135. effect.setFloat("weight", _this.weight);
  60136. effect.setFloat("density", _this.density);
  60137. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  60138. });
  60139. return _this;
  60140. }
  60141. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  60142. get: function () {
  60143. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60144. return false;
  60145. },
  60146. set: function (useDiffuseColor) {
  60147. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60148. },
  60149. enumerable: true,
  60150. configurable: true
  60151. });
  60152. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  60153. return "VolumetricLightScatteringPostProcess";
  60154. };
  60155. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  60156. var mesh = subMesh.getMesh();
  60157. // Render this.mesh as default
  60158. if (mesh === this.mesh && mesh.material) {
  60159. return mesh.material.isReady(mesh);
  60160. }
  60161. var defines = [];
  60162. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60163. var material = subMesh.getMaterial();
  60164. // Alpha test
  60165. if (material) {
  60166. if (material.needAlphaTesting()) {
  60167. defines.push("#define ALPHATEST");
  60168. }
  60169. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60170. attribs.push(BABYLON.VertexBuffer.UVKind);
  60171. defines.push("#define UV1");
  60172. }
  60173. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60174. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60175. defines.push("#define UV2");
  60176. }
  60177. }
  60178. // Bones
  60179. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60180. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60181. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60182. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60183. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  60184. }
  60185. else {
  60186. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60187. }
  60188. // Instances
  60189. if (useInstances) {
  60190. defines.push("#define INSTANCES");
  60191. attribs.push("world0");
  60192. attribs.push("world1");
  60193. attribs.push("world2");
  60194. attribs.push("world3");
  60195. }
  60196. // Get correct effect
  60197. var join = defines.join("\n");
  60198. if (this._cachedDefines !== join) {
  60199. this._cachedDefines = join;
  60200. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  60201. }
  60202. return this._volumetricLightScatteringPass.isReady();
  60203. };
  60204. /**
  60205. * Sets the new light position for light scattering effect
  60206. * @param {BABYLON.Vector3} The new custom light position
  60207. */
  60208. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  60209. this.customMeshPosition = position;
  60210. };
  60211. /**
  60212. * Returns the light position for light scattering effect
  60213. * @return {BABYLON.Vector3} The custom light position
  60214. */
  60215. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  60216. return this.customMeshPosition;
  60217. };
  60218. /**
  60219. * Disposes the internal assets and detaches the post-process from the camera
  60220. */
  60221. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  60222. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  60223. if (rttIndex !== -1) {
  60224. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  60225. }
  60226. this._volumetricLightScatteringRTT.dispose();
  60227. _super.prototype.dispose.call(this, camera);
  60228. };
  60229. /**
  60230. * Returns the render target texture used by the post-process
  60231. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  60232. */
  60233. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  60234. return this._volumetricLightScatteringRTT;
  60235. };
  60236. // Private methods
  60237. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  60238. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  60239. return true;
  60240. }
  60241. return false;
  60242. };
  60243. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  60244. var _this = this;
  60245. var engine = scene.getEngine();
  60246. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  60247. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60248. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60249. this._volumetricLightScatteringRTT.renderList = null;
  60250. this._volumetricLightScatteringRTT.renderParticles = false;
  60251. var camera = this.getCamera();
  60252. if (camera) {
  60253. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  60254. }
  60255. else {
  60256. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  60257. }
  60258. // Custom render function for submeshes
  60259. var renderSubMesh = function (subMesh) {
  60260. var mesh = subMesh.getRenderingMesh();
  60261. if (_this._meshExcluded(mesh)) {
  60262. return;
  60263. }
  60264. var material = subMesh.getMaterial();
  60265. if (!material) {
  60266. return;
  60267. }
  60268. var scene = mesh.getScene();
  60269. var engine = scene.getEngine();
  60270. // Culling
  60271. engine.setState(material.backFaceCulling);
  60272. // Managing instances
  60273. var batch = mesh._getInstancesRenderList(subMesh._id);
  60274. if (batch.mustReturn) {
  60275. return;
  60276. }
  60277. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  60278. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  60279. var effect = _this._volumetricLightScatteringPass;
  60280. if (mesh === _this.mesh) {
  60281. if (subMesh.effect) {
  60282. effect = subMesh.effect;
  60283. }
  60284. else {
  60285. effect = material.getEffect();
  60286. }
  60287. }
  60288. engine.enableEffect(effect);
  60289. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  60290. if (mesh === _this.mesh) {
  60291. material.bind(mesh.getWorldMatrix(), mesh);
  60292. }
  60293. else {
  60294. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  60295. // Alpha test
  60296. if (material && material.needAlphaTesting()) {
  60297. var alphaTexture = material.getAlphaTestTexture();
  60298. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  60299. if (alphaTexture) {
  60300. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60301. }
  60302. }
  60303. // Bones
  60304. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60305. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60306. }
  60307. }
  60308. // Draw
  60309. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  60310. }
  60311. };
  60312. // Render target texture callbacks
  60313. var savedSceneClearColor;
  60314. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  60315. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  60316. savedSceneClearColor = scene.clearColor;
  60317. scene.clearColor = sceneClearColor;
  60318. });
  60319. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  60320. scene.clearColor = savedSceneClearColor;
  60321. });
  60322. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60323. var engine = scene.getEngine();
  60324. var index;
  60325. if (depthOnlySubMeshes.length) {
  60326. engine.setColorWrite(false);
  60327. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60328. renderSubMesh(depthOnlySubMeshes.data[index]);
  60329. }
  60330. engine.setColorWrite(true);
  60331. }
  60332. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60333. renderSubMesh(opaqueSubMeshes.data[index]);
  60334. }
  60335. engine.setAlphaTesting(true);
  60336. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60337. renderSubMesh(alphaTestSubMeshes.data[index]);
  60338. }
  60339. engine.setAlphaTesting(false);
  60340. if (transparentSubMeshes.length) {
  60341. // Sort sub meshes
  60342. for (index = 0; index < transparentSubMeshes.length; index++) {
  60343. var submesh = transparentSubMeshes.data[index];
  60344. var boundingInfo = submesh.getBoundingInfo();
  60345. if (boundingInfo && scene.activeCamera) {
  60346. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  60347. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  60348. }
  60349. }
  60350. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  60351. sortedArray.sort(function (a, b) {
  60352. // Alpha index first
  60353. if (a._alphaIndex > b._alphaIndex) {
  60354. return 1;
  60355. }
  60356. if (a._alphaIndex < b._alphaIndex) {
  60357. return -1;
  60358. }
  60359. // Then distance to camera
  60360. if (a._distanceToCamera < b._distanceToCamera) {
  60361. return 1;
  60362. }
  60363. if (a._distanceToCamera > b._distanceToCamera) {
  60364. return -1;
  60365. }
  60366. return 0;
  60367. });
  60368. // Render sub meshes
  60369. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60370. for (index = 0; index < sortedArray.length; index++) {
  60371. renderSubMesh(sortedArray[index]);
  60372. }
  60373. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60374. }
  60375. };
  60376. };
  60377. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  60378. var transform = scene.getTransformMatrix();
  60379. var meshPosition;
  60380. if (this.useCustomMeshPosition) {
  60381. meshPosition = this.customMeshPosition;
  60382. }
  60383. else if (this.attachedNode) {
  60384. meshPosition = this.attachedNode.position;
  60385. }
  60386. else {
  60387. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  60388. }
  60389. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  60390. this._screenCoordinates.x = pos.x / this._viewPort.width;
  60391. this._screenCoordinates.y = pos.y / this._viewPort.height;
  60392. if (this.invert)
  60393. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  60394. };
  60395. // Static methods
  60396. /**
  60397. * Creates a default mesh for the Volumeric Light Scattering post-process
  60398. * @param {string} The mesh name
  60399. * @param {BABYLON.Scene} The scene where to create the mesh
  60400. * @return {BABYLON.Mesh} the default mesh
  60401. */
  60402. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  60403. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  60404. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  60405. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  60406. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  60407. mesh.material = material;
  60408. return mesh;
  60409. };
  60410. __decorate([
  60411. BABYLON.serializeAsVector3()
  60412. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  60413. __decorate([
  60414. BABYLON.serialize()
  60415. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  60416. __decorate([
  60417. BABYLON.serialize()
  60418. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  60419. __decorate([
  60420. BABYLON.serializeAsMeshReference()
  60421. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  60422. __decorate([
  60423. BABYLON.serialize()
  60424. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  60425. __decorate([
  60426. BABYLON.serialize()
  60427. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  60428. __decorate([
  60429. BABYLON.serialize()
  60430. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  60431. __decorate([
  60432. BABYLON.serialize()
  60433. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  60434. __decorate([
  60435. BABYLON.serialize()
  60436. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  60437. return VolumetricLightScatteringPostProcess;
  60438. }(BABYLON.PostProcess));
  60439. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  60440. })(BABYLON || (BABYLON = {}));
  60441. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  60442. //
  60443. // This post-process allows the modification of rendered colors by using
  60444. // a 'look-up table' (LUT). This effect is also called Color Grading.
  60445. //
  60446. // The object needs to be provided an url to a texture containing the color
  60447. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  60448. // Use an image editing software to tweak the LUT to match your needs.
  60449. //
  60450. // For an example of a color LUT, see here:
  60451. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  60452. // For explanations on color grading, see here:
  60453. // http://udn.epicgames.com/Three/ColorGrading.html
  60454. //
  60455. var BABYLON;
  60456. (function (BABYLON) {
  60457. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  60458. __extends(ColorCorrectionPostProcess, _super);
  60459. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  60460. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  60461. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60462. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  60463. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60464. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60465. _this.onApply = function (effect) {
  60466. effect.setTexture("colorTable", _this._colorTableTexture);
  60467. };
  60468. return _this;
  60469. }
  60470. return ColorCorrectionPostProcess;
  60471. }(BABYLON.PostProcess));
  60472. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  60473. })(BABYLON || (BABYLON = {}));
  60474. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  60475. var BABYLON;
  60476. (function (BABYLON) {
  60477. var TonemappingOperator;
  60478. (function (TonemappingOperator) {
  60479. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  60480. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  60481. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  60482. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  60483. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  60484. ;
  60485. var TonemapPostProcess = /** @class */ (function (_super) {
  60486. __extends(TonemapPostProcess, _super);
  60487. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  60488. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60489. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60490. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  60491. _this._operator = _operator;
  60492. _this.exposureAdjustment = exposureAdjustment;
  60493. var defines = "#define ";
  60494. if (_this._operator === TonemappingOperator.Hable)
  60495. defines += "HABLE_TONEMAPPING";
  60496. else if (_this._operator === TonemappingOperator.Reinhard)
  60497. defines += "REINHARD_TONEMAPPING";
  60498. else if (_this._operator === TonemappingOperator.HejiDawson)
  60499. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  60500. else if (_this._operator === TonemappingOperator.Photographic)
  60501. defines += "PHOTOGRAPHIC_TONEMAPPING";
  60502. //sadly a second call to create the effect.
  60503. _this.updateEffect(defines);
  60504. _this.onApply = function (effect) {
  60505. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  60506. };
  60507. return _this;
  60508. }
  60509. return TonemapPostProcess;
  60510. }(BABYLON.PostProcess));
  60511. BABYLON.TonemapPostProcess = TonemapPostProcess;
  60512. })(BABYLON || (BABYLON = {}));
  60513. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  60514. var BABYLON;
  60515. (function (BABYLON) {
  60516. var DisplayPassPostProcess = /** @class */ (function (_super) {
  60517. __extends(DisplayPassPostProcess, _super);
  60518. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  60519. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  60520. }
  60521. return DisplayPassPostProcess;
  60522. }(BABYLON.PostProcess));
  60523. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  60524. })(BABYLON || (BABYLON = {}));
  60525. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  60526. var BABYLON;
  60527. (function (BABYLON) {
  60528. var HighlightsPostProcess = /** @class */ (function (_super) {
  60529. __extends(HighlightsPostProcess, _super);
  60530. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  60531. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60532. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  60533. }
  60534. return HighlightsPostProcess;
  60535. }(BABYLON.PostProcess));
  60536. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  60537. })(BABYLON || (BABYLON = {}));
  60538. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  60539. var BABYLON;
  60540. (function (BABYLON) {
  60541. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  60542. __extends(ImageProcessingPostProcess, _super);
  60543. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  60544. if (camera === void 0) { camera = null; }
  60545. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60546. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  60547. _this._fromLinearSpace = true;
  60548. /**
  60549. * Defines cache preventing GC.
  60550. */
  60551. _this._defines = {
  60552. IMAGEPROCESSING: false,
  60553. VIGNETTE: false,
  60554. VIGNETTEBLENDMODEMULTIPLY: false,
  60555. VIGNETTEBLENDMODEOPAQUE: false,
  60556. TONEMAPPING: false,
  60557. CONTRAST: false,
  60558. COLORCURVES: false,
  60559. COLORGRADING: false,
  60560. COLORGRADING3D: false,
  60561. FROMLINEARSPACE: false,
  60562. SAMPLER3DGREENDEPTH: false,
  60563. SAMPLER3DBGRMAP: false,
  60564. IMAGEPROCESSINGPOSTPROCESS: false,
  60565. EXPOSURE: false,
  60566. };
  60567. // Setup the default processing configuration to the scene.
  60568. _this._attachImageProcessingConfiguration(null, true);
  60569. _this.imageProcessingConfiguration.applyByPostProcess = true;
  60570. _this.onApply = function (effect) {
  60571. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  60572. };
  60573. return _this;
  60574. }
  60575. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  60576. /**
  60577. * Gets the image processing configuration used either in this material.
  60578. */
  60579. get: function () {
  60580. return this._imageProcessingConfiguration;
  60581. },
  60582. /**
  60583. * Sets the Default image processing configuration used either in the this material.
  60584. *
  60585. * If sets to null, the scene one is in use.
  60586. */
  60587. set: function (value) {
  60588. this._attachImageProcessingConfiguration(value);
  60589. },
  60590. enumerable: true,
  60591. configurable: true
  60592. });
  60593. /**
  60594. * Attaches a new image processing configuration to the PBR Material.
  60595. * @param configuration
  60596. */
  60597. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  60598. var _this = this;
  60599. if (doNotBuild === void 0) { doNotBuild = false; }
  60600. if (configuration === this._imageProcessingConfiguration) {
  60601. return;
  60602. }
  60603. // Detaches observer.
  60604. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60605. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60606. }
  60607. // Pick the scene configuration if needed.
  60608. if (!configuration) {
  60609. var scene = null;
  60610. var engine = this.getEngine();
  60611. var camera = this.getCamera();
  60612. if (camera) {
  60613. scene = camera.getScene();
  60614. }
  60615. else if (engine && engine.scenes) {
  60616. var scenes = engine.scenes;
  60617. scene = scenes[scenes.length - 1];
  60618. }
  60619. else {
  60620. scene = BABYLON.Engine.LastCreatedScene;
  60621. }
  60622. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  60623. }
  60624. else {
  60625. this._imageProcessingConfiguration = configuration;
  60626. }
  60627. // Attaches observer.
  60628. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  60629. _this._updateParameters();
  60630. });
  60631. // Ensure the effect will be rebuilt.
  60632. if (!doNotBuild) {
  60633. this._updateParameters();
  60634. }
  60635. };
  60636. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  60637. /**
  60638. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60639. */
  60640. get: function () {
  60641. return this.imageProcessingConfiguration.colorCurves;
  60642. },
  60643. /**
  60644. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60645. */
  60646. set: function (value) {
  60647. this.imageProcessingConfiguration.colorCurves = value;
  60648. },
  60649. enumerable: true,
  60650. configurable: true
  60651. });
  60652. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  60653. /**
  60654. * Gets wether the color curves effect is enabled.
  60655. */
  60656. get: function () {
  60657. return this.imageProcessingConfiguration.colorCurvesEnabled;
  60658. },
  60659. /**
  60660. * Sets wether the color curves effect is enabled.
  60661. */
  60662. set: function (value) {
  60663. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  60664. },
  60665. enumerable: true,
  60666. configurable: true
  60667. });
  60668. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  60669. /**
  60670. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60671. */
  60672. get: function () {
  60673. return this.imageProcessingConfiguration.colorGradingTexture;
  60674. },
  60675. /**
  60676. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60677. */
  60678. set: function (value) {
  60679. this.imageProcessingConfiguration.colorGradingTexture = value;
  60680. },
  60681. enumerable: true,
  60682. configurable: true
  60683. });
  60684. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  60685. /**
  60686. * Gets wether the color grading effect is enabled.
  60687. */
  60688. get: function () {
  60689. return this.imageProcessingConfiguration.colorGradingEnabled;
  60690. },
  60691. /**
  60692. * Gets wether the color grading effect is enabled.
  60693. */
  60694. set: function (value) {
  60695. this.imageProcessingConfiguration.colorGradingEnabled = value;
  60696. },
  60697. enumerable: true,
  60698. configurable: true
  60699. });
  60700. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  60701. /**
  60702. * Gets exposure used in the effect.
  60703. */
  60704. get: function () {
  60705. return this.imageProcessingConfiguration.exposure;
  60706. },
  60707. /**
  60708. * Sets exposure used in the effect.
  60709. */
  60710. set: function (value) {
  60711. this.imageProcessingConfiguration.exposure = value;
  60712. },
  60713. enumerable: true,
  60714. configurable: true
  60715. });
  60716. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  60717. /**
  60718. * Gets wether tonemapping is enabled or not.
  60719. */
  60720. get: function () {
  60721. return this._imageProcessingConfiguration.toneMappingEnabled;
  60722. },
  60723. /**
  60724. * Sets wether tonemapping is enabled or not
  60725. */
  60726. set: function (value) {
  60727. this._imageProcessingConfiguration.toneMappingEnabled = value;
  60728. },
  60729. enumerable: true,
  60730. configurable: true
  60731. });
  60732. ;
  60733. ;
  60734. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  60735. /**
  60736. * Gets contrast used in the effect.
  60737. */
  60738. get: function () {
  60739. return this.imageProcessingConfiguration.contrast;
  60740. },
  60741. /**
  60742. * Sets contrast used in the effect.
  60743. */
  60744. set: function (value) {
  60745. this.imageProcessingConfiguration.contrast = value;
  60746. },
  60747. enumerable: true,
  60748. configurable: true
  60749. });
  60750. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  60751. /**
  60752. * Gets Vignette stretch size.
  60753. */
  60754. get: function () {
  60755. return this.imageProcessingConfiguration.vignetteStretch;
  60756. },
  60757. /**
  60758. * Sets Vignette stretch size.
  60759. */
  60760. set: function (value) {
  60761. this.imageProcessingConfiguration.vignetteStretch = value;
  60762. },
  60763. enumerable: true,
  60764. configurable: true
  60765. });
  60766. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  60767. /**
  60768. * Gets Vignette centre X Offset.
  60769. */
  60770. get: function () {
  60771. return this.imageProcessingConfiguration.vignetteCentreX;
  60772. },
  60773. /**
  60774. * Sets Vignette centre X Offset.
  60775. */
  60776. set: function (value) {
  60777. this.imageProcessingConfiguration.vignetteCentreX = value;
  60778. },
  60779. enumerable: true,
  60780. configurable: true
  60781. });
  60782. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  60783. /**
  60784. * Gets Vignette centre Y Offset.
  60785. */
  60786. get: function () {
  60787. return this.imageProcessingConfiguration.vignetteCentreY;
  60788. },
  60789. /**
  60790. * Sets Vignette centre Y Offset.
  60791. */
  60792. set: function (value) {
  60793. this.imageProcessingConfiguration.vignetteCentreY = value;
  60794. },
  60795. enumerable: true,
  60796. configurable: true
  60797. });
  60798. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  60799. /**
  60800. * Gets Vignette weight or intensity of the vignette effect.
  60801. */
  60802. get: function () {
  60803. return this.imageProcessingConfiguration.vignetteWeight;
  60804. },
  60805. /**
  60806. * Sets Vignette weight or intensity of the vignette effect.
  60807. */
  60808. set: function (value) {
  60809. this.imageProcessingConfiguration.vignetteWeight = value;
  60810. },
  60811. enumerable: true,
  60812. configurable: true
  60813. });
  60814. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  60815. /**
  60816. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60817. * if vignetteEnabled is set to true.
  60818. */
  60819. get: function () {
  60820. return this.imageProcessingConfiguration.vignetteColor;
  60821. },
  60822. /**
  60823. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60824. * if vignetteEnabled is set to true.
  60825. */
  60826. set: function (value) {
  60827. this.imageProcessingConfiguration.vignetteColor = value;
  60828. },
  60829. enumerable: true,
  60830. configurable: true
  60831. });
  60832. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  60833. /**
  60834. * Gets Camera field of view used by the Vignette effect.
  60835. */
  60836. get: function () {
  60837. return this.imageProcessingConfiguration.vignetteCameraFov;
  60838. },
  60839. /**
  60840. * Sets Camera field of view used by the Vignette effect.
  60841. */
  60842. set: function (value) {
  60843. this.imageProcessingConfiguration.vignetteCameraFov = value;
  60844. },
  60845. enumerable: true,
  60846. configurable: true
  60847. });
  60848. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  60849. /**
  60850. * Gets the vignette blend mode allowing different kind of effect.
  60851. */
  60852. get: function () {
  60853. return this.imageProcessingConfiguration.vignetteBlendMode;
  60854. },
  60855. /**
  60856. * Sets the vignette blend mode allowing different kind of effect.
  60857. */
  60858. set: function (value) {
  60859. this.imageProcessingConfiguration.vignetteBlendMode = value;
  60860. },
  60861. enumerable: true,
  60862. configurable: true
  60863. });
  60864. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  60865. /**
  60866. * Gets wether the vignette effect is enabled.
  60867. */
  60868. get: function () {
  60869. return this.imageProcessingConfiguration.vignetteEnabled;
  60870. },
  60871. /**
  60872. * Sets wether the vignette effect is enabled.
  60873. */
  60874. set: function (value) {
  60875. this.imageProcessingConfiguration.vignetteEnabled = value;
  60876. },
  60877. enumerable: true,
  60878. configurable: true
  60879. });
  60880. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  60881. /**
  60882. * Gets wether the input of the processing is in Gamma or Linear Space.
  60883. */
  60884. get: function () {
  60885. return this._fromLinearSpace;
  60886. },
  60887. /**
  60888. * Sets wether the input of the processing is in Gamma or Linear Space.
  60889. */
  60890. set: function (value) {
  60891. if (this._fromLinearSpace === value) {
  60892. return;
  60893. }
  60894. this._fromLinearSpace = value;
  60895. this._updateParameters();
  60896. },
  60897. enumerable: true,
  60898. configurable: true
  60899. });
  60900. ImageProcessingPostProcess.prototype.getClassName = function () {
  60901. return "ImageProcessingPostProcess";
  60902. };
  60903. ImageProcessingPostProcess.prototype._updateParameters = function () {
  60904. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  60905. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  60906. var defines = "";
  60907. for (var define in this._defines) {
  60908. if (this._defines[define]) {
  60909. defines += "#define " + define + ";\r\n";
  60910. }
  60911. }
  60912. var samplers = ["textureSampler"];
  60913. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  60914. var uniforms = ["scale"];
  60915. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  60916. this.updateEffect(defines, uniforms, samplers);
  60917. };
  60918. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  60919. _super.prototype.dispose.call(this, camera);
  60920. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60921. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60922. }
  60923. this.imageProcessingConfiguration.applyByPostProcess = false;
  60924. };
  60925. __decorate([
  60926. BABYLON.serialize()
  60927. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  60928. return ImageProcessingPostProcess;
  60929. }(BABYLON.PostProcess));
  60930. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  60931. })(BABYLON || (BABYLON = {}));
  60932. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  60933. var BABYLON;
  60934. (function (BABYLON) {
  60935. var BlurPostProcess = /** @class */ (function (_super) {
  60936. __extends(BlurPostProcess, _super);
  60937. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  60938. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60939. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60940. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  60941. _this.direction = direction;
  60942. _this._packedFloat = false;
  60943. _this.onApplyObservable.add(function (effect) {
  60944. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  60945. });
  60946. _this.kernel = kernel;
  60947. return _this;
  60948. }
  60949. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  60950. /**
  60951. * Gets the length in pixels of the blur sample region
  60952. */
  60953. get: function () {
  60954. return this._idealKernel;
  60955. },
  60956. /**
  60957. * Sets the length in pixels of the blur sample region
  60958. */
  60959. set: function (v) {
  60960. if (this._idealKernel === v) {
  60961. return;
  60962. }
  60963. v = Math.max(v, 1);
  60964. this._idealKernel = v;
  60965. this._kernel = this._nearestBestKernel(v);
  60966. this._updateParameters();
  60967. },
  60968. enumerable: true,
  60969. configurable: true
  60970. });
  60971. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  60972. /**
  60973. * Gets wether or not the blur is unpacking/repacking floats
  60974. */
  60975. get: function () {
  60976. return this._packedFloat;
  60977. },
  60978. /**
  60979. * Sets wether or not the blur needs to unpack/repack floats
  60980. */
  60981. set: function (v) {
  60982. if (this._packedFloat === v) {
  60983. return;
  60984. }
  60985. this._packedFloat = v;
  60986. this._updateParameters();
  60987. },
  60988. enumerable: true,
  60989. configurable: true
  60990. });
  60991. BlurPostProcess.prototype._updateParameters = function () {
  60992. // Generate sampling offsets and weights
  60993. var N = this._kernel;
  60994. var centerIndex = (N - 1) / 2;
  60995. // Generate Gaussian sampling weights over kernel
  60996. var offsets = [];
  60997. var weights = [];
  60998. var totalWeight = 0;
  60999. for (var i = 0; i < N; i++) {
  61000. var u = i / (N - 1);
  61001. var w = this._gaussianWeight(u * 2.0 - 1);
  61002. offsets[i] = (i - centerIndex);
  61003. weights[i] = w;
  61004. totalWeight += w;
  61005. }
  61006. // Normalize weights
  61007. for (var i = 0; i < weights.length; i++) {
  61008. weights[i] /= totalWeight;
  61009. }
  61010. // Optimize: combine samples to take advantage of hardware linear sampling
  61011. // Walk from left to center, combining pairs (symmetrically)
  61012. var linearSamplingWeights = [];
  61013. var linearSamplingOffsets = [];
  61014. var linearSamplingMap = [];
  61015. for (var i = 0; i <= centerIndex; i += 2) {
  61016. var j = Math.min(i + 1, Math.floor(centerIndex));
  61017. var singleCenterSample = i === j;
  61018. if (singleCenterSample) {
  61019. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  61020. }
  61021. else {
  61022. var sharedCell = j === centerIndex;
  61023. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  61024. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  61025. if (offsetLinear === 0) {
  61026. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  61027. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  61028. }
  61029. else {
  61030. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  61031. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  61032. }
  61033. }
  61034. }
  61035. for (var i = 0; i < linearSamplingMap.length; i++) {
  61036. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  61037. linearSamplingWeights[i] = linearSamplingMap[i].w;
  61038. }
  61039. // Replace with optimized
  61040. offsets = linearSamplingOffsets;
  61041. weights = linearSamplingWeights;
  61042. // Generate shaders
  61043. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  61044. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  61045. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  61046. var defines = "";
  61047. for (var i = 0; i < varyingCount; i++) {
  61048. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  61049. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  61050. }
  61051. var depCount = 0;
  61052. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  61053. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  61054. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  61055. depCount++;
  61056. }
  61057. if (this.packedFloat) {
  61058. defines += "#define PACKEDFLOAT 1";
  61059. }
  61060. this.updateEffect(defines, null, null, {
  61061. varyingCount: varyingCount,
  61062. depCount: depCount
  61063. });
  61064. };
  61065. /**
  61066. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  61067. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  61068. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  61069. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  61070. * The gaps between physical kernels are compensated for in the weighting of the samples
  61071. * @param idealKernel Ideal blur kernel.
  61072. * @return Nearest best kernel.
  61073. */
  61074. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  61075. var v = Math.round(idealKernel);
  61076. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  61077. var k = _a[_i];
  61078. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  61079. return Math.max(k, 3);
  61080. }
  61081. }
  61082. return Math.max(v, 3);
  61083. };
  61084. /**
  61085. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  61086. * @param x The point on the Gaussian distribution to sample.
  61087. * @return the value of the Gaussian function at x.
  61088. */
  61089. BlurPostProcess.prototype._gaussianWeight = function (x) {
  61090. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  61091. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  61092. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  61093. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  61094. // truncated at around 1.3% of peak strength.
  61095. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  61096. var sigma = (1 / 3);
  61097. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  61098. var exponent = -((x * x) / (2.0 * sigma * sigma));
  61099. var weight = (1.0 / denominator) * Math.exp(exponent);
  61100. return weight;
  61101. };
  61102. /**
  61103. * Generates a string that can be used as a floating point number in GLSL.
  61104. * @param x Value to print.
  61105. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  61106. * @return GLSL float string.
  61107. */
  61108. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  61109. if (decimalFigures === void 0) { decimalFigures = 8; }
  61110. return x.toFixed(decimalFigures).replace(/0+$/, '');
  61111. };
  61112. return BlurPostProcess;
  61113. }(BABYLON.PostProcess));
  61114. BABYLON.BlurPostProcess = BlurPostProcess;
  61115. })(BABYLON || (BABYLON = {}));
  61116. //# sourceMappingURL=babylon.blurPostProcess.js.map
  61117. var BABYLON;
  61118. (function (BABYLON) {
  61119. var Bone = /** @class */ (function (_super) {
  61120. __extends(Bone, _super);
  61121. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  61122. if (parentBone === void 0) { parentBone = null; }
  61123. if (localMatrix === void 0) { localMatrix = null; }
  61124. if (restPose === void 0) { restPose = null; }
  61125. if (baseMatrix === void 0) { baseMatrix = null; }
  61126. if (index === void 0) { index = null; }
  61127. var _this = _super.call(this, name, skeleton.getScene()) || this;
  61128. _this.name = name;
  61129. _this.children = new Array();
  61130. _this.animations = new Array();
  61131. // Set this value to map this bone to a different index in the transform matrices.
  61132. // Set this value to -1 to exclude the bone from the transform matrices.
  61133. _this._index = null;
  61134. _this._worldTransform = new BABYLON.Matrix();
  61135. _this._absoluteTransform = new BABYLON.Matrix();
  61136. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  61137. _this._scaleMatrix = BABYLON.Matrix.Identity();
  61138. _this._scaleVector = BABYLON.Vector3.One();
  61139. _this._negateScaleChildren = BABYLON.Vector3.One();
  61140. _this._scalingDeterminant = 1;
  61141. _this._skeleton = skeleton;
  61142. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  61143. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  61144. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  61145. _this._index = index;
  61146. skeleton.bones.push(_this);
  61147. _this.setParent(parentBone, false);
  61148. _this._updateDifferenceMatrix();
  61149. return _this;
  61150. }
  61151. Object.defineProperty(Bone.prototype, "_matrix", {
  61152. get: function () {
  61153. return this._localMatrix;
  61154. },
  61155. set: function (val) {
  61156. if (this._localMatrix) {
  61157. this._localMatrix.copyFrom(val);
  61158. }
  61159. else {
  61160. this._localMatrix = val;
  61161. }
  61162. },
  61163. enumerable: true,
  61164. configurable: true
  61165. });
  61166. // Members
  61167. Bone.prototype.getSkeleton = function () {
  61168. return this._skeleton;
  61169. };
  61170. Bone.prototype.getParent = function () {
  61171. return this._parent;
  61172. };
  61173. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  61174. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  61175. if (this._parent === parent) {
  61176. return;
  61177. }
  61178. if (this._parent) {
  61179. var index = this._parent.children.indexOf(this);
  61180. if (index !== -1) {
  61181. this._parent.children.splice(index, 1);
  61182. }
  61183. }
  61184. this._parent = parent;
  61185. if (this._parent) {
  61186. this._parent.children.push(this);
  61187. }
  61188. if (updateDifferenceMatrix) {
  61189. this._updateDifferenceMatrix();
  61190. }
  61191. };
  61192. Bone.prototype.getLocalMatrix = function () {
  61193. return this._localMatrix;
  61194. };
  61195. Bone.prototype.getBaseMatrix = function () {
  61196. return this._baseMatrix;
  61197. };
  61198. Bone.prototype.getRestPose = function () {
  61199. return this._restPose;
  61200. };
  61201. Bone.prototype.returnToRest = function () {
  61202. this.updateMatrix(this._restPose.clone());
  61203. };
  61204. Bone.prototype.getWorldMatrix = function () {
  61205. return this._worldTransform;
  61206. };
  61207. Bone.prototype.getInvertedAbsoluteTransform = function () {
  61208. return this._invertedAbsoluteTransform;
  61209. };
  61210. Bone.prototype.getAbsoluteTransform = function () {
  61211. return this._absoluteTransform;
  61212. };
  61213. Object.defineProperty(Bone.prototype, "position", {
  61214. // Properties (matches AbstractMesh properties)
  61215. get: function () {
  61216. return this.getPosition();
  61217. },
  61218. set: function (newPosition) {
  61219. this.setPosition(newPosition);
  61220. },
  61221. enumerable: true,
  61222. configurable: true
  61223. });
  61224. Object.defineProperty(Bone.prototype, "rotation", {
  61225. get: function () {
  61226. return this.getRotation();
  61227. },
  61228. set: function (newRotation) {
  61229. this.setRotation(newRotation);
  61230. },
  61231. enumerable: true,
  61232. configurable: true
  61233. });
  61234. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  61235. get: function () {
  61236. return this.getRotationQuaternion();
  61237. },
  61238. set: function (newRotation) {
  61239. this.setRotationQuaternion(newRotation);
  61240. },
  61241. enumerable: true,
  61242. configurable: true
  61243. });
  61244. Object.defineProperty(Bone.prototype, "scaling", {
  61245. get: function () {
  61246. return this.getScale();
  61247. },
  61248. set: function (newScaling) {
  61249. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  61250. },
  61251. enumerable: true,
  61252. configurable: true
  61253. });
  61254. // Methods
  61255. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  61256. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  61257. this._baseMatrix = matrix.clone();
  61258. this._localMatrix = matrix.clone();
  61259. this._skeleton._markAsDirty();
  61260. if (updateDifferenceMatrix) {
  61261. this._updateDifferenceMatrix();
  61262. }
  61263. };
  61264. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  61265. if (!rootMatrix) {
  61266. rootMatrix = this._baseMatrix;
  61267. }
  61268. if (this._parent) {
  61269. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  61270. }
  61271. else {
  61272. this._absoluteTransform.copyFrom(rootMatrix);
  61273. }
  61274. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  61275. for (var index = 0; index < this.children.length; index++) {
  61276. this.children[index]._updateDifferenceMatrix();
  61277. }
  61278. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  61279. };
  61280. Bone.prototype.markAsDirty = function () {
  61281. this._currentRenderId++;
  61282. this._skeleton._markAsDirty();
  61283. };
  61284. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  61285. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  61286. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  61287. // all animation may be coming from a library skeleton, so may need to create animation
  61288. if (this.animations.length === 0) {
  61289. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  61290. this.animations[0].setKeys([]);
  61291. }
  61292. // get animation info / verify there is such a range from the source bone
  61293. var sourceRange = source.animations[0].getRange(rangeName);
  61294. if (!sourceRange) {
  61295. return false;
  61296. }
  61297. var from = sourceRange.from;
  61298. var to = sourceRange.to;
  61299. var sourceKeys = source.animations[0].getKeys();
  61300. // rescaling prep
  61301. var sourceBoneLength = source.length;
  61302. var sourceParent = source.getParent();
  61303. var parent = this.getParent();
  61304. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  61305. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  61306. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  61307. var destKeys = this.animations[0].getKeys();
  61308. // loop vars declaration
  61309. var orig;
  61310. var origTranslation;
  61311. var mat;
  61312. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  61313. orig = sourceKeys[key];
  61314. if (orig.frame >= from && orig.frame <= to) {
  61315. if (rescaleAsRequired) {
  61316. mat = orig.value.clone();
  61317. // scale based on parent ratio, when bone has parent
  61318. if (parentScalingReqd) {
  61319. origTranslation = mat.getTranslation();
  61320. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  61321. // scale based on skeleton dimension ratio when root bone, and value is passed
  61322. }
  61323. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  61324. origTranslation = mat.getTranslation();
  61325. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  61326. // use original when root bone, and no data for skelDimensionsRatio
  61327. }
  61328. else {
  61329. mat = orig.value;
  61330. }
  61331. }
  61332. else {
  61333. mat = orig.value;
  61334. }
  61335. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  61336. }
  61337. }
  61338. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  61339. return true;
  61340. };
  61341. /**
  61342. * Translate the bone in local or world space.
  61343. * @param vec The amount to translate the bone.
  61344. * @param space The space that the translation is in.
  61345. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61346. */
  61347. Bone.prototype.translate = function (vec, space, mesh) {
  61348. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61349. var lm = this.getLocalMatrix();
  61350. if (space == BABYLON.Space.LOCAL) {
  61351. lm.m[12] += vec.x;
  61352. lm.m[13] += vec.y;
  61353. lm.m[14] += vec.z;
  61354. }
  61355. else {
  61356. var wm = null;
  61357. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61358. if (mesh) {
  61359. wm = mesh.getWorldMatrix();
  61360. }
  61361. this._skeleton.computeAbsoluteTransforms();
  61362. var tmat = Bone._tmpMats[0];
  61363. var tvec = Bone._tmpVecs[0];
  61364. if (this._parent) {
  61365. if (mesh && wm) {
  61366. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61367. tmat.multiplyToRef(wm, tmat);
  61368. }
  61369. else {
  61370. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61371. }
  61372. }
  61373. tmat.m[12] = 0;
  61374. tmat.m[13] = 0;
  61375. tmat.m[14] = 0;
  61376. tmat.invert();
  61377. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  61378. lm.m[12] += tvec.x;
  61379. lm.m[13] += tvec.y;
  61380. lm.m[14] += tvec.z;
  61381. }
  61382. this.markAsDirty();
  61383. };
  61384. /**
  61385. * Set the postion of the bone in local or world space.
  61386. * @param position The position to set the bone.
  61387. * @param space The space that the position is in.
  61388. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61389. */
  61390. Bone.prototype.setPosition = function (position, space, mesh) {
  61391. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61392. var lm = this.getLocalMatrix();
  61393. if (space == BABYLON.Space.LOCAL) {
  61394. lm.m[12] = position.x;
  61395. lm.m[13] = position.y;
  61396. lm.m[14] = position.z;
  61397. }
  61398. else {
  61399. var wm = null;
  61400. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61401. if (mesh) {
  61402. wm = mesh.getWorldMatrix();
  61403. }
  61404. this._skeleton.computeAbsoluteTransforms();
  61405. var tmat = Bone._tmpMats[0];
  61406. var vec = Bone._tmpVecs[0];
  61407. if (this._parent) {
  61408. if (mesh && wm) {
  61409. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61410. tmat.multiplyToRef(wm, tmat);
  61411. }
  61412. else {
  61413. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61414. }
  61415. }
  61416. tmat.invert();
  61417. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  61418. lm.m[12] = vec.x;
  61419. lm.m[13] = vec.y;
  61420. lm.m[14] = vec.z;
  61421. }
  61422. this.markAsDirty();
  61423. };
  61424. /**
  61425. * Set the absolute postion of the bone (world space).
  61426. * @param position The position to set the bone.
  61427. * @param mesh The mesh that this bone is attached to.
  61428. */
  61429. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  61430. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  61431. };
  61432. /**
  61433. * Set the scale of the bone on the x, y and z axes.
  61434. * @param x The scale of the bone on the x axis.
  61435. * @param x The scale of the bone on the y axis.
  61436. * @param z The scale of the bone on the z axis.
  61437. * @param scaleChildren Set this to true if children of the bone should be scaled.
  61438. */
  61439. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  61440. if (scaleChildren === void 0) { scaleChildren = false; }
  61441. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  61442. if (!scaleChildren) {
  61443. this._negateScaleChildren.x = 1 / x;
  61444. this._negateScaleChildren.y = 1 / y;
  61445. this._negateScaleChildren.z = 1 / z;
  61446. }
  61447. this._syncScaleVector();
  61448. }
  61449. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  61450. };
  61451. /**
  61452. * Scale the bone on the x, y and z axes.
  61453. * @param x The amount to scale the bone on the x axis.
  61454. * @param x The amount to scale the bone on the y axis.
  61455. * @param z The amount to scale the bone on the z axis.
  61456. * @param scaleChildren Set this to true if children of the bone should be scaled.
  61457. */
  61458. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  61459. if (scaleChildren === void 0) { scaleChildren = false; }
  61460. var locMat = this.getLocalMatrix();
  61461. var origLocMat = Bone._tmpMats[0];
  61462. origLocMat.copyFrom(locMat);
  61463. var origLocMatInv = Bone._tmpMats[1];
  61464. origLocMatInv.copyFrom(origLocMat);
  61465. origLocMatInv.invert();
  61466. var scaleMat = Bone._tmpMats[2];
  61467. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  61468. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  61469. this._scaleVector.x *= x;
  61470. this._scaleVector.y *= y;
  61471. this._scaleVector.z *= z;
  61472. locMat.multiplyToRef(origLocMatInv, locMat);
  61473. locMat.multiplyToRef(scaleMat, locMat);
  61474. locMat.multiplyToRef(origLocMat, locMat);
  61475. var parent = this.getParent();
  61476. if (parent) {
  61477. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  61478. }
  61479. else {
  61480. this.getAbsoluteTransform().copyFrom(locMat);
  61481. }
  61482. var len = this.children.length;
  61483. scaleMat.invert();
  61484. for (var i = 0; i < len; i++) {
  61485. var child = this.children[i];
  61486. var cm = child.getLocalMatrix();
  61487. cm.multiplyToRef(scaleMat, cm);
  61488. var lm = child.getLocalMatrix();
  61489. lm.m[12] *= x;
  61490. lm.m[13] *= y;
  61491. lm.m[14] *= z;
  61492. }
  61493. this.computeAbsoluteTransforms();
  61494. if (scaleChildren) {
  61495. for (var i = 0; i < len; i++) {
  61496. this.children[i].scale(x, y, z, scaleChildren);
  61497. }
  61498. }
  61499. this.markAsDirty();
  61500. };
  61501. /**
  61502. * Set the yaw, pitch, and roll of the bone in local or world space.
  61503. * @param yaw The rotation of the bone on the y axis.
  61504. * @param pitch The rotation of the bone on the x axis.
  61505. * @param roll The rotation of the bone on the z axis.
  61506. * @param space The space that the axes of rotation are in.
  61507. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61508. */
  61509. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  61510. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61511. var rotMat = Bone._tmpMats[0];
  61512. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  61513. var rotMatInv = Bone._tmpMats[1];
  61514. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61515. rotMatInv.multiplyToRef(rotMat, rotMat);
  61516. this._rotateWithMatrix(rotMat, space, mesh);
  61517. };
  61518. /**
  61519. * Rotate the bone on an axis in local or world space.
  61520. * @param axis The axis to rotate the bone on.
  61521. * @param amount The amount to rotate the bone.
  61522. * @param space The space that the axis is in.
  61523. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61524. */
  61525. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  61526. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61527. var rmat = Bone._tmpMats[0];
  61528. rmat.m[12] = 0;
  61529. rmat.m[13] = 0;
  61530. rmat.m[14] = 0;
  61531. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  61532. this._rotateWithMatrix(rmat, space, mesh);
  61533. };
  61534. /**
  61535. * Set the rotation of the bone to a particular axis angle in local or world space.
  61536. * @param axis The axis to rotate the bone on.
  61537. * @param angle The angle that the bone should be rotated to.
  61538. * @param space The space that the axis is in.
  61539. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61540. */
  61541. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  61542. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61543. var rotMat = Bone._tmpMats[0];
  61544. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  61545. var rotMatInv = Bone._tmpMats[1];
  61546. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61547. rotMatInv.multiplyToRef(rotMat, rotMat);
  61548. this._rotateWithMatrix(rotMat, space, mesh);
  61549. };
  61550. /**
  61551. * Set the euler rotation of the bone in local of world space.
  61552. * @param rotation The euler rotation that the bone should be set to.
  61553. * @param space The space that the rotation is in.
  61554. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61555. */
  61556. Bone.prototype.setRotation = function (rotation, space, mesh) {
  61557. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61558. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  61559. };
  61560. /**
  61561. * Set the quaternion rotation of the bone in local of world space.
  61562. * @param quat The quaternion rotation that the bone should be set to.
  61563. * @param space The space that the rotation is in.
  61564. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61565. */
  61566. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  61567. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61568. var rotMatInv = Bone._tmpMats[0];
  61569. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61570. var rotMat = Bone._tmpMats[1];
  61571. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  61572. rotMatInv.multiplyToRef(rotMat, rotMat);
  61573. this._rotateWithMatrix(rotMat, space, mesh);
  61574. };
  61575. /**
  61576. * Set the rotation matrix of the bone in local of world space.
  61577. * @param rotMat The rotation matrix that the bone should be set to.
  61578. * @param space The space that the rotation is in.
  61579. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61580. */
  61581. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  61582. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61583. var rotMatInv = Bone._tmpMats[0];
  61584. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61585. var rotMat2 = Bone._tmpMats[1];
  61586. rotMat2.copyFrom(rotMat);
  61587. rotMatInv.multiplyToRef(rotMat, rotMat2);
  61588. this._rotateWithMatrix(rotMat2, space, mesh);
  61589. };
  61590. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  61591. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61592. var lmat = this.getLocalMatrix();
  61593. var lx = lmat.m[12];
  61594. var ly = lmat.m[13];
  61595. var lz = lmat.m[14];
  61596. var parent = this.getParent();
  61597. var parentScale = Bone._tmpMats[3];
  61598. var parentScaleInv = Bone._tmpMats[4];
  61599. if (parent) {
  61600. if (space == BABYLON.Space.WORLD) {
  61601. if (mesh) {
  61602. parentScale.copyFrom(mesh.getWorldMatrix());
  61603. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  61604. }
  61605. else {
  61606. parentScale.copyFrom(parent.getAbsoluteTransform());
  61607. }
  61608. }
  61609. else {
  61610. parentScale = parent._scaleMatrix;
  61611. }
  61612. parentScaleInv.copyFrom(parentScale);
  61613. parentScaleInv.invert();
  61614. lmat.multiplyToRef(parentScale, lmat);
  61615. lmat.multiplyToRef(rmat, lmat);
  61616. lmat.multiplyToRef(parentScaleInv, lmat);
  61617. }
  61618. else {
  61619. if (space == BABYLON.Space.WORLD && mesh) {
  61620. parentScale.copyFrom(mesh.getWorldMatrix());
  61621. parentScaleInv.copyFrom(parentScale);
  61622. parentScaleInv.invert();
  61623. lmat.multiplyToRef(parentScale, lmat);
  61624. lmat.multiplyToRef(rmat, lmat);
  61625. lmat.multiplyToRef(parentScaleInv, lmat);
  61626. }
  61627. else {
  61628. lmat.multiplyToRef(rmat, lmat);
  61629. }
  61630. }
  61631. lmat.m[12] = lx;
  61632. lmat.m[13] = ly;
  61633. lmat.m[14] = lz;
  61634. this.computeAbsoluteTransforms();
  61635. this.markAsDirty();
  61636. };
  61637. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  61638. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61639. if (space == BABYLON.Space.WORLD) {
  61640. var scaleMatrix = Bone._tmpMats[2];
  61641. scaleMatrix.copyFrom(this._scaleMatrix);
  61642. rotMatInv.copyFrom(this.getAbsoluteTransform());
  61643. if (mesh) {
  61644. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  61645. var meshScale = Bone._tmpMats[3];
  61646. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  61647. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  61648. }
  61649. rotMatInv.invert();
  61650. scaleMatrix.m[0] *= this._scalingDeterminant;
  61651. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61652. }
  61653. else {
  61654. rotMatInv.copyFrom(this.getLocalMatrix());
  61655. rotMatInv.invert();
  61656. var scaleMatrix = Bone._tmpMats[2];
  61657. scaleMatrix.copyFrom(this._scaleMatrix);
  61658. if (this._parent) {
  61659. var pscaleMatrix = Bone._tmpMats[3];
  61660. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  61661. pscaleMatrix.invert();
  61662. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  61663. }
  61664. else {
  61665. scaleMatrix.m[0] *= this._scalingDeterminant;
  61666. }
  61667. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61668. }
  61669. };
  61670. /**
  61671. * Get the scale of the bone
  61672. * @returns the scale of the bone
  61673. */
  61674. Bone.prototype.getScale = function () {
  61675. return this._scaleVector.clone();
  61676. };
  61677. /**
  61678. * Copy the scale of the bone to a vector3.
  61679. * @param result The vector3 to copy the scale to
  61680. */
  61681. Bone.prototype.getScaleToRef = function (result) {
  61682. result.copyFrom(this._scaleVector);
  61683. };
  61684. /**
  61685. * Get the position of the bone in local or world space.
  61686. * @param space The space that the returned position is in.
  61687. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61688. * @returns The position of the bone
  61689. */
  61690. Bone.prototype.getPosition = function (space, mesh) {
  61691. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61692. if (mesh === void 0) { mesh = null; }
  61693. var pos = BABYLON.Vector3.Zero();
  61694. this.getPositionToRef(space, mesh, pos);
  61695. return pos;
  61696. };
  61697. /**
  61698. * Copy the position of the bone to a vector3 in local or world space.
  61699. * @param space The space that the returned position is in.
  61700. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61701. * @param result The vector3 to copy the position to.
  61702. */
  61703. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  61704. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61705. if (space == BABYLON.Space.LOCAL) {
  61706. var lm = this.getLocalMatrix();
  61707. result.x = lm.m[12];
  61708. result.y = lm.m[13];
  61709. result.z = lm.m[14];
  61710. }
  61711. else {
  61712. var wm = null;
  61713. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61714. if (mesh) {
  61715. wm = mesh.getWorldMatrix();
  61716. }
  61717. this._skeleton.computeAbsoluteTransforms();
  61718. var tmat = Bone._tmpMats[0];
  61719. if (mesh && wm) {
  61720. tmat.copyFrom(this.getAbsoluteTransform());
  61721. tmat.multiplyToRef(wm, tmat);
  61722. }
  61723. else {
  61724. tmat = this.getAbsoluteTransform();
  61725. }
  61726. result.x = tmat.m[12];
  61727. result.y = tmat.m[13];
  61728. result.z = tmat.m[14];
  61729. }
  61730. };
  61731. /**
  61732. * Get the absolute position of the bone (world space).
  61733. * @param mesh The mesh that this bone is attached to.
  61734. * @returns The absolute position of the bone
  61735. */
  61736. Bone.prototype.getAbsolutePosition = function (mesh) {
  61737. if (mesh === void 0) { mesh = null; }
  61738. var pos = BABYLON.Vector3.Zero();
  61739. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  61740. return pos;
  61741. };
  61742. /**
  61743. * Copy the absolute position of the bone (world space) to the result param.
  61744. * @param mesh The mesh that this bone is attached to.
  61745. * @param result The vector3 to copy the absolute position to.
  61746. */
  61747. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  61748. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  61749. };
  61750. /**
  61751. * Compute the absolute transforms of this bone and its children.
  61752. */
  61753. Bone.prototype.computeAbsoluteTransforms = function () {
  61754. if (this._parent) {
  61755. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  61756. }
  61757. else {
  61758. this._absoluteTransform.copyFrom(this._localMatrix);
  61759. var poseMatrix = this._skeleton.getPoseMatrix();
  61760. if (poseMatrix) {
  61761. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  61762. }
  61763. }
  61764. var children = this.children;
  61765. var len = children.length;
  61766. for (var i = 0; i < len; i++) {
  61767. children[i].computeAbsoluteTransforms();
  61768. }
  61769. };
  61770. Bone.prototype._syncScaleVector = function () {
  61771. var lm = this.getLocalMatrix();
  61772. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  61773. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  61774. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  61775. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  61776. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  61777. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  61778. this._scaleVector.x = xs * Math.sqrt(xsq);
  61779. this._scaleVector.y = ys * Math.sqrt(ysq);
  61780. this._scaleVector.z = zs * Math.sqrt(zsq);
  61781. if (this._parent) {
  61782. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  61783. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  61784. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  61785. }
  61786. 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);
  61787. };
  61788. /**
  61789. * Get the world direction from an axis that is in the local space of the bone.
  61790. * @param localAxis The local direction that is used to compute the world direction.
  61791. * @param mesh The mesh that this bone is attached to.
  61792. * @returns The world direction
  61793. */
  61794. Bone.prototype.getDirection = function (localAxis, mesh) {
  61795. if (mesh === void 0) { mesh = null; }
  61796. var result = BABYLON.Vector3.Zero();
  61797. this.getDirectionToRef(localAxis, mesh, result);
  61798. return result;
  61799. };
  61800. /**
  61801. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  61802. * @param localAxis The local direction that is used to compute the world direction.
  61803. * @param mesh The mesh that this bone is attached to.
  61804. * @param result The vector3 that the world direction will be copied to.
  61805. */
  61806. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  61807. if (mesh === void 0) { mesh = null; }
  61808. var wm = null;
  61809. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61810. if (mesh) {
  61811. wm = mesh.getWorldMatrix();
  61812. }
  61813. this._skeleton.computeAbsoluteTransforms();
  61814. var mat = Bone._tmpMats[0];
  61815. mat.copyFrom(this.getAbsoluteTransform());
  61816. if (mesh && wm) {
  61817. mat.multiplyToRef(wm, mat);
  61818. }
  61819. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  61820. result.normalize();
  61821. };
  61822. /**
  61823. * Get the euler rotation of the bone in local or world space.
  61824. * @param space The space that the rotation should be in.
  61825. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61826. * @returns The euler rotation
  61827. */
  61828. Bone.prototype.getRotation = function (space, mesh) {
  61829. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61830. if (mesh === void 0) { mesh = null; }
  61831. var result = BABYLON.Vector3.Zero();
  61832. this.getRotationToRef(space, mesh, result);
  61833. return result;
  61834. };
  61835. /**
  61836. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  61837. * @param space The space that the rotation should be in.
  61838. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61839. * @param result The vector3 that the rotation should be copied to.
  61840. */
  61841. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  61842. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61843. if (mesh === void 0) { mesh = null; }
  61844. var quat = Bone._tmpQuat;
  61845. this.getRotationQuaternionToRef(space, mesh, quat);
  61846. quat.toEulerAnglesToRef(result);
  61847. };
  61848. /**
  61849. * Get the quaternion rotation of the bone in either local or world space.
  61850. * @param space The space that the rotation should be in.
  61851. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61852. * @returns The quaternion rotation
  61853. */
  61854. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  61855. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61856. if (mesh === void 0) { mesh = null; }
  61857. var result = BABYLON.Quaternion.Identity();
  61858. this.getRotationQuaternionToRef(space, mesh, result);
  61859. return result;
  61860. };
  61861. /**
  61862. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  61863. * @param space The space that the rotation should be in.
  61864. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61865. * @param result The quaternion that the rotation should be copied to.
  61866. */
  61867. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  61868. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61869. if (mesh === void 0) { mesh = null; }
  61870. if (space == BABYLON.Space.LOCAL) {
  61871. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61872. }
  61873. else {
  61874. var mat = Bone._tmpMats[0];
  61875. var amat = this.getAbsoluteTransform();
  61876. if (mesh) {
  61877. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61878. }
  61879. else {
  61880. mat.copyFrom(amat);
  61881. }
  61882. mat.m[0] *= this._scalingDeterminant;
  61883. mat.m[1] *= this._scalingDeterminant;
  61884. mat.m[2] *= this._scalingDeterminant;
  61885. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61886. }
  61887. };
  61888. /**
  61889. * Get the rotation matrix of the bone in local or world space.
  61890. * @param space The space that the rotation should be in.
  61891. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61892. * @returns The rotation matrix
  61893. */
  61894. Bone.prototype.getRotationMatrix = function (space, mesh) {
  61895. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61896. var result = BABYLON.Matrix.Identity();
  61897. this.getRotationMatrixToRef(space, mesh, result);
  61898. return result;
  61899. };
  61900. /**
  61901. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  61902. * @param space The space that the rotation should be in.
  61903. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61904. * @param result The quaternion that the rotation should be copied to.
  61905. */
  61906. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  61907. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61908. if (space == BABYLON.Space.LOCAL) {
  61909. this.getLocalMatrix().getRotationMatrixToRef(result);
  61910. }
  61911. else {
  61912. var mat = Bone._tmpMats[0];
  61913. var amat = this.getAbsoluteTransform();
  61914. if (mesh) {
  61915. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61916. }
  61917. else {
  61918. mat.copyFrom(amat);
  61919. }
  61920. mat.m[0] *= this._scalingDeterminant;
  61921. mat.m[1] *= this._scalingDeterminant;
  61922. mat.m[2] *= this._scalingDeterminant;
  61923. mat.getRotationMatrixToRef(result);
  61924. }
  61925. };
  61926. /**
  61927. * Get the world position of a point that is in the local space of the bone.
  61928. * @param position The local position
  61929. * @param mesh The mesh that this bone is attached to.
  61930. * @returns The world position
  61931. */
  61932. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  61933. if (mesh === void 0) { mesh = null; }
  61934. var result = BABYLON.Vector3.Zero();
  61935. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  61936. return result;
  61937. };
  61938. /**
  61939. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  61940. * @param position The local position
  61941. * @param mesh The mesh that this bone is attached to.
  61942. * @param result The vector3 that the world position should be copied to.
  61943. */
  61944. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  61945. if (mesh === void 0) { mesh = null; }
  61946. var wm = null;
  61947. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61948. if (mesh) {
  61949. wm = mesh.getWorldMatrix();
  61950. }
  61951. this._skeleton.computeAbsoluteTransforms();
  61952. var tmat = Bone._tmpMats[0];
  61953. if (mesh && wm) {
  61954. tmat.copyFrom(this.getAbsoluteTransform());
  61955. tmat.multiplyToRef(wm, tmat);
  61956. }
  61957. else {
  61958. tmat = this.getAbsoluteTransform();
  61959. }
  61960. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61961. };
  61962. /**
  61963. * Get the local position of a point that is in world space.
  61964. * @param position The world position
  61965. * @param mesh The mesh that this bone is attached to.
  61966. * @returns The local position
  61967. */
  61968. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  61969. if (mesh === void 0) { mesh = null; }
  61970. var result = BABYLON.Vector3.Zero();
  61971. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  61972. return result;
  61973. };
  61974. /**
  61975. * Get the local position of a point that is in world space and copy it to the result param.
  61976. * @param position The world position
  61977. * @param mesh The mesh that this bone is attached to.
  61978. * @param result The vector3 that the local position should be copied to.
  61979. */
  61980. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  61981. if (mesh === void 0) { mesh = null; }
  61982. var wm = null;
  61983. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61984. if (mesh) {
  61985. wm = mesh.getWorldMatrix();
  61986. }
  61987. this._skeleton.computeAbsoluteTransforms();
  61988. var tmat = Bone._tmpMats[0];
  61989. tmat.copyFrom(this.getAbsoluteTransform());
  61990. if (mesh && wm) {
  61991. tmat.multiplyToRef(wm, tmat);
  61992. }
  61993. tmat.invert();
  61994. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61995. };
  61996. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61997. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  61998. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61999. return Bone;
  62000. }(BABYLON.Node));
  62001. BABYLON.Bone = Bone;
  62002. })(BABYLON || (BABYLON = {}));
  62003. //# sourceMappingURL=babylon.bone.js.map
  62004. var BABYLON;
  62005. (function (BABYLON) {
  62006. var BoneIKController = /** @class */ (function () {
  62007. function BoneIKController(mesh, bone, options) {
  62008. this.targetPosition = BABYLON.Vector3.Zero();
  62009. this.poleTargetPosition = BABYLON.Vector3.Zero();
  62010. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  62011. this.poleAngle = 0;
  62012. this.slerpAmount = 1;
  62013. this._bone1Quat = BABYLON.Quaternion.Identity();
  62014. this._bone1Mat = BABYLON.Matrix.Identity();
  62015. this._bone2Ang = Math.PI;
  62016. this._maxAngle = Math.PI;
  62017. this._rightHandedSystem = false;
  62018. this._bendAxis = BABYLON.Vector3.Right();
  62019. this._slerping = false;
  62020. this._adjustRoll = 0;
  62021. this._bone2 = bone;
  62022. this._bone1 = bone.getParent();
  62023. if (!this._bone1) {
  62024. return;
  62025. }
  62026. this.mesh = mesh;
  62027. var bonePos = bone.getPosition();
  62028. if (bone.getAbsoluteTransform().determinant() > 0) {
  62029. this._rightHandedSystem = true;
  62030. this._bendAxis.x = 0;
  62031. this._bendAxis.y = 0;
  62032. this._bendAxis.z = -1;
  62033. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  62034. this._adjustRoll = Math.PI * .5;
  62035. this._bendAxis.z = 1;
  62036. }
  62037. }
  62038. if (this._bone1.length) {
  62039. var boneScale1 = this._bone1.getScale();
  62040. var boneScale2 = this._bone2.getScale();
  62041. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  62042. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  62043. }
  62044. else if (this._bone1.children[0]) {
  62045. mesh.computeWorldMatrix(true);
  62046. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  62047. var pos2 = this._bone2.getAbsolutePosition(mesh);
  62048. var pos3 = this._bone1.getAbsolutePosition(mesh);
  62049. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  62050. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  62051. }
  62052. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  62053. this.maxAngle = Math.PI;
  62054. if (options) {
  62055. if (options.targetMesh) {
  62056. this.targetMesh = options.targetMesh;
  62057. this.targetMesh.computeWorldMatrix(true);
  62058. }
  62059. if (options.poleTargetMesh) {
  62060. this.poleTargetMesh = options.poleTargetMesh;
  62061. this.poleTargetMesh.computeWorldMatrix(true);
  62062. }
  62063. else if (options.poleTargetBone) {
  62064. this.poleTargetBone = options.poleTargetBone;
  62065. }
  62066. else if (this._bone1.getParent()) {
  62067. this.poleTargetBone = this._bone1.getParent();
  62068. }
  62069. if (options.poleTargetLocalOffset) {
  62070. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  62071. }
  62072. if (options.poleAngle) {
  62073. this.poleAngle = options.poleAngle;
  62074. }
  62075. if (options.bendAxis) {
  62076. this._bendAxis.copyFrom(options.bendAxis);
  62077. }
  62078. if (options.maxAngle) {
  62079. this.maxAngle = options.maxAngle;
  62080. }
  62081. if (options.slerpAmount) {
  62082. this.slerpAmount = options.slerpAmount;
  62083. }
  62084. }
  62085. }
  62086. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  62087. get: function () {
  62088. return this._maxAngle;
  62089. },
  62090. set: function (value) {
  62091. this._setMaxAngle(value);
  62092. },
  62093. enumerable: true,
  62094. configurable: true
  62095. });
  62096. BoneIKController.prototype._setMaxAngle = function (ang) {
  62097. if (ang < 0) {
  62098. ang = 0;
  62099. }
  62100. if (ang > Math.PI || ang == undefined) {
  62101. ang = Math.PI;
  62102. }
  62103. this._maxAngle = ang;
  62104. var a = this._bone1Length;
  62105. var b = this._bone2Length;
  62106. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  62107. };
  62108. BoneIKController.prototype.update = function () {
  62109. var bone1 = this._bone1;
  62110. if (!bone1) {
  62111. return;
  62112. }
  62113. var target = this.targetPosition;
  62114. var poleTarget = this.poleTargetPosition;
  62115. var mat1 = BoneIKController._tmpMats[0];
  62116. var mat2 = BoneIKController._tmpMats[1];
  62117. if (this.targetMesh) {
  62118. target.copyFrom(this.targetMesh.getAbsolutePosition());
  62119. }
  62120. if (this.poleTargetBone) {
  62121. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  62122. }
  62123. else if (this.poleTargetMesh) {
  62124. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  62125. }
  62126. var bonePos = BoneIKController._tmpVecs[0];
  62127. var zaxis = BoneIKController._tmpVecs[1];
  62128. var xaxis = BoneIKController._tmpVecs[2];
  62129. var yaxis = BoneIKController._tmpVecs[3];
  62130. var upAxis = BoneIKController._tmpVecs[4];
  62131. var _tmpQuat = BoneIKController._tmpQuat;
  62132. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  62133. poleTarget.subtractToRef(bonePos, upAxis);
  62134. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  62135. upAxis.y = 1;
  62136. }
  62137. else {
  62138. upAxis.normalize();
  62139. }
  62140. target.subtractToRef(bonePos, yaxis);
  62141. yaxis.normalize();
  62142. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  62143. zaxis.normalize();
  62144. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  62145. xaxis.normalize();
  62146. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  62147. var a = this._bone1Length;
  62148. var b = this._bone2Length;
  62149. var c = BABYLON.Vector3.Distance(bonePos, target);
  62150. if (this._maxReach > 0) {
  62151. c = Math.min(this._maxReach, c);
  62152. }
  62153. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  62154. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  62155. if (acosa > 1) {
  62156. acosa = 1;
  62157. }
  62158. if (acosb > 1) {
  62159. acosb = 1;
  62160. }
  62161. if (acosa < -1) {
  62162. acosa = -1;
  62163. }
  62164. if (acosb < -1) {
  62165. acosb = -1;
  62166. }
  62167. var angA = Math.acos(acosa);
  62168. var angB = Math.acos(acosb);
  62169. var angC = -angA - angB;
  62170. if (this._rightHandedSystem) {
  62171. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  62172. mat2.multiplyToRef(mat1, mat1);
  62173. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  62174. mat2.multiplyToRef(mat1, mat1);
  62175. }
  62176. else {
  62177. var _tmpVec = BoneIKController._tmpVecs[5];
  62178. _tmpVec.copyFrom(this._bendAxis);
  62179. _tmpVec.x *= -1;
  62180. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  62181. mat2.multiplyToRef(mat1, mat1);
  62182. }
  62183. if (this.poleAngle) {
  62184. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  62185. mat1.multiplyToRef(mat2, mat1);
  62186. }
  62187. if (this._bone1) {
  62188. if (this.slerpAmount < 1) {
  62189. if (!this._slerping) {
  62190. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  62191. }
  62192. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  62193. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  62194. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  62195. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  62196. this._slerping = true;
  62197. }
  62198. else {
  62199. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  62200. this._bone1Mat.copyFrom(mat1);
  62201. this._slerping = false;
  62202. }
  62203. }
  62204. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  62205. this._bone2Ang = angC;
  62206. };
  62207. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62208. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  62209. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62210. return BoneIKController;
  62211. }());
  62212. BABYLON.BoneIKController = BoneIKController;
  62213. })(BABYLON || (BABYLON = {}));
  62214. //# sourceMappingURL=babylon.boneIKController.js.map
  62215. var BABYLON;
  62216. (function (BABYLON) {
  62217. var BoneLookController = /** @class */ (function () {
  62218. /**
  62219. * Create a BoneLookController
  62220. * @param mesh the mesh that the bone belongs to
  62221. * @param bone the bone that will be looking to the target
  62222. * @param target the target Vector3 to look at
  62223. * @param settings optional settings:
  62224. * - maxYaw: the maximum angle the bone will yaw to
  62225. * - minYaw: the minimum angle the bone will yaw to
  62226. * - maxPitch: the maximum angle the bone will pitch to
  62227. * - minPitch: the minimum angle the bone will yaw to
  62228. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  62229. * - upAxis: the up axis of the coordinate system
  62230. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  62231. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  62232. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  62233. * - adjustYaw: used to make an adjustment to the yaw of the bone
  62234. * - adjustPitch: used to make an adjustment to the pitch of the bone
  62235. * - adjustRoll: used to make an adjustment to the roll of the bone
  62236. **/
  62237. function BoneLookController(mesh, bone, target, options) {
  62238. /**
  62239. * The up axis of the coordinate system that is used when the bone is rotated.
  62240. */
  62241. this.upAxis = BABYLON.Vector3.Up();
  62242. /**
  62243. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  62244. */
  62245. this.upAxisSpace = BABYLON.Space.LOCAL;
  62246. /**
  62247. * Used to make an adjustment to the yaw of the bone.
  62248. */
  62249. this.adjustYaw = 0;
  62250. /**
  62251. * Used to make an adjustment to the pitch of the bone.
  62252. */
  62253. this.adjustPitch = 0;
  62254. /**
  62255. * Used to make an adjustment to the roll of the bone.
  62256. */
  62257. this.adjustRoll = 0;
  62258. /**
  62259. * 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).
  62260. */
  62261. this.slerpAmount = 1;
  62262. this._boneQuat = BABYLON.Quaternion.Identity();
  62263. this._slerping = false;
  62264. this._firstFrameSkipped = false;
  62265. this._fowardAxis = BABYLON.Vector3.Forward();
  62266. this.mesh = mesh;
  62267. this.bone = bone;
  62268. this.target = target;
  62269. if (options) {
  62270. if (options.adjustYaw) {
  62271. this.adjustYaw = options.adjustYaw;
  62272. }
  62273. if (options.adjustPitch) {
  62274. this.adjustPitch = options.adjustPitch;
  62275. }
  62276. if (options.adjustRoll) {
  62277. this.adjustRoll = options.adjustRoll;
  62278. }
  62279. if (options.maxYaw != null) {
  62280. this.maxYaw = options.maxYaw;
  62281. }
  62282. else {
  62283. this.maxYaw = Math.PI;
  62284. }
  62285. if (options.minYaw != null) {
  62286. this.minYaw = options.minYaw;
  62287. }
  62288. else {
  62289. this.minYaw = -Math.PI;
  62290. }
  62291. if (options.maxPitch != null) {
  62292. this.maxPitch = options.maxPitch;
  62293. }
  62294. else {
  62295. this.maxPitch = Math.PI;
  62296. }
  62297. if (options.minPitch != null) {
  62298. this.minPitch = options.minPitch;
  62299. }
  62300. else {
  62301. this.minPitch = -Math.PI;
  62302. }
  62303. if (options.slerpAmount != null) {
  62304. this.slerpAmount = options.slerpAmount;
  62305. }
  62306. if (options.upAxis != null) {
  62307. this.upAxis = options.upAxis;
  62308. }
  62309. if (options.upAxisSpace != null) {
  62310. this.upAxisSpace = options.upAxisSpace;
  62311. }
  62312. if (options.yawAxis != null || options.pitchAxis != null) {
  62313. var newYawAxis = BABYLON.Axis.Y;
  62314. var newPitchAxis = BABYLON.Axis.X;
  62315. if (options.yawAxis != null) {
  62316. newYawAxis = options.yawAxis.clone();
  62317. newYawAxis.normalize();
  62318. }
  62319. if (options.pitchAxis != null) {
  62320. newPitchAxis = options.pitchAxis.clone();
  62321. newPitchAxis.normalize();
  62322. }
  62323. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  62324. this._transformYawPitch = BABYLON.Matrix.Identity();
  62325. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  62326. this._transformYawPitchInv = this._transformYawPitch.clone();
  62327. this._transformYawPitch.invert();
  62328. }
  62329. }
  62330. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  62331. this.upAxisSpace = BABYLON.Space.LOCAL;
  62332. }
  62333. }
  62334. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  62335. /**
  62336. * Get/set the minimum yaw angle that the bone can look to.
  62337. */
  62338. get: function () {
  62339. return this._minYaw;
  62340. },
  62341. set: function (value) {
  62342. this._minYaw = value;
  62343. this._minYawSin = Math.sin(value);
  62344. this._minYawCos = Math.cos(value);
  62345. if (this._maxYaw != null) {
  62346. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  62347. this._yawRange = this._maxYaw - this._minYaw;
  62348. }
  62349. },
  62350. enumerable: true,
  62351. configurable: true
  62352. });
  62353. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  62354. /**
  62355. * Get/set the maximum yaw angle that the bone can look to.
  62356. */
  62357. get: function () {
  62358. return this._maxYaw;
  62359. },
  62360. set: function (value) {
  62361. this._maxYaw = value;
  62362. this._maxYawSin = Math.sin(value);
  62363. this._maxYawCos = Math.cos(value);
  62364. if (this._minYaw != null) {
  62365. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  62366. this._yawRange = this._maxYaw - this._minYaw;
  62367. }
  62368. },
  62369. enumerable: true,
  62370. configurable: true
  62371. });
  62372. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  62373. /**
  62374. * Get/set the minimum pitch angle that the bone can look to.
  62375. */
  62376. get: function () {
  62377. return this._minPitch;
  62378. },
  62379. set: function (value) {
  62380. this._minPitch = value;
  62381. this._minPitchTan = Math.tan(value);
  62382. },
  62383. enumerable: true,
  62384. configurable: true
  62385. });
  62386. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  62387. /**
  62388. * Get/set the maximum pitch angle that the bone can look to.
  62389. */
  62390. get: function () {
  62391. return this._maxPitch;
  62392. },
  62393. set: function (value) {
  62394. this._maxPitch = value;
  62395. this._maxPitchTan = Math.tan(value);
  62396. },
  62397. enumerable: true,
  62398. configurable: true
  62399. });
  62400. /**
  62401. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  62402. */
  62403. BoneLookController.prototype.update = function () {
  62404. //skip the first frame when slerping so that the mesh rotation is correct
  62405. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  62406. this._firstFrameSkipped = true;
  62407. return;
  62408. }
  62409. var bone = this.bone;
  62410. var bonePos = BoneLookController._tmpVecs[0];
  62411. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  62412. var target = this.target;
  62413. var _tmpMat1 = BoneLookController._tmpMats[0];
  62414. var _tmpMat2 = BoneLookController._tmpMats[1];
  62415. var mesh = this.mesh;
  62416. var parentBone = bone.getParent();
  62417. var upAxis = BoneLookController._tmpVecs[1];
  62418. upAxis.copyFrom(this.upAxis);
  62419. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  62420. if (this._transformYawPitch) {
  62421. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  62422. }
  62423. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  62424. }
  62425. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  62426. mesh.getDirectionToRef(upAxis, upAxis);
  62427. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  62428. upAxis.normalize();
  62429. }
  62430. }
  62431. var checkYaw = false;
  62432. var checkPitch = false;
  62433. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  62434. checkYaw = true;
  62435. }
  62436. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  62437. checkPitch = true;
  62438. }
  62439. if (checkYaw || checkPitch) {
  62440. var spaceMat = BoneLookController._tmpMats[2];
  62441. var spaceMatInv = BoneLookController._tmpMats[3];
  62442. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  62443. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  62444. }
  62445. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  62446. spaceMat.copyFrom(mesh.getWorldMatrix());
  62447. }
  62448. else {
  62449. var forwardAxis = BoneLookController._tmpVecs[2];
  62450. forwardAxis.copyFrom(this._fowardAxis);
  62451. if (this._transformYawPitch) {
  62452. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  62453. }
  62454. if (parentBone) {
  62455. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  62456. }
  62457. else {
  62458. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  62459. }
  62460. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  62461. rightAxis.normalize();
  62462. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  62463. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  62464. }
  62465. spaceMat.invertToRef(spaceMatInv);
  62466. var xzlen = null;
  62467. if (checkPitch) {
  62468. var localTarget = BoneLookController._tmpVecs[3];
  62469. target.subtractToRef(bonePos, localTarget);
  62470. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  62471. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62472. var pitch = Math.atan2(localTarget.y, xzlen);
  62473. var newPitch = pitch;
  62474. if (pitch > this._maxPitch) {
  62475. localTarget.y = this._maxPitchTan * xzlen;
  62476. newPitch = this._maxPitch;
  62477. }
  62478. else if (pitch < this._minPitch) {
  62479. localTarget.y = this._minPitchTan * xzlen;
  62480. newPitch = this._minPitch;
  62481. }
  62482. if (pitch != newPitch) {
  62483. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  62484. localTarget.addInPlace(bonePos);
  62485. target = localTarget;
  62486. }
  62487. }
  62488. if (checkYaw) {
  62489. var localTarget = BoneLookController._tmpVecs[4];
  62490. target.subtractToRef(bonePos, localTarget);
  62491. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  62492. var yaw = Math.atan2(localTarget.x, localTarget.z);
  62493. var newYaw = yaw;
  62494. if (yaw > this._maxYaw || yaw < this._minYaw) {
  62495. if (xzlen == null) {
  62496. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62497. }
  62498. if (this._yawRange > Math.PI) {
  62499. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  62500. localTarget.z = this._maxYawCos * xzlen;
  62501. localTarget.x = this._maxYawSin * xzlen;
  62502. newYaw = this._maxYaw;
  62503. }
  62504. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  62505. localTarget.z = this._minYawCos * xzlen;
  62506. localTarget.x = this._minYawSin * xzlen;
  62507. newYaw = this._minYaw;
  62508. }
  62509. }
  62510. else {
  62511. if (yaw > this._maxYaw) {
  62512. localTarget.z = this._maxYawCos * xzlen;
  62513. localTarget.x = this._maxYawSin * xzlen;
  62514. newYaw = this._maxYaw;
  62515. }
  62516. else if (yaw < this._minYaw) {
  62517. localTarget.z = this._minYawCos * xzlen;
  62518. localTarget.x = this._minYawSin * xzlen;
  62519. newYaw = this._minYaw;
  62520. }
  62521. }
  62522. }
  62523. if (this._slerping && this._yawRange > Math.PI) {
  62524. //are we going to be crossing into the min/max region?
  62525. var boneFwd = BoneLookController._tmpVecs[8];
  62526. boneFwd.copyFrom(BABYLON.Axis.Z);
  62527. if (this._transformYawPitch) {
  62528. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  62529. }
  62530. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  62531. this._boneQuat.toRotationMatrix(boneRotMat);
  62532. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  62533. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  62534. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  62535. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  62536. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  62537. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  62538. if (angBtwTar > angBtwMidYaw) {
  62539. if (xzlen == null) {
  62540. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62541. }
  62542. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  62543. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  62544. if (angBtwMin < angBtwMax) {
  62545. newYaw = boneYaw + Math.PI * .75;
  62546. localTarget.z = Math.cos(newYaw) * xzlen;
  62547. localTarget.x = Math.sin(newYaw) * xzlen;
  62548. }
  62549. else {
  62550. newYaw = boneYaw - Math.PI * .75;
  62551. localTarget.z = Math.cos(newYaw) * xzlen;
  62552. localTarget.x = Math.sin(newYaw) * xzlen;
  62553. }
  62554. }
  62555. }
  62556. if (yaw != newYaw) {
  62557. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  62558. localTarget.addInPlace(bonePos);
  62559. target = localTarget;
  62560. }
  62561. }
  62562. }
  62563. var zaxis = BoneLookController._tmpVecs[5];
  62564. var xaxis = BoneLookController._tmpVecs[6];
  62565. var yaxis = BoneLookController._tmpVecs[7];
  62566. var _tmpQuat = BoneLookController._tmpQuat;
  62567. target.subtractToRef(bonePos, zaxis);
  62568. zaxis.normalize();
  62569. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  62570. xaxis.normalize();
  62571. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  62572. yaxis.normalize();
  62573. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  62574. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  62575. return;
  62576. }
  62577. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  62578. return;
  62579. }
  62580. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  62581. return;
  62582. }
  62583. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  62584. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  62585. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  62586. }
  62587. if (this.slerpAmount < 1) {
  62588. if (!this._slerping) {
  62589. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  62590. }
  62591. if (this._transformYawPitch) {
  62592. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  62593. }
  62594. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  62595. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  62596. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  62597. this._slerping = true;
  62598. }
  62599. else {
  62600. if (this._transformYawPitch) {
  62601. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  62602. }
  62603. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  62604. this._slerping = false;
  62605. }
  62606. };
  62607. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  62608. var angDiff = ang2 - ang1;
  62609. angDiff %= Math.PI * 2;
  62610. if (angDiff > Math.PI) {
  62611. angDiff -= Math.PI * 2;
  62612. }
  62613. else if (angDiff < -Math.PI) {
  62614. angDiff += Math.PI * 2;
  62615. }
  62616. return angDiff;
  62617. };
  62618. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  62619. ang1 %= (2 * Math.PI);
  62620. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  62621. ang2 %= (2 * Math.PI);
  62622. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  62623. var ab = 0;
  62624. if (ang1 < ang2) {
  62625. ab = ang2 - ang1;
  62626. }
  62627. else {
  62628. ab = ang1 - ang2;
  62629. }
  62630. if (ab > Math.PI) {
  62631. ab = Math.PI * 2 - ab;
  62632. }
  62633. return ab;
  62634. };
  62635. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  62636. ang %= (2 * Math.PI);
  62637. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  62638. ang1 %= (2 * Math.PI);
  62639. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  62640. ang2 %= (2 * Math.PI);
  62641. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  62642. if (ang1 < ang2) {
  62643. if (ang > ang1 && ang < ang2) {
  62644. return true;
  62645. }
  62646. }
  62647. else {
  62648. if (ang > ang2 && ang < ang1) {
  62649. return true;
  62650. }
  62651. }
  62652. return false;
  62653. };
  62654. 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()];
  62655. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  62656. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62657. return BoneLookController;
  62658. }());
  62659. BABYLON.BoneLookController = BoneLookController;
  62660. })(BABYLON || (BABYLON = {}));
  62661. //# sourceMappingURL=babylon.boneLookController.js.map
  62662. var BABYLON;
  62663. (function (BABYLON) {
  62664. var Skeleton = /** @class */ (function () {
  62665. function Skeleton(name, id, scene) {
  62666. this.name = name;
  62667. this.id = id;
  62668. this.bones = new Array();
  62669. this.needInitialSkinMatrix = false;
  62670. this._isDirty = true;
  62671. this._meshesWithPoseMatrix = new Array();
  62672. this._identity = BABYLON.Matrix.Identity();
  62673. this._ranges = {};
  62674. this._lastAbsoluteTransformsUpdateId = -1;
  62675. // Events
  62676. /**
  62677. * An event triggered before computing the skeleton's matrices
  62678. * @type {BABYLON.Observable}
  62679. */
  62680. this.onBeforeComputeObservable = new BABYLON.Observable();
  62681. this.bones = [];
  62682. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62683. scene.skeletons.push(this);
  62684. //make sure it will recalculate the matrix next time prepare is called.
  62685. this._isDirty = true;
  62686. }
  62687. // Members
  62688. Skeleton.prototype.getTransformMatrices = function (mesh) {
  62689. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  62690. return mesh._bonesTransformMatrices;
  62691. }
  62692. if (!this._transformMatrices) {
  62693. this.prepare();
  62694. }
  62695. return this._transformMatrices;
  62696. };
  62697. Skeleton.prototype.getScene = function () {
  62698. return this._scene;
  62699. };
  62700. // Methods
  62701. /**
  62702. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  62703. */
  62704. Skeleton.prototype.toString = function (fullDetails) {
  62705. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  62706. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  62707. if (fullDetails) {
  62708. ret += ", Ranges: {";
  62709. var first = true;
  62710. for (var name_1 in this._ranges) {
  62711. if (first) {
  62712. ret += ", ";
  62713. first = false;
  62714. }
  62715. ret += name_1;
  62716. }
  62717. ret += "}";
  62718. }
  62719. return ret;
  62720. };
  62721. /**
  62722. * Get bone's index searching by name
  62723. * @param {string} name is bone's name to search for
  62724. * @return {number} Indice of the bone. Returns -1 if not found
  62725. */
  62726. Skeleton.prototype.getBoneIndexByName = function (name) {
  62727. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  62728. if (this.bones[boneIndex].name === name) {
  62729. return boneIndex;
  62730. }
  62731. }
  62732. return -1;
  62733. };
  62734. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  62735. // check name not already in use
  62736. if (!this._ranges[name]) {
  62737. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  62738. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62739. if (this.bones[i].animations[0]) {
  62740. this.bones[i].animations[0].createRange(name, from, to);
  62741. }
  62742. }
  62743. }
  62744. };
  62745. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  62746. if (deleteFrames === void 0) { deleteFrames = true; }
  62747. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62748. if (this.bones[i].animations[0]) {
  62749. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  62750. }
  62751. }
  62752. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  62753. };
  62754. Skeleton.prototype.getAnimationRange = function (name) {
  62755. return this._ranges[name];
  62756. };
  62757. /**
  62758. * Returns as an Array, all AnimationRanges defined on this skeleton
  62759. */
  62760. Skeleton.prototype.getAnimationRanges = function () {
  62761. var animationRanges = [];
  62762. var name;
  62763. var i = 0;
  62764. for (name in this._ranges) {
  62765. animationRanges[i] = this._ranges[name];
  62766. i++;
  62767. }
  62768. return animationRanges;
  62769. };
  62770. /**
  62771. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  62772. */
  62773. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  62774. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  62775. if (this._ranges[name] || !source.getAnimationRange(name)) {
  62776. return false;
  62777. }
  62778. var ret = true;
  62779. var frameOffset = this._getHighestAnimationFrame() + 1;
  62780. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  62781. var boneDict = {};
  62782. var sourceBones = source.bones;
  62783. var nBones;
  62784. var i;
  62785. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  62786. boneDict[sourceBones[i].name] = sourceBones[i];
  62787. }
  62788. if (this.bones.length !== sourceBones.length) {
  62789. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  62790. ret = false;
  62791. }
  62792. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  62793. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  62794. var boneName = this.bones[i].name;
  62795. var sourceBone = boneDict[boneName];
  62796. if (sourceBone) {
  62797. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  62798. }
  62799. else {
  62800. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  62801. ret = false;
  62802. }
  62803. }
  62804. // do not call createAnimationRange(), since it also is done to bones, which was already done
  62805. var range = source.getAnimationRange(name);
  62806. if (range) {
  62807. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  62808. }
  62809. return ret;
  62810. };
  62811. Skeleton.prototype.returnToRest = function () {
  62812. for (var index = 0; index < this.bones.length; index++) {
  62813. this.bones[index].returnToRest();
  62814. }
  62815. };
  62816. Skeleton.prototype._getHighestAnimationFrame = function () {
  62817. var ret = 0;
  62818. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62819. if (this.bones[i].animations[0]) {
  62820. var highest = this.bones[i].animations[0].getHighestFrame();
  62821. if (ret < highest) {
  62822. ret = highest;
  62823. }
  62824. }
  62825. }
  62826. return ret;
  62827. };
  62828. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  62829. var range = this.getAnimationRange(name);
  62830. if (!range) {
  62831. return null;
  62832. }
  62833. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  62834. };
  62835. Skeleton.prototype._markAsDirty = function () {
  62836. this._isDirty = true;
  62837. };
  62838. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  62839. this._meshesWithPoseMatrix.push(mesh);
  62840. };
  62841. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  62842. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  62843. if (index > -1) {
  62844. this._meshesWithPoseMatrix.splice(index, 1);
  62845. }
  62846. };
  62847. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  62848. this.onBeforeComputeObservable.notifyObservers(this);
  62849. for (var index = 0; index < this.bones.length; index++) {
  62850. var bone = this.bones[index];
  62851. var parentBone = bone.getParent();
  62852. if (parentBone) {
  62853. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  62854. }
  62855. else {
  62856. if (initialSkinMatrix) {
  62857. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  62858. }
  62859. else {
  62860. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  62861. }
  62862. }
  62863. if (bone._index !== -1) {
  62864. var mappedIndex = bone._index === null ? index : bone._index;
  62865. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  62866. }
  62867. }
  62868. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  62869. };
  62870. Skeleton.prototype.prepare = function () {
  62871. if (!this._isDirty) {
  62872. return;
  62873. }
  62874. if (this.needInitialSkinMatrix) {
  62875. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  62876. var mesh = this._meshesWithPoseMatrix[index];
  62877. var poseMatrix = mesh.getPoseMatrix();
  62878. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  62879. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62880. }
  62881. if (this._synchronizedWithMesh !== mesh) {
  62882. this._synchronizedWithMesh = mesh;
  62883. // Prepare bones
  62884. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  62885. var bone = this.bones[boneIndex];
  62886. if (!bone.getParent()) {
  62887. var matrix = bone.getBaseMatrix();
  62888. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  62889. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  62890. }
  62891. }
  62892. }
  62893. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  62894. }
  62895. }
  62896. else {
  62897. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  62898. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62899. }
  62900. this._computeTransformMatrices(this._transformMatrices, null);
  62901. }
  62902. this._isDirty = false;
  62903. this._scene._activeBones.addCount(this.bones.length, false);
  62904. };
  62905. Skeleton.prototype.getAnimatables = function () {
  62906. if (!this._animatables || this._animatables.length !== this.bones.length) {
  62907. this._animatables = [];
  62908. for (var index = 0; index < this.bones.length; index++) {
  62909. this._animatables.push(this.bones[index]);
  62910. }
  62911. }
  62912. return this._animatables;
  62913. };
  62914. Skeleton.prototype.clone = function (name, id) {
  62915. var result = new Skeleton(name, id || name, this._scene);
  62916. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62917. for (var index = 0; index < this.bones.length; index++) {
  62918. var source = this.bones[index];
  62919. var parentBone = null;
  62920. var parent_1 = source.getParent();
  62921. if (parent_1) {
  62922. var parentIndex = this.bones.indexOf(parent_1);
  62923. parentBone = result.bones[parentIndex];
  62924. }
  62925. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  62926. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  62927. }
  62928. if (this._ranges) {
  62929. result._ranges = {};
  62930. for (var rangeName in this._ranges) {
  62931. var range = this._ranges[rangeName];
  62932. if (range) {
  62933. result._ranges[rangeName] = range.clone();
  62934. }
  62935. }
  62936. }
  62937. this._isDirty = true;
  62938. return result;
  62939. };
  62940. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  62941. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  62942. this.bones.forEach(function (bone) {
  62943. bone.animations.forEach(function (animation) {
  62944. animation.enableBlending = true;
  62945. animation.blendingSpeed = blendingSpeed;
  62946. });
  62947. });
  62948. };
  62949. Skeleton.prototype.dispose = function () {
  62950. this._meshesWithPoseMatrix = [];
  62951. // Animations
  62952. this.getScene().stopAnimation(this);
  62953. // Remove from scene
  62954. this.getScene().removeSkeleton(this);
  62955. };
  62956. Skeleton.prototype.serialize = function () {
  62957. var serializationObject = {};
  62958. serializationObject.name = this.name;
  62959. serializationObject.id = this.id;
  62960. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  62961. serializationObject.bones = [];
  62962. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62963. for (var index = 0; index < this.bones.length; index++) {
  62964. var bone = this.bones[index];
  62965. var parent_2 = bone.getParent();
  62966. var serializedBone = {
  62967. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  62968. name: bone.name,
  62969. matrix: bone.getBaseMatrix().toArray(),
  62970. rest: bone.getRestPose().toArray()
  62971. };
  62972. serializationObject.bones.push(serializedBone);
  62973. if (bone.length) {
  62974. serializedBone.length = bone.length;
  62975. }
  62976. if (bone.animations && bone.animations.length > 0) {
  62977. serializedBone.animation = bone.animations[0].serialize();
  62978. }
  62979. serializationObject.ranges = [];
  62980. for (var name in this._ranges) {
  62981. var source = this._ranges[name];
  62982. if (!source) {
  62983. continue;
  62984. }
  62985. var range = {};
  62986. range.name = name;
  62987. range.from = source.from;
  62988. range.to = source.to;
  62989. serializationObject.ranges.push(range);
  62990. }
  62991. }
  62992. return serializationObject;
  62993. };
  62994. Skeleton.Parse = function (parsedSkeleton, scene) {
  62995. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  62996. if (parsedSkeleton.dimensionsAtRest) {
  62997. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  62998. }
  62999. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  63000. var index;
  63001. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  63002. var parsedBone = parsedSkeleton.bones[index];
  63003. var parentBone = null;
  63004. if (parsedBone.parentBoneIndex > -1) {
  63005. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  63006. }
  63007. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  63008. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  63009. if (parsedBone.length) {
  63010. bone.length = parsedBone.length;
  63011. }
  63012. if (parsedBone.animation) {
  63013. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  63014. }
  63015. }
  63016. // placed after bones, so createAnimationRange can cascade down
  63017. if (parsedSkeleton.ranges) {
  63018. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  63019. var data = parsedSkeleton.ranges[index];
  63020. skeleton.createAnimationRange(data.name, data.from, data.to);
  63021. }
  63022. }
  63023. return skeleton;
  63024. };
  63025. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  63026. if (forceUpdate === void 0) { forceUpdate = false; }
  63027. var renderId = this._scene.getRenderId();
  63028. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  63029. this.bones[0].computeAbsoluteTransforms();
  63030. this._lastAbsoluteTransformsUpdateId = renderId;
  63031. }
  63032. };
  63033. Skeleton.prototype.getPoseMatrix = function () {
  63034. var poseMatrix = null;
  63035. if (this._meshesWithPoseMatrix.length > 0) {
  63036. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  63037. }
  63038. return poseMatrix;
  63039. };
  63040. Skeleton.prototype.sortBones = function () {
  63041. var bones = new Array();
  63042. var visited = new Array(this.bones.length);
  63043. for (var index = 0; index < this.bones.length; index++) {
  63044. this._sortBones(index, bones, visited);
  63045. }
  63046. this.bones = bones;
  63047. };
  63048. Skeleton.prototype._sortBones = function (index, bones, visited) {
  63049. if (visited[index]) {
  63050. return;
  63051. }
  63052. visited[index] = true;
  63053. var bone = this.bones[index];
  63054. if (bone._index === undefined) {
  63055. bone._index = index;
  63056. }
  63057. var parentBone = bone.getParent();
  63058. if (parentBone) {
  63059. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  63060. }
  63061. bones.push(bone);
  63062. };
  63063. return Skeleton;
  63064. }());
  63065. BABYLON.Skeleton = Skeleton;
  63066. })(BABYLON || (BABYLON = {}));
  63067. //# sourceMappingURL=babylon.skeleton.js.map
  63068. var BABYLON;
  63069. (function (BABYLON) {
  63070. var SphericalPolynomial = /** @class */ (function () {
  63071. function SphericalPolynomial() {
  63072. this.x = BABYLON.Vector3.Zero();
  63073. this.y = BABYLON.Vector3.Zero();
  63074. this.z = BABYLON.Vector3.Zero();
  63075. this.xx = BABYLON.Vector3.Zero();
  63076. this.yy = BABYLON.Vector3.Zero();
  63077. this.zz = BABYLON.Vector3.Zero();
  63078. this.xy = BABYLON.Vector3.Zero();
  63079. this.yz = BABYLON.Vector3.Zero();
  63080. this.zx = BABYLON.Vector3.Zero();
  63081. }
  63082. SphericalPolynomial.prototype.addAmbient = function (color) {
  63083. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63084. this.xx = this.xx.add(colorVector);
  63085. this.yy = this.yy.add(colorVector);
  63086. this.zz = this.zz.add(colorVector);
  63087. };
  63088. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  63089. var result = new SphericalPolynomial();
  63090. result.x = harmonics.L11.scale(1.02333);
  63091. result.y = harmonics.L1_1.scale(1.02333);
  63092. result.z = harmonics.L10.scale(1.02333);
  63093. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  63094. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  63095. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  63096. result.yz = harmonics.L2_1.scale(0.858086);
  63097. result.zx = harmonics.L21.scale(0.858086);
  63098. result.xy = harmonics.L2_2.scale(0.858086);
  63099. result.scale(1.0 / Math.PI);
  63100. return result;
  63101. };
  63102. SphericalPolynomial.prototype.scale = function (scale) {
  63103. this.x = this.x.scale(scale);
  63104. this.y = this.y.scale(scale);
  63105. this.z = this.z.scale(scale);
  63106. this.xx = this.xx.scale(scale);
  63107. this.yy = this.yy.scale(scale);
  63108. this.zz = this.zz.scale(scale);
  63109. this.yz = this.yz.scale(scale);
  63110. this.zx = this.zx.scale(scale);
  63111. this.xy = this.xy.scale(scale);
  63112. };
  63113. return SphericalPolynomial;
  63114. }());
  63115. BABYLON.SphericalPolynomial = SphericalPolynomial;
  63116. var SphericalHarmonics = /** @class */ (function () {
  63117. function SphericalHarmonics() {
  63118. this.L00 = BABYLON.Vector3.Zero();
  63119. this.L1_1 = BABYLON.Vector3.Zero();
  63120. this.L10 = BABYLON.Vector3.Zero();
  63121. this.L11 = BABYLON.Vector3.Zero();
  63122. this.L2_2 = BABYLON.Vector3.Zero();
  63123. this.L2_1 = BABYLON.Vector3.Zero();
  63124. this.L20 = BABYLON.Vector3.Zero();
  63125. this.L21 = BABYLON.Vector3.Zero();
  63126. this.L22 = BABYLON.Vector3.Zero();
  63127. }
  63128. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  63129. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63130. var c = colorVector.scale(deltaSolidAngle);
  63131. this.L00 = this.L00.add(c.scale(0.282095));
  63132. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  63133. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  63134. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  63135. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  63136. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  63137. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  63138. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  63139. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  63140. };
  63141. SphericalHarmonics.prototype.scale = function (scale) {
  63142. this.L00 = this.L00.scale(scale);
  63143. this.L1_1 = this.L1_1.scale(scale);
  63144. this.L10 = this.L10.scale(scale);
  63145. this.L11 = this.L11.scale(scale);
  63146. this.L2_2 = this.L2_2.scale(scale);
  63147. this.L2_1 = this.L2_1.scale(scale);
  63148. this.L20 = this.L20.scale(scale);
  63149. this.L21 = this.L21.scale(scale);
  63150. this.L22 = this.L22.scale(scale);
  63151. };
  63152. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  63153. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  63154. //
  63155. // E_lm = A_l * L_lm
  63156. //
  63157. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  63158. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  63159. // the scaling factors are given in equation 9.
  63160. // Constant (Band 0)
  63161. this.L00 = this.L00.scale(3.141593);
  63162. // Linear (Band 1)
  63163. this.L1_1 = this.L1_1.scale(2.094395);
  63164. this.L10 = this.L10.scale(2.094395);
  63165. this.L11 = this.L11.scale(2.094395);
  63166. // Quadratic (Band 2)
  63167. this.L2_2 = this.L2_2.scale(0.785398);
  63168. this.L2_1 = this.L2_1.scale(0.785398);
  63169. this.L20 = this.L20.scale(0.785398);
  63170. this.L21 = this.L21.scale(0.785398);
  63171. this.L22 = this.L22.scale(0.785398);
  63172. };
  63173. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  63174. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  63175. // L = (1/pi) * E * rho
  63176. //
  63177. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  63178. this.scale(1.0 / Math.PI);
  63179. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  63180. // (The pixel shader must apply albedo after texture fetches, etc).
  63181. };
  63182. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  63183. var result = new SphericalHarmonics();
  63184. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  63185. result.L1_1 = polynomial.y.scale(0.977204);
  63186. result.L10 = polynomial.z.scale(0.977204);
  63187. result.L11 = polynomial.x.scale(0.977204);
  63188. result.L2_2 = polynomial.xy.scale(1.16538);
  63189. result.L2_1 = polynomial.yz.scale(1.16538);
  63190. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  63191. result.L21 = polynomial.zx.scale(1.16538);
  63192. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  63193. result.scale(Math.PI);
  63194. return result;
  63195. };
  63196. return SphericalHarmonics;
  63197. }());
  63198. BABYLON.SphericalHarmonics = SphericalHarmonics;
  63199. })(BABYLON || (BABYLON = {}));
  63200. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  63201. var BABYLON;
  63202. (function (BABYLON) {
  63203. var Internals;
  63204. (function (Internals) {
  63205. var FileFaceOrientation = /** @class */ (function () {
  63206. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  63207. this.name = name;
  63208. this.worldAxisForNormal = worldAxisForNormal;
  63209. this.worldAxisForFileX = worldAxisForFileX;
  63210. this.worldAxisForFileY = worldAxisForFileY;
  63211. }
  63212. return FileFaceOrientation;
  63213. }());
  63214. ;
  63215. /**
  63216. * Helper class dealing with the extraction of spherical polynomial dataArray
  63217. * from a cube map.
  63218. */
  63219. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  63220. function CubeMapToSphericalPolynomialTools() {
  63221. }
  63222. /**
  63223. * Converts a texture to the according Spherical Polynomial data.
  63224. * This extracts the first 3 orders only as they are the only one used in the lighting.
  63225. *
  63226. * @param texture The texture to extract the information from.
  63227. * @return The Spherical Polynomial data.
  63228. */
  63229. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  63230. if (!texture.isCube) {
  63231. // Only supports cube Textures currently.
  63232. return null;
  63233. }
  63234. var size = texture.getSize().width;
  63235. var right = texture.readPixels(0);
  63236. var left = texture.readPixels(1);
  63237. var up;
  63238. var down;
  63239. if (texture.isRenderTarget) {
  63240. up = texture.readPixels(3);
  63241. down = texture.readPixels(2);
  63242. }
  63243. else {
  63244. up = texture.readPixels(2);
  63245. down = texture.readPixels(3);
  63246. }
  63247. var front = texture.readPixels(4);
  63248. var back = texture.readPixels(5);
  63249. var gammaSpace = texture.gammaSpace;
  63250. // Always read as RGBA.
  63251. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  63252. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63253. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  63254. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63255. }
  63256. var cubeInfo = {
  63257. size: size,
  63258. right: right,
  63259. left: left,
  63260. up: up,
  63261. down: down,
  63262. front: front,
  63263. back: back,
  63264. format: format,
  63265. type: type,
  63266. gammaSpace: gammaSpace,
  63267. };
  63268. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  63269. };
  63270. /**
  63271. * Converts a cubemap to the according Spherical Polynomial data.
  63272. * This extracts the first 3 orders only as they are the only one used in the lighting.
  63273. *
  63274. * @param cubeInfo The Cube map to extract the information from.
  63275. * @return The Spherical Polynomial data.
  63276. */
  63277. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  63278. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  63279. var totalSolidAngle = 0.0;
  63280. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  63281. var du = 2.0 / cubeInfo.size;
  63282. var dv = du;
  63283. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  63284. var minUV = du * 0.5 - 1.0;
  63285. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63286. var fileFace = this.FileFaces[faceIndex];
  63287. var dataArray = cubeInfo[fileFace.name];
  63288. var v = minUV;
  63289. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  63290. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  63291. // Because SP is still linear, so summation is fine in that basis.
  63292. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  63293. for (var y = 0; y < cubeInfo.size; y++) {
  63294. var u = minUV;
  63295. for (var x = 0; x < cubeInfo.size; x++) {
  63296. // World direction (not normalised)
  63297. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  63298. worldDirection.normalize();
  63299. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  63300. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  63301. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  63302. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  63303. // Handle Integer types.
  63304. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  63305. r /= 255;
  63306. g /= 255;
  63307. b /= 255;
  63308. }
  63309. // Handle Gamma space textures.
  63310. if (cubeInfo.gammaSpace) {
  63311. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  63312. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  63313. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  63314. }
  63315. var color = new BABYLON.Color3(r, g, b);
  63316. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  63317. totalSolidAngle += deltaSolidAngle;
  63318. u += du;
  63319. }
  63320. v += dv;
  63321. }
  63322. }
  63323. // Solid angle for entire sphere is 4*pi
  63324. var sphereSolidAngle = 4.0 * Math.PI;
  63325. // Adjust the solid angle to allow for how many faces we processed.
  63326. var facesProcessed = 6.0;
  63327. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  63328. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  63329. // This is needed because the numerical integration over the cube uses a
  63330. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  63331. // and also to compensate for accumulative error due to float precision in the summation.
  63332. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  63333. sphericalHarmonics.scale(correctionFactor);
  63334. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  63335. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  63336. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  63337. };
  63338. CubeMapToSphericalPolynomialTools.FileFaces = [
  63339. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  63340. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  63341. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  63342. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  63343. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  63344. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  63345. ];
  63346. return CubeMapToSphericalPolynomialTools;
  63347. }());
  63348. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  63349. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63350. })(BABYLON || (BABYLON = {}));
  63351. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  63352. var BABYLON;
  63353. (function (BABYLON) {
  63354. var Internals;
  63355. (function (Internals) {
  63356. /**
  63357. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  63358. */
  63359. var PanoramaToCubeMapTools = /** @class */ (function () {
  63360. function PanoramaToCubeMapTools() {
  63361. }
  63362. /**
  63363. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  63364. *
  63365. * @param float32Array The source data.
  63366. * @param inputWidth The width of the input panorama.
  63367. * @param inputhHeight The height of the input panorama.
  63368. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  63369. * @return The cubemap data
  63370. */
  63371. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  63372. if (!float32Array) {
  63373. throw "ConvertPanoramaToCubemap: input cannot be null";
  63374. }
  63375. if (float32Array.length != inputWidth * inputHeight * 3) {
  63376. throw "ConvertPanoramaToCubemap: input size is wrong";
  63377. }
  63378. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  63379. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  63380. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  63381. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  63382. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  63383. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  63384. return {
  63385. front: textureFront,
  63386. back: textureBack,
  63387. left: textureLeft,
  63388. right: textureRight,
  63389. up: textureUp,
  63390. down: textureDown,
  63391. size: size,
  63392. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  63393. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  63394. gammaSpace: false,
  63395. };
  63396. };
  63397. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  63398. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  63399. var textureArray = new Float32Array(buffer);
  63400. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  63401. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  63402. var dy = 1 / texSize;
  63403. var fy = 0;
  63404. for (var y = 0; y < texSize; y++) {
  63405. var xv1 = faceData[0];
  63406. var xv2 = faceData[2];
  63407. for (var x = 0; x < texSize; x++) {
  63408. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  63409. v.normalize();
  63410. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  63411. // 3 channels per pixels
  63412. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  63413. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  63414. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  63415. xv1 = xv1.add(rotDX1);
  63416. xv2 = xv2.add(rotDX2);
  63417. }
  63418. fy += dy;
  63419. }
  63420. return textureArray;
  63421. };
  63422. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  63423. var theta = Math.atan2(vDir.z, vDir.x);
  63424. var phi = Math.acos(vDir.y);
  63425. while (theta < -Math.PI)
  63426. theta += 2 * Math.PI;
  63427. while (theta > Math.PI)
  63428. theta -= 2 * Math.PI;
  63429. var dx = theta / Math.PI;
  63430. var dy = phi / Math.PI;
  63431. // recenter.
  63432. dx = dx * 0.5 + 0.5;
  63433. var px = Math.round(dx * inputWidth);
  63434. if (px < 0)
  63435. px = 0;
  63436. else if (px >= inputWidth)
  63437. px = inputWidth - 1;
  63438. var py = Math.round(dy * inputHeight);
  63439. if (py < 0)
  63440. py = 0;
  63441. else if (py >= inputHeight)
  63442. py = inputHeight - 1;
  63443. var inputY = (inputHeight - py - 1);
  63444. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  63445. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  63446. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  63447. return {
  63448. r: r,
  63449. g: g,
  63450. b: b
  63451. };
  63452. };
  63453. PanoramaToCubeMapTools.FACE_FRONT = [
  63454. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63455. new BABYLON.Vector3(1.0, -1.0, -1.0),
  63456. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  63457. new BABYLON.Vector3(1.0, 1.0, -1.0)
  63458. ];
  63459. PanoramaToCubeMapTools.FACE_BACK = [
  63460. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63461. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63462. new BABYLON.Vector3(1.0, 1.0, 1.0),
  63463. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  63464. ];
  63465. PanoramaToCubeMapTools.FACE_RIGHT = [
  63466. new BABYLON.Vector3(1.0, -1.0, -1.0),
  63467. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63468. new BABYLON.Vector3(1.0, 1.0, -1.0),
  63469. new BABYLON.Vector3(1.0, 1.0, 1.0)
  63470. ];
  63471. PanoramaToCubeMapTools.FACE_LEFT = [
  63472. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63473. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63474. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  63475. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  63476. ];
  63477. PanoramaToCubeMapTools.FACE_DOWN = [
  63478. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  63479. new BABYLON.Vector3(1.0, 1.0, -1.0),
  63480. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  63481. new BABYLON.Vector3(1.0, 1.0, 1.0)
  63482. ];
  63483. PanoramaToCubeMapTools.FACE_UP = [
  63484. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63485. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63486. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63487. new BABYLON.Vector3(1.0, -1.0, -1.0)
  63488. ];
  63489. return PanoramaToCubeMapTools;
  63490. }());
  63491. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  63492. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63493. })(BABYLON || (BABYLON = {}));
  63494. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  63495. var BABYLON;
  63496. (function (BABYLON) {
  63497. var Internals;
  63498. (function (Internals) {
  63499. ;
  63500. /**
  63501. * This groups tools to convert HDR texture to native colors array.
  63502. */
  63503. var HDRTools = /** @class */ (function () {
  63504. function HDRTools() {
  63505. }
  63506. HDRTools.Ldexp = function (mantissa, exponent) {
  63507. if (exponent > 1023) {
  63508. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  63509. }
  63510. if (exponent < -1074) {
  63511. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  63512. }
  63513. return mantissa * Math.pow(2, exponent);
  63514. };
  63515. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  63516. if (exponent > 0) {
  63517. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  63518. float32array[index + 0] = red * exponent;
  63519. float32array[index + 1] = green * exponent;
  63520. float32array[index + 2] = blue * exponent;
  63521. }
  63522. else {
  63523. float32array[index + 0] = 0;
  63524. float32array[index + 1] = 0;
  63525. float32array[index + 2] = 0;
  63526. }
  63527. };
  63528. HDRTools.readStringLine = function (uint8array, startIndex) {
  63529. var line = "";
  63530. var character = "";
  63531. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  63532. character = String.fromCharCode(uint8array[i]);
  63533. if (character == "\n") {
  63534. break;
  63535. }
  63536. line += character;
  63537. }
  63538. return line;
  63539. };
  63540. /**
  63541. * Reads header information from an RGBE texture stored in a native array.
  63542. * More information on this format are available here:
  63543. * https://en.wikipedia.org/wiki/RGBE_image_format
  63544. *
  63545. * @param uint8array The binary file stored in native array.
  63546. * @return The header information.
  63547. */
  63548. HDRTools.RGBE_ReadHeader = function (uint8array) {
  63549. var height = 0;
  63550. var width = 0;
  63551. var line = this.readStringLine(uint8array, 0);
  63552. if (line[0] != '#' || line[1] != '?') {
  63553. throw "Bad HDR Format.";
  63554. }
  63555. var endOfHeader = false;
  63556. var findFormat = false;
  63557. var lineIndex = 0;
  63558. do {
  63559. lineIndex += (line.length + 1);
  63560. line = this.readStringLine(uint8array, lineIndex);
  63561. if (line == "FORMAT=32-bit_rle_rgbe") {
  63562. findFormat = true;
  63563. }
  63564. else if (line.length == 0) {
  63565. endOfHeader = true;
  63566. }
  63567. } while (!endOfHeader);
  63568. if (!findFormat) {
  63569. throw "HDR Bad header format, unsupported FORMAT";
  63570. }
  63571. lineIndex += (line.length + 1);
  63572. line = this.readStringLine(uint8array, lineIndex);
  63573. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  63574. var match = sizeRegexp.exec(line);
  63575. // TODO. Support +Y and -X if needed.
  63576. if (!match || match.length < 3) {
  63577. throw "HDR Bad header format, no size";
  63578. }
  63579. width = parseInt(match[2]);
  63580. height = parseInt(match[1]);
  63581. if (width < 8 || width > 0x7fff) {
  63582. throw "HDR Bad header format, unsupported size";
  63583. }
  63584. lineIndex += (line.length + 1);
  63585. return {
  63586. height: height,
  63587. width: width,
  63588. dataPosition: lineIndex
  63589. };
  63590. };
  63591. /**
  63592. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  63593. * This RGBE texture needs to store the information as a panorama.
  63594. *
  63595. * More information on this format are available here:
  63596. * https://en.wikipedia.org/wiki/RGBE_image_format
  63597. *
  63598. * @param buffer The binary file stored in an array buffer.
  63599. * @param size The expected size of the extracted cubemap.
  63600. * @return The Cube Map information.
  63601. */
  63602. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  63603. var uint8array = new Uint8Array(buffer);
  63604. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  63605. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  63606. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  63607. return cubeMapData;
  63608. };
  63609. /**
  63610. * Returns the pixels data extracted from an RGBE texture.
  63611. * This pixels will be stored left to right up to down in the R G B order in one array.
  63612. *
  63613. * More information on this format are available here:
  63614. * https://en.wikipedia.org/wiki/RGBE_image_format
  63615. *
  63616. * @param uint8array The binary file stored in an array buffer.
  63617. * @param hdrInfo The header information of the file.
  63618. * @return The pixels data in RGB right to left up to down order.
  63619. */
  63620. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  63621. // Keep for multi format supports.
  63622. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  63623. };
  63624. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  63625. var num_scanlines = hdrInfo.height;
  63626. var scanline_width = hdrInfo.width;
  63627. var a, b, c, d, count;
  63628. var dataIndex = hdrInfo.dataPosition;
  63629. var index = 0, endIndex = 0, i = 0;
  63630. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  63631. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  63632. // 3 channels of 4 bytes per pixel in float.
  63633. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  63634. var resultArray = new Float32Array(resultBuffer);
  63635. // read in each successive scanline
  63636. while (num_scanlines > 0) {
  63637. a = uint8array[dataIndex++];
  63638. b = uint8array[dataIndex++];
  63639. c = uint8array[dataIndex++];
  63640. d = uint8array[dataIndex++];
  63641. if (a != 2 || b != 2 || (c & 0x80)) {
  63642. // this file is not run length encoded
  63643. throw "HDR Bad header format, not RLE";
  63644. }
  63645. if (((c << 8) | d) != scanline_width) {
  63646. throw "HDR Bad header format, wrong scan line width";
  63647. }
  63648. index = 0;
  63649. // read each of the four channels for the scanline into the buffer
  63650. for (i = 0; i < 4; i++) {
  63651. endIndex = (i + 1) * scanline_width;
  63652. while (index < endIndex) {
  63653. a = uint8array[dataIndex++];
  63654. b = uint8array[dataIndex++];
  63655. if (a > 128) {
  63656. // a run of the same value
  63657. count = a - 128;
  63658. if ((count == 0) || (count > endIndex - index)) {
  63659. throw "HDR Bad Format, bad scanline data (run)";
  63660. }
  63661. while (count-- > 0) {
  63662. scanLineArray[index++] = b;
  63663. }
  63664. }
  63665. else {
  63666. // a non-run
  63667. count = a;
  63668. if ((count == 0) || (count > endIndex - index)) {
  63669. throw "HDR Bad Format, bad scanline data (non-run)";
  63670. }
  63671. scanLineArray[index++] = b;
  63672. if (--count > 0) {
  63673. for (var j = 0; j < count; j++) {
  63674. scanLineArray[index++] = uint8array[dataIndex++];
  63675. }
  63676. }
  63677. }
  63678. }
  63679. }
  63680. // now convert data from buffer into floats
  63681. for (i = 0; i < scanline_width; i++) {
  63682. a = scanLineArray[i];
  63683. b = scanLineArray[i + scanline_width];
  63684. c = scanLineArray[i + 2 * scanline_width];
  63685. d = scanLineArray[i + 3 * scanline_width];
  63686. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  63687. }
  63688. num_scanlines--;
  63689. }
  63690. return resultArray;
  63691. };
  63692. return HDRTools;
  63693. }());
  63694. Internals.HDRTools = HDRTools;
  63695. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63696. })(BABYLON || (BABYLON = {}));
  63697. //# sourceMappingURL=babylon.hdr.js.map
  63698. var BABYLON;
  63699. (function (BABYLON) {
  63700. /**
  63701. * This represents a texture coming from an HDR input.
  63702. *
  63703. * The only supported format is currently panorama picture stored in RGBE format.
  63704. * Example of such files can be found on HDRLib: http://hdrlib.com/
  63705. */
  63706. var HDRCubeTexture = /** @class */ (function (_super) {
  63707. __extends(HDRCubeTexture, _super);
  63708. /**
  63709. * Instantiates an HDRTexture from the following parameters.
  63710. *
  63711. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  63712. * @param scene The scene the texture will be used in
  63713. * @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.
  63714. * @param noMipmap Forces to not generate the mipmap if true
  63715. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  63716. * @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)
  63717. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  63718. */
  63719. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  63720. if (noMipmap === void 0) { noMipmap = false; }
  63721. if (generateHarmonics === void 0) { generateHarmonics = true; }
  63722. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  63723. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  63724. if (onLoad === void 0) { onLoad = null; }
  63725. if (onError === void 0) { onError = null; }
  63726. var _this = _super.call(this, scene) || this;
  63727. _this._useInGammaSpace = false;
  63728. _this._generateHarmonics = true;
  63729. _this._isBABYLONPreprocessed = false;
  63730. _this._onLoad = null;
  63731. _this._onError = null;
  63732. /**
  63733. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  63734. */
  63735. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63736. /**
  63737. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  63738. * This is usefull at run time to apply the good shader.
  63739. */
  63740. _this.isPMREM = false;
  63741. _this._isBlocking = true;
  63742. if (!url) {
  63743. return _this;
  63744. }
  63745. _this.name = url;
  63746. _this.url = url;
  63747. _this.hasAlpha = false;
  63748. _this.isCube = true;
  63749. _this._textureMatrix = BABYLON.Matrix.Identity();
  63750. _this._onLoad = onLoad;
  63751. _this._onError = onError;
  63752. _this.gammaSpace = false;
  63753. var caps = scene.getEngine().getCaps();
  63754. if (size) {
  63755. _this._isBABYLONPreprocessed = false;
  63756. _this._noMipmap = noMipmap;
  63757. _this._size = size;
  63758. _this._useInGammaSpace = useInGammaSpace;
  63759. _this._usePMREMGenerator = usePMREMGenerator &&
  63760. caps.textureLOD &&
  63761. caps.textureFloat &&
  63762. !_this._useInGammaSpace;
  63763. }
  63764. else {
  63765. _this._isBABYLONPreprocessed = true;
  63766. _this._noMipmap = false;
  63767. _this._useInGammaSpace = false;
  63768. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  63769. !_this._useInGammaSpace;
  63770. }
  63771. _this.isPMREM = _this._usePMREMGenerator;
  63772. _this._texture = _this._getFromCache(url, _this._noMipmap);
  63773. if (!_this._texture) {
  63774. if (!scene.useDelayedTextureLoading) {
  63775. _this.loadTexture();
  63776. }
  63777. else {
  63778. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63779. }
  63780. }
  63781. return _this;
  63782. }
  63783. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  63784. /**
  63785. * Gets wether or not the texture is blocking during loading.
  63786. */
  63787. get: function () {
  63788. return this._isBlocking;
  63789. },
  63790. /**
  63791. * Sets wether or not the texture is blocking during loading.
  63792. */
  63793. set: function (value) {
  63794. this._isBlocking = value;
  63795. },
  63796. enumerable: true,
  63797. configurable: true
  63798. });
  63799. /**
  63800. * Occurs when the file is a preprocessed .babylon.hdr file.
  63801. */
  63802. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  63803. var _this = this;
  63804. var mipLevels = 0;
  63805. var floatArrayView = null;
  63806. var scene = this.getScene();
  63807. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  63808. var mips = new Array();
  63809. if (!floatArrayView) {
  63810. return mips;
  63811. }
  63812. var startIndex = 30;
  63813. for (var level = 0; level < mipLevels; level++) {
  63814. mips.push([]);
  63815. // Fill each pixel of the mip level.
  63816. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  63817. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63818. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  63819. mips[level].push(faceData);
  63820. startIndex += faceSize;
  63821. }
  63822. }
  63823. return mips;
  63824. } : null;
  63825. var callback = function (buffer) {
  63826. var scene = _this.getScene();
  63827. if (!scene) {
  63828. return null;
  63829. }
  63830. // Create Native Array Views
  63831. var intArrayView = new Int32Array(buffer);
  63832. floatArrayView = new Float32Array(buffer);
  63833. // Fill header.
  63834. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  63835. _this._size = intArrayView[1]; // CubeMap max mip face size.
  63836. // Update Texture Information.
  63837. if (!_this._texture) {
  63838. return null;
  63839. }
  63840. _this._texture.updateSize(_this._size, _this._size);
  63841. // Fill polynomial information.
  63842. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  63843. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  63844. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  63845. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  63846. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  63847. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  63848. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  63849. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  63850. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  63851. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  63852. _this.sphericalPolynomial = sphericalPolynomial;
  63853. // Fill pixel data.
  63854. mipLevels = intArrayView[29]; // Number of mip levels.
  63855. var startIndex = 30;
  63856. var data = [];
  63857. var faceSize = Math.pow(_this._size, 2) * 3;
  63858. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63859. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  63860. startIndex += faceSize;
  63861. }
  63862. var results = [];
  63863. var byteArray = null;
  63864. // Push each faces.
  63865. for (var k = 0; k < 6; k++) {
  63866. var dataFace = null;
  63867. // To be deprecated.
  63868. if (version === 1) {
  63869. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  63870. dataFace = data[j];
  63871. }
  63872. // If special cases.
  63873. if (!mipmapGenerator && dataFace) {
  63874. if (!scene.getEngine().getCaps().textureFloat) {
  63875. // 3 channels of 1 bytes per pixel in bytes.
  63876. var byteBuffer = new ArrayBuffer(faceSize);
  63877. byteArray = new Uint8Array(byteBuffer);
  63878. }
  63879. for (var i = 0; i < _this._size * _this._size; i++) {
  63880. // Put in gamma space if requested.
  63881. if (_this._useInGammaSpace) {
  63882. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63883. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63884. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63885. }
  63886. // Convert to int texture for fallback.
  63887. if (byteArray) {
  63888. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63889. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63890. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63891. // May use luminance instead if the result is not accurate.
  63892. var max = Math.max(Math.max(r, g), b);
  63893. if (max > 255) {
  63894. var scale = 255 / max;
  63895. r *= scale;
  63896. g *= scale;
  63897. b *= scale;
  63898. }
  63899. byteArray[(i * 3) + 0] = r;
  63900. byteArray[(i * 3) + 1] = g;
  63901. byteArray[(i * 3) + 2] = b;
  63902. }
  63903. }
  63904. }
  63905. // Fill the array accordingly.
  63906. if (byteArray) {
  63907. results.push(byteArray);
  63908. }
  63909. else {
  63910. results.push(dataFace);
  63911. }
  63912. }
  63913. return results;
  63914. };
  63915. if (scene) {
  63916. 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);
  63917. }
  63918. };
  63919. /**
  63920. * Occurs when the file is raw .hdr file.
  63921. */
  63922. HDRCubeTexture.prototype.loadHDRTexture = function () {
  63923. var _this = this;
  63924. var callback = function (buffer) {
  63925. var scene = _this.getScene();
  63926. if (!scene) {
  63927. return null;
  63928. }
  63929. // Extract the raw linear data.
  63930. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  63931. // Generate harmonics if needed.
  63932. if (_this._generateHarmonics) {
  63933. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  63934. _this.sphericalPolynomial = sphericalPolynomial;
  63935. }
  63936. var results = [];
  63937. var byteArray = null;
  63938. // Push each faces.
  63939. for (var j = 0; j < 6; j++) {
  63940. // Create uintarray fallback.
  63941. if (!scene.getEngine().getCaps().textureFloat) {
  63942. // 3 channels of 1 bytes per pixel in bytes.
  63943. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  63944. byteArray = new Uint8Array(byteBuffer);
  63945. }
  63946. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  63947. // If special cases.
  63948. if (_this._useInGammaSpace || byteArray) {
  63949. for (var i = 0; i < _this._size * _this._size; i++) {
  63950. // Put in gamma space if requested.
  63951. if (_this._useInGammaSpace) {
  63952. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63953. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63954. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63955. }
  63956. // Convert to int texture for fallback.
  63957. if (byteArray) {
  63958. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63959. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63960. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63961. // May use luminance instead if the result is not accurate.
  63962. var max = Math.max(Math.max(r, g), b);
  63963. if (max > 255) {
  63964. var scale = 255 / max;
  63965. r *= scale;
  63966. g *= scale;
  63967. b *= scale;
  63968. }
  63969. byteArray[(i * 3) + 0] = r;
  63970. byteArray[(i * 3) + 1] = g;
  63971. byteArray[(i * 3) + 2] = b;
  63972. }
  63973. }
  63974. }
  63975. if (byteArray) {
  63976. results.push(byteArray);
  63977. }
  63978. else {
  63979. results.push(dataFace);
  63980. }
  63981. }
  63982. return results;
  63983. };
  63984. var mipmapGenerator = null;
  63985. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  63986. // if (!this._noMipmap &&
  63987. // this._usePMREMGenerator) {
  63988. // mipmapGenerator = (data: ArrayBufferView[]) => {
  63989. // // Custom setup of the generator matching with the PBR shader values.
  63990. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  63991. // this._size,
  63992. // this._size,
  63993. // 0,
  63994. // 3,
  63995. // this.getScene().getEngine().getCaps().textureFloat,
  63996. // 2048,
  63997. // 0.25,
  63998. // false,
  63999. // true);
  64000. // return generator.filterCubeMap();
  64001. // };
  64002. // }
  64003. var scene = this.getScene();
  64004. if (scene) {
  64005. 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);
  64006. }
  64007. };
  64008. /**
  64009. * Starts the loading process of the texture.
  64010. */
  64011. HDRCubeTexture.prototype.loadTexture = function () {
  64012. if (this._isBABYLONPreprocessed) {
  64013. this.loadBabylonTexture();
  64014. }
  64015. else {
  64016. this.loadHDRTexture();
  64017. }
  64018. };
  64019. HDRCubeTexture.prototype.clone = function () {
  64020. var scene = this.getScene();
  64021. if (!scene) {
  64022. return this;
  64023. }
  64024. var size = (this._isBABYLONPreprocessed ? null : this._size);
  64025. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  64026. // Base texture
  64027. newTexture.level = this.level;
  64028. newTexture.wrapU = this.wrapU;
  64029. newTexture.wrapV = this.wrapV;
  64030. newTexture.coordinatesIndex = this.coordinatesIndex;
  64031. newTexture.coordinatesMode = this.coordinatesMode;
  64032. return newTexture;
  64033. };
  64034. // Methods
  64035. HDRCubeTexture.prototype.delayLoad = function () {
  64036. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64037. return;
  64038. }
  64039. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64040. this._texture = this._getFromCache(this.url, this._noMipmap);
  64041. if (!this._texture) {
  64042. this.loadTexture();
  64043. }
  64044. };
  64045. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  64046. return this._textureMatrix;
  64047. };
  64048. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  64049. this._textureMatrix = value;
  64050. };
  64051. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64052. var texture = null;
  64053. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  64054. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  64055. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  64056. texture.name = parsedTexture.name;
  64057. texture.hasAlpha = parsedTexture.hasAlpha;
  64058. texture.level = parsedTexture.level;
  64059. texture.coordinatesMode = parsedTexture.coordinatesMode;
  64060. texture.isBlocking = parsedTexture.isBlocking;
  64061. }
  64062. return texture;
  64063. };
  64064. HDRCubeTexture.prototype.serialize = function () {
  64065. if (!this.name) {
  64066. return null;
  64067. }
  64068. var serializationObject = {};
  64069. serializationObject.name = this.name;
  64070. serializationObject.hasAlpha = this.hasAlpha;
  64071. serializationObject.isCube = true;
  64072. serializationObject.level = this.level;
  64073. serializationObject.size = this._size;
  64074. serializationObject.coordinatesMode = this.coordinatesMode;
  64075. serializationObject.useInGammaSpace = this._useInGammaSpace;
  64076. serializationObject.generateHarmonics = this._generateHarmonics;
  64077. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  64078. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  64079. serializationObject.customType = "BABYLON.HDRCubeTexture";
  64080. serializationObject.noMipmap = this._noMipmap;
  64081. serializationObject.isBlocking = this._isBlocking;
  64082. return serializationObject;
  64083. };
  64084. /**
  64085. * Saves as a file the data contained in the texture in a binary format.
  64086. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64087. * as the spherical used in the lighting.
  64088. * @param url The HDR file url.
  64089. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64090. * @param onError Method called if any error happens during download.
  64091. * @return The packed binary data.
  64092. */
  64093. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  64094. if (onError === void 0) { onError = null; }
  64095. var callback = function (buffer) {
  64096. var data = new Blob([buffer], { type: 'application/octet-stream' });
  64097. // Returns a URL you can use as a href.
  64098. var objUrl = window.URL.createObjectURL(data);
  64099. // Simulates a link to it and click to dowload.
  64100. var a = document.createElement("a");
  64101. document.body.appendChild(a);
  64102. a.style.display = "none";
  64103. a.href = objUrl;
  64104. a.download = "envmap.babylon.hdr";
  64105. a.click();
  64106. };
  64107. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  64108. };
  64109. /**
  64110. * Serializes the data contained in the texture in a binary format.
  64111. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64112. * as the spherical used in the lighting.
  64113. * @param url The HDR file url.
  64114. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64115. * @param onError Method called if any error happens during download.
  64116. * @return The packed binary data.
  64117. */
  64118. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  64119. if (onError === void 0) { onError = null; }
  64120. // Needs the url tho create the texture.
  64121. if (!url) {
  64122. return;
  64123. }
  64124. // Check Power of two size.
  64125. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  64126. return;
  64127. }
  64128. // Coming Back in 3.x.
  64129. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  64130. };
  64131. HDRCubeTexture._facesMapping = [
  64132. "right",
  64133. "left",
  64134. "up",
  64135. "down",
  64136. "front",
  64137. "back"
  64138. ];
  64139. return HDRCubeTexture;
  64140. }(BABYLON.BaseTexture));
  64141. BABYLON.HDRCubeTexture = HDRCubeTexture;
  64142. })(BABYLON || (BABYLON = {}));
  64143. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  64144. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  64145. // Huge respect for a such great lib.
  64146. // Earcut license:
  64147. // Copyright (c) 2016, Mapbox
  64148. //
  64149. // Permission to use, copy, modify, and/or distribute this software for any purpose
  64150. // with or without fee is hereby granted, provided that the above copyright notice
  64151. // and this permission notice appear in all copies.
  64152. //
  64153. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  64154. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  64155. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  64156. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  64157. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  64158. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  64159. // THIS SOFTWARE.
  64160. var Earcut;
  64161. (function (Earcut) {
  64162. /**
  64163. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  64164. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  64165. * @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).
  64166. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  64167. */
  64168. function earcut(data, holeIndices, dim) {
  64169. dim = dim || 2;
  64170. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  64171. if (!outerNode)
  64172. return triangles;
  64173. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  64174. if (hasHoles)
  64175. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  64176. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  64177. if (data.length > 80 * dim) {
  64178. minX = maxX = data[0];
  64179. minY = maxY = data[1];
  64180. for (var i = dim; i < outerLen; i += dim) {
  64181. x = data[i];
  64182. y = data[i + 1];
  64183. if (x < minX)
  64184. minX = x;
  64185. if (y < minY)
  64186. minY = y;
  64187. if (x > maxX)
  64188. maxX = x;
  64189. if (y > maxY)
  64190. maxY = y;
  64191. }
  64192. // minX, minY and size are later used to transform coords into integers for z-order calculation
  64193. size = Math.max(maxX - minX, maxY - minY);
  64194. }
  64195. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  64196. return triangles;
  64197. }
  64198. Earcut.earcut = earcut;
  64199. var Node = /** @class */ (function () {
  64200. function Node(i, x, y) {
  64201. this.i = i;
  64202. this.x = x;
  64203. this.y = y;
  64204. this.prev = null;
  64205. this.next = null;
  64206. this.z = null;
  64207. this.prevZ = null;
  64208. this.nextZ = null;
  64209. this.steiner = false;
  64210. }
  64211. return Node;
  64212. }());
  64213. // create a circular doubly linked list from polygon points in the specified winding order
  64214. function linkedList(data, start, end, dim, clockwise) {
  64215. var i, last = null;
  64216. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  64217. for (i = start; i < end; i += dim)
  64218. last = insertNode(i, data[i], data[i + 1], last);
  64219. }
  64220. else {
  64221. for (i = end - dim; i >= start; i -= dim)
  64222. last = insertNode(i, data[i], data[i + 1], last);
  64223. }
  64224. if (last && equals(last, last.next)) {
  64225. removeNode(last);
  64226. last = last.next;
  64227. }
  64228. return last;
  64229. }
  64230. // eliminate colinear or duplicate points
  64231. function filterPoints(start, end) {
  64232. if (!start)
  64233. return start;
  64234. if (!end)
  64235. end = start;
  64236. var p = start, again;
  64237. do {
  64238. again = false;
  64239. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  64240. removeNode(p);
  64241. p = end = p.prev;
  64242. if (p === p.next)
  64243. return undefined;
  64244. again = true;
  64245. }
  64246. else {
  64247. p = p.next;
  64248. }
  64249. } while (again || p !== end);
  64250. return end;
  64251. }
  64252. // main ear slicing loop which triangulates a polygon (given as a linked list)
  64253. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  64254. if (!ear)
  64255. return;
  64256. // interlink polygon nodes in z-order
  64257. if (!pass && size)
  64258. indexCurve(ear, minX, minY, size);
  64259. var stop = ear, prev, next;
  64260. // iterate through ears, slicing them one by one
  64261. while (ear.prev !== ear.next) {
  64262. prev = ear.prev;
  64263. next = ear.next;
  64264. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  64265. // cut off the triangle
  64266. triangles.push(prev.i / dim);
  64267. triangles.push(ear.i / dim);
  64268. triangles.push(next.i / dim);
  64269. removeNode(ear);
  64270. // skipping the next vertice leads to less sliver triangles
  64271. ear = next.next;
  64272. stop = next.next;
  64273. continue;
  64274. }
  64275. ear = next;
  64276. // if we looped through the whole remaining polygon and can't find any more ears
  64277. if (ear === stop) {
  64278. // try filtering points and slicing again
  64279. if (!pass) {
  64280. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  64281. // if this didn't work, try curing all small self-intersections locally
  64282. }
  64283. else if (pass === 1) {
  64284. ear = cureLocalIntersections(ear, triangles, dim);
  64285. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  64286. // as a last resort, try splitting the remaining polygon into two
  64287. }
  64288. else if (pass === 2) {
  64289. splitEarcut(ear, triangles, dim, minX, minY, size);
  64290. }
  64291. break;
  64292. }
  64293. }
  64294. }
  64295. // check whether a polygon node forms a valid ear with adjacent nodes
  64296. function isEar(ear) {
  64297. var a = ear.prev, b = ear, c = ear.next;
  64298. if (area(a, b, c) >= 0)
  64299. return false; // reflex, can't be an ear
  64300. // now make sure we don't have other points inside the potential ear
  64301. var p = ear.next.next;
  64302. while (p !== ear.prev) {
  64303. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64304. area(p.prev, p, p.next) >= 0)
  64305. return false;
  64306. p = p.next;
  64307. }
  64308. return true;
  64309. }
  64310. function isEarHashed(ear, minX, minY, size) {
  64311. var a = ear.prev, b = ear, c = ear.next;
  64312. if (area(a, b, c) >= 0)
  64313. return false; // reflex, can't be an ear
  64314. // triangle bbox; min & max are calculated like this for speed
  64315. 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);
  64316. // z-order range for the current triangle bbox;
  64317. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  64318. // first look for points inside the triangle in increasing z-order
  64319. var p = ear.nextZ;
  64320. while (p && p.z <= maxZ) {
  64321. if (p !== ear.prev &&
  64322. p !== ear.next &&
  64323. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64324. area(p.prev, p, p.next) >= 0)
  64325. return false;
  64326. p = p.nextZ;
  64327. }
  64328. // then look for points in decreasing z-order
  64329. p = ear.prevZ;
  64330. while (p && p.z >= minZ) {
  64331. if (p !== ear.prev &&
  64332. p !== ear.next &&
  64333. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64334. area(p.prev, p, p.next) >= 0)
  64335. return false;
  64336. p = p.prevZ;
  64337. }
  64338. return true;
  64339. }
  64340. // go through all polygon nodes and cure small local self-intersections
  64341. function cureLocalIntersections(start, triangles, dim) {
  64342. var p = start;
  64343. do {
  64344. var a = p.prev, b = p.next.next;
  64345. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  64346. triangles.push(a.i / dim);
  64347. triangles.push(p.i / dim);
  64348. triangles.push(b.i / dim);
  64349. // remove two nodes involved
  64350. removeNode(p);
  64351. removeNode(p.next);
  64352. p = start = b;
  64353. }
  64354. p = p.next;
  64355. } while (p !== start);
  64356. return p;
  64357. }
  64358. // try splitting polygon into two and triangulate them independently
  64359. function splitEarcut(start, triangles, dim, minX, minY, size) {
  64360. // look for a valid diagonal that divides the polygon into two
  64361. var a = start;
  64362. do {
  64363. var b = a.next.next;
  64364. while (b !== a.prev) {
  64365. if (a.i !== b.i && isValidDiagonal(a, b)) {
  64366. // split the polygon in two by the diagonal
  64367. var c = splitPolygon(a, b);
  64368. // filter colinear points around the cuts
  64369. a = filterPoints(a, a.next);
  64370. c = filterPoints(c, c.next);
  64371. // run earcut on each half
  64372. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  64373. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  64374. return;
  64375. }
  64376. b = b.next;
  64377. }
  64378. a = a.next;
  64379. } while (a !== start);
  64380. }
  64381. // link every hole into the outer loop, producing a single-ring polygon without holes
  64382. function eliminateHoles(data, holeIndices, outerNode, dim) {
  64383. var queue = [], i, len, start, end, list;
  64384. for (i = 0, len = holeIndices.length; i < len; i++) {
  64385. start = holeIndices[i] * dim;
  64386. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  64387. list = linkedList(data, start, end, dim, false);
  64388. if (list === list.next)
  64389. list.steiner = true;
  64390. queue.push(getLeftmost(list));
  64391. }
  64392. queue.sort(compareX);
  64393. // process holes from left to right
  64394. for (i = 0; i < queue.length; i++) {
  64395. eliminateHole(queue[i], outerNode);
  64396. outerNode = filterPoints(outerNode, outerNode.next);
  64397. }
  64398. return outerNode;
  64399. }
  64400. function compareX(a, b) {
  64401. return a.x - b.x;
  64402. }
  64403. // find a bridge between vertices that connects hole with an outer ring and and link it
  64404. function eliminateHole(hole, outerNode) {
  64405. outerNode = findHoleBridge(hole, outerNode);
  64406. if (outerNode) {
  64407. var b = splitPolygon(outerNode, hole);
  64408. filterPoints(b, b.next);
  64409. }
  64410. }
  64411. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  64412. function findHoleBridge(hole, outerNode) {
  64413. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  64414. // find a segment intersected by a ray from the hole's leftmost point to the left;
  64415. // segment's endpoint with lesser x will be potential connection point
  64416. do {
  64417. if (hy <= p.y && hy >= p.next.y) {
  64418. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  64419. if (x <= hx && x > qx) {
  64420. qx = x;
  64421. if (x === hx) {
  64422. if (hy === p.y)
  64423. return p;
  64424. if (hy === p.next.y)
  64425. return p.next;
  64426. }
  64427. m = p.x < p.next.x ? p : p.next;
  64428. }
  64429. }
  64430. p = p.next;
  64431. } while (p !== outerNode);
  64432. if (!m)
  64433. return null;
  64434. if (hx === qx)
  64435. return m.prev; // hole touches outer segment; pick lower endpoint
  64436. // look for points inside the triangle of hole point, segment intersection and endpoint;
  64437. // if there are no points found, we have a valid connection;
  64438. // otherwise choose the point of the minimum angle with the ray as connection point
  64439. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  64440. p = m.next;
  64441. while (p !== stop) {
  64442. if (hx >= p.x &&
  64443. p.x >= mx &&
  64444. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  64445. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  64446. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  64447. m = p;
  64448. tanMin = tan;
  64449. }
  64450. }
  64451. p = p.next;
  64452. }
  64453. return m;
  64454. }
  64455. // interlink polygon nodes in z-order
  64456. function indexCurve(start, minX, minY, size) {
  64457. var p = start;
  64458. do {
  64459. if (p.z === null)
  64460. p.z = zOrder(p.x, p.y, minX, minY, size);
  64461. p.prevZ = p.prev;
  64462. p.nextZ = p.next;
  64463. p = p.next;
  64464. } while (p !== start);
  64465. p.prevZ.nextZ = null;
  64466. p.prevZ = null;
  64467. sortLinked(p);
  64468. }
  64469. // Simon Tatham's linked list merge sort algorithm
  64470. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  64471. function sortLinked(list) {
  64472. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  64473. do {
  64474. p = list;
  64475. list = null;
  64476. tail = null;
  64477. numMerges = 0;
  64478. while (p) {
  64479. numMerges++;
  64480. q = p;
  64481. pSize = 0;
  64482. for (i = 0; i < inSize; i++) {
  64483. pSize++;
  64484. q = q.nextZ;
  64485. if (!q)
  64486. break;
  64487. }
  64488. qSize = inSize;
  64489. while (pSize > 0 || (qSize > 0 && q)) {
  64490. if (pSize === 0) {
  64491. e = q;
  64492. q = q.nextZ;
  64493. qSize--;
  64494. }
  64495. else if (qSize === 0 || !q) {
  64496. e = p;
  64497. p = p.nextZ;
  64498. pSize--;
  64499. }
  64500. else if (p.z <= q.z) {
  64501. e = p;
  64502. p = p.nextZ;
  64503. pSize--;
  64504. }
  64505. else {
  64506. e = q;
  64507. q = q.nextZ;
  64508. qSize--;
  64509. }
  64510. if (tail)
  64511. tail.nextZ = e;
  64512. else
  64513. list = e;
  64514. e.prevZ = tail;
  64515. tail = e;
  64516. }
  64517. p = q;
  64518. }
  64519. tail.nextZ = null;
  64520. inSize *= 2;
  64521. } while (numMerges > 1);
  64522. return list;
  64523. }
  64524. // z-order of a point given coords and size of the data bounding box
  64525. function zOrder(x, y, minX, minY, size) {
  64526. // coords are transformed into non-negative 15-bit integer range
  64527. x = 32767 * (x - minX) / size;
  64528. y = 32767 * (y - minY) / size;
  64529. x = (x | (x << 8)) & 0x00FF00FF;
  64530. x = (x | (x << 4)) & 0x0F0F0F0F;
  64531. x = (x | (x << 2)) & 0x33333333;
  64532. x = (x | (x << 1)) & 0x55555555;
  64533. y = (y | (y << 8)) & 0x00FF00FF;
  64534. y = (y | (y << 4)) & 0x0F0F0F0F;
  64535. y = (y | (y << 2)) & 0x33333333;
  64536. y = (y | (y << 1)) & 0x55555555;
  64537. return x | (y << 1);
  64538. }
  64539. // find the leftmost node of a polygon ring
  64540. function getLeftmost(start) {
  64541. var p = start, leftmost = start;
  64542. do {
  64543. if (p.x < leftmost.x)
  64544. leftmost = p;
  64545. p = p.next;
  64546. } while (p !== start);
  64547. return leftmost;
  64548. }
  64549. // check if a point lies within a convex triangle
  64550. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  64551. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  64552. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  64553. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  64554. }
  64555. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  64556. function isValidDiagonal(a, b) {
  64557. return a.next.i !== b.i &&
  64558. a.prev.i !== b.i &&
  64559. !intersectsPolygon(a, b) &&
  64560. locallyInside(a, b) &&
  64561. locallyInside(b, a) &&
  64562. middleInside(a, b);
  64563. }
  64564. // signed area of a triangle
  64565. function area(p, q, r) {
  64566. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  64567. }
  64568. // check if two points are equal
  64569. function equals(p1, p2) {
  64570. return p1.x === p2.x && p1.y === p2.y;
  64571. }
  64572. // check if two segments intersect
  64573. function intersects(p1, q1, p2, q2) {
  64574. if ((equals(p1, q1) && equals(p2, q2)) ||
  64575. (equals(p1, q2) && equals(p2, q1)))
  64576. return true;
  64577. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  64578. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  64579. }
  64580. // check if a polygon diagonal intersects any polygon segments
  64581. function intersectsPolygon(a, b) {
  64582. var p = a;
  64583. do {
  64584. if (p.i !== a.i &&
  64585. p.next.i !== a.i &&
  64586. p.i !== b.i &&
  64587. p.next.i !== b.i &&
  64588. intersects(p, p.next, a, b))
  64589. return true;
  64590. p = p.next;
  64591. } while (p !== a);
  64592. return false;
  64593. }
  64594. // check if a polygon diagonal is locally inside the polygon
  64595. function locallyInside(a, b) {
  64596. return area(a.prev, a, a.next) < 0
  64597. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  64598. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  64599. }
  64600. // check if the middle point of a polygon diagonal is inside the polygon
  64601. function middleInside(a, b) {
  64602. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  64603. do {
  64604. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  64605. inside = !inside;
  64606. p = p.next;
  64607. } while (p !== a);
  64608. return inside;
  64609. }
  64610. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  64611. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  64612. function splitPolygon(a, b) {
  64613. 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;
  64614. a.next = b;
  64615. b.prev = a;
  64616. a2.next = an;
  64617. an.prev = a2;
  64618. b2.next = a2;
  64619. a2.prev = b2;
  64620. bp.next = b2;
  64621. b2.prev = bp;
  64622. return b2;
  64623. }
  64624. // create a node and optionally link it with previous one (in a circular doubly linked list)
  64625. function insertNode(i, x, y, last) {
  64626. var p = new Node(i, x, y);
  64627. if (!last) {
  64628. p.prev = p;
  64629. p.next = p;
  64630. }
  64631. else {
  64632. p.next = last.next;
  64633. p.prev = last;
  64634. last.next.prev = p;
  64635. last.next = p;
  64636. }
  64637. return p;
  64638. }
  64639. function removeNode(p) {
  64640. p.next.prev = p.prev;
  64641. p.prev.next = p.next;
  64642. if (p.prevZ)
  64643. p.prevZ.nextZ = p.nextZ;
  64644. if (p.nextZ)
  64645. p.nextZ.prevZ = p.prevZ;
  64646. }
  64647. /**
  64648. * return a percentage difference between the polygon area and its triangulation area;
  64649. * used to verify correctness of triangulation
  64650. */
  64651. function deviation(data, holeIndices, dim, triangles) {
  64652. var hasHoles = holeIndices && holeIndices.length;
  64653. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  64654. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  64655. if (hasHoles) {
  64656. for (var i = 0, len = holeIndices.length; i < len; i++) {
  64657. var start = holeIndices[i] * dim;
  64658. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  64659. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  64660. }
  64661. }
  64662. var trianglesArea = 0;
  64663. for (i = 0; i < triangles.length; i += 3) {
  64664. var a = triangles[i] * dim;
  64665. var b = triangles[i + 1] * dim;
  64666. var c = triangles[i + 2] * dim;
  64667. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  64668. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  64669. }
  64670. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  64671. }
  64672. Earcut.deviation = deviation;
  64673. ;
  64674. function signedArea(data, start, end, dim) {
  64675. var sum = 0;
  64676. for (var i = start, j = end - dim; i < end; i += dim) {
  64677. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  64678. j = i;
  64679. }
  64680. return sum;
  64681. }
  64682. /**
  64683. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  64684. */
  64685. function flatten(data) {
  64686. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  64687. for (var i = 0; i < data.length; i++) {
  64688. for (var j = 0; j < data[i].length; j++) {
  64689. for (var d = 0; d < dim; d++)
  64690. result.vertices.push(data[i][j][d]);
  64691. }
  64692. if (i > 0) {
  64693. holeIndex += data[i - 1].length;
  64694. result.holes.push(holeIndex);
  64695. }
  64696. }
  64697. return result;
  64698. }
  64699. Earcut.flatten = flatten;
  64700. ;
  64701. })(Earcut || (Earcut = {}));
  64702. //# sourceMappingURL=babylon.earcut.js.map
  64703. var BABYLON;
  64704. (function (BABYLON) {
  64705. var IndexedVector2 = /** @class */ (function (_super) {
  64706. __extends(IndexedVector2, _super);
  64707. function IndexedVector2(original, index) {
  64708. var _this = _super.call(this, original.x, original.y) || this;
  64709. _this.index = index;
  64710. return _this;
  64711. }
  64712. return IndexedVector2;
  64713. }(BABYLON.Vector2));
  64714. var PolygonPoints = /** @class */ (function () {
  64715. function PolygonPoints() {
  64716. this.elements = new Array();
  64717. }
  64718. PolygonPoints.prototype.add = function (originalPoints) {
  64719. var _this = this;
  64720. var result = new Array();
  64721. originalPoints.forEach(function (point) {
  64722. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  64723. var newPoint = new IndexedVector2(point, _this.elements.length);
  64724. result.push(newPoint);
  64725. _this.elements.push(newPoint);
  64726. }
  64727. });
  64728. return result;
  64729. };
  64730. PolygonPoints.prototype.computeBounds = function () {
  64731. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64732. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64733. this.elements.forEach(function (point) {
  64734. // x
  64735. if (point.x < lmin.x) {
  64736. lmin.x = point.x;
  64737. }
  64738. else if (point.x > lmax.x) {
  64739. lmax.x = point.x;
  64740. }
  64741. // y
  64742. if (point.y < lmin.y) {
  64743. lmin.y = point.y;
  64744. }
  64745. else if (point.y > lmax.y) {
  64746. lmax.y = point.y;
  64747. }
  64748. });
  64749. return {
  64750. min: lmin,
  64751. max: lmax,
  64752. width: lmax.x - lmin.x,
  64753. height: lmax.y - lmin.y
  64754. };
  64755. };
  64756. return PolygonPoints;
  64757. }());
  64758. var Polygon = /** @class */ (function () {
  64759. function Polygon() {
  64760. }
  64761. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  64762. return [
  64763. new BABYLON.Vector2(xmin, ymin),
  64764. new BABYLON.Vector2(xmax, ymin),
  64765. new BABYLON.Vector2(xmax, ymax),
  64766. new BABYLON.Vector2(xmin, ymax)
  64767. ];
  64768. };
  64769. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  64770. if (cx === void 0) { cx = 0; }
  64771. if (cy === void 0) { cy = 0; }
  64772. if (numberOfSides === void 0) { numberOfSides = 32; }
  64773. var result = new Array();
  64774. var angle = 0;
  64775. var increment = (Math.PI * 2) / numberOfSides;
  64776. for (var i = 0; i < numberOfSides; i++) {
  64777. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  64778. angle -= increment;
  64779. }
  64780. return result;
  64781. };
  64782. Polygon.Parse = function (input) {
  64783. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  64784. var i, result = [];
  64785. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  64786. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  64787. }
  64788. return result;
  64789. };
  64790. Polygon.StartingAt = function (x, y) {
  64791. return BABYLON.Path2.StartingAt(x, y);
  64792. };
  64793. return Polygon;
  64794. }());
  64795. BABYLON.Polygon = Polygon;
  64796. var PolygonMeshBuilder = /** @class */ (function () {
  64797. function PolygonMeshBuilder(name, contours, scene) {
  64798. this._points = new PolygonPoints();
  64799. this._outlinepoints = new PolygonPoints();
  64800. this._holes = new Array();
  64801. this._epoints = new Array();
  64802. this._eholes = new Array();
  64803. this._name = name;
  64804. this._scene = scene;
  64805. var points;
  64806. if (contours instanceof BABYLON.Path2) {
  64807. points = contours.getPoints();
  64808. }
  64809. else {
  64810. points = contours;
  64811. }
  64812. this._addToepoint(points);
  64813. this._points.add(points);
  64814. this._outlinepoints.add(points);
  64815. }
  64816. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  64817. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  64818. var p = points_1[_i];
  64819. this._epoints.push(p.x, p.y);
  64820. }
  64821. };
  64822. PolygonMeshBuilder.prototype.addHole = function (hole) {
  64823. this._points.add(hole);
  64824. var holepoints = new PolygonPoints();
  64825. holepoints.add(hole);
  64826. this._holes.push(holepoints);
  64827. this._eholes.push(this._epoints.length / 2);
  64828. this._addToepoint(hole);
  64829. return this;
  64830. };
  64831. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  64832. var _this = this;
  64833. if (updatable === void 0) { updatable = false; }
  64834. if (depth === void 0) { depth = 0; }
  64835. var result = new BABYLON.Mesh(this._name, this._scene);
  64836. var normals = new Array();
  64837. var positions = new Array();
  64838. var uvs = new Array();
  64839. var bounds = this._points.computeBounds();
  64840. this._points.elements.forEach(function (p) {
  64841. normals.push(0, 1.0, 0);
  64842. positions.push(p.x, 0, p.y);
  64843. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  64844. });
  64845. var indices = new Array();
  64846. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  64847. for (var i = 0; i < res.length; i++) {
  64848. indices.push(res[i]);
  64849. }
  64850. if (depth > 0) {
  64851. var positionscount = (positions.length / 3); //get the current pointcount
  64852. this._points.elements.forEach(function (p) {
  64853. normals.push(0, -1.0, 0);
  64854. positions.push(p.x, -depth, p.y);
  64855. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  64856. });
  64857. var totalCount = indices.length;
  64858. for (var i = 0; i < totalCount; i += 3) {
  64859. var i0 = indices[i + 0];
  64860. var i1 = indices[i + 1];
  64861. var i2 = indices[i + 2];
  64862. indices.push(i2 + positionscount);
  64863. indices.push(i1 + positionscount);
  64864. indices.push(i0 + positionscount);
  64865. }
  64866. //Add the sides
  64867. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  64868. this._holes.forEach(function (hole) {
  64869. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  64870. });
  64871. }
  64872. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  64873. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  64874. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  64875. result.setIndices(indices);
  64876. return result;
  64877. };
  64878. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  64879. var StartIndex = positions.length / 3;
  64880. var ulength = 0;
  64881. for (var i = 0; i < points.elements.length; i++) {
  64882. var p = points.elements[i];
  64883. var p1;
  64884. if ((i + 1) > points.elements.length - 1) {
  64885. p1 = points.elements[0];
  64886. }
  64887. else {
  64888. p1 = points.elements[i + 1];
  64889. }
  64890. positions.push(p.x, 0, p.y);
  64891. positions.push(p.x, -depth, p.y);
  64892. positions.push(p1.x, 0, p1.y);
  64893. positions.push(p1.x, -depth, p1.y);
  64894. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  64895. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  64896. var v3 = v2.subtract(v1);
  64897. var v4 = new BABYLON.Vector3(0, 1, 0);
  64898. var vn = BABYLON.Vector3.Cross(v3, v4);
  64899. vn = vn.normalize();
  64900. uvs.push(ulength / bounds.width, 0);
  64901. uvs.push(ulength / bounds.width, 1);
  64902. ulength += v3.length();
  64903. uvs.push((ulength / bounds.width), 0);
  64904. uvs.push((ulength / bounds.width), 1);
  64905. if (!flip) {
  64906. normals.push(-vn.x, -vn.y, -vn.z);
  64907. normals.push(-vn.x, -vn.y, -vn.z);
  64908. normals.push(-vn.x, -vn.y, -vn.z);
  64909. normals.push(-vn.x, -vn.y, -vn.z);
  64910. indices.push(StartIndex);
  64911. indices.push(StartIndex + 1);
  64912. indices.push(StartIndex + 2);
  64913. indices.push(StartIndex + 1);
  64914. indices.push(StartIndex + 3);
  64915. indices.push(StartIndex + 2);
  64916. }
  64917. else {
  64918. normals.push(vn.x, vn.y, vn.z);
  64919. normals.push(vn.x, vn.y, vn.z);
  64920. normals.push(vn.x, vn.y, vn.z);
  64921. normals.push(vn.x, vn.y, vn.z);
  64922. indices.push(StartIndex);
  64923. indices.push(StartIndex + 2);
  64924. indices.push(StartIndex + 1);
  64925. indices.push(StartIndex + 1);
  64926. indices.push(StartIndex + 2);
  64927. indices.push(StartIndex + 3);
  64928. }
  64929. StartIndex += 4;
  64930. }
  64931. ;
  64932. };
  64933. return PolygonMeshBuilder;
  64934. }());
  64935. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  64936. })(BABYLON || (BABYLON = {}));
  64937. //# sourceMappingURL=babylon.polygonMesh.js.map
  64938. var BABYLON;
  64939. (function (BABYLON) {
  64940. // Unique ID when we import meshes from Babylon to CSG
  64941. var currentCSGMeshId = 0;
  64942. // # class Vertex
  64943. // Represents a vertex of a polygon. Use your own vertex class instead of this
  64944. // one to provide additional features like texture coordinates and vertex
  64945. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  64946. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  64947. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  64948. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  64949. // is not used anywhere else.
  64950. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  64951. var Vertex = /** @class */ (function () {
  64952. function Vertex(pos, normal, uv) {
  64953. this.pos = pos;
  64954. this.normal = normal;
  64955. this.uv = uv;
  64956. }
  64957. Vertex.prototype.clone = function () {
  64958. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  64959. };
  64960. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  64961. // orientation of a polygon is flipped.
  64962. Vertex.prototype.flip = function () {
  64963. this.normal = this.normal.scale(-1);
  64964. };
  64965. // Create a new vertex between this vertex and `other` by linearly
  64966. // interpolating all properties using a parameter of `t`. Subclasses should
  64967. // override this to interpolate additional properties.
  64968. Vertex.prototype.interpolate = function (other, t) {
  64969. 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));
  64970. };
  64971. return Vertex;
  64972. }());
  64973. // # class Plane
  64974. // Represents a plane in 3D space.
  64975. var Plane = /** @class */ (function () {
  64976. function Plane(normal, w) {
  64977. this.normal = normal;
  64978. this.w = w;
  64979. }
  64980. Plane.FromPoints = function (a, b, c) {
  64981. var v0 = c.subtract(a);
  64982. var v1 = b.subtract(a);
  64983. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  64984. return null;
  64985. }
  64986. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  64987. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  64988. };
  64989. Plane.prototype.clone = function () {
  64990. return new Plane(this.normal.clone(), this.w);
  64991. };
  64992. Plane.prototype.flip = function () {
  64993. this.normal.scaleInPlace(-1);
  64994. this.w = -this.w;
  64995. };
  64996. // Split `polygon` by this plane if needed, then put the polygon or polygon
  64997. // fragments in the appropriate lists. Coplanar polygons go into either
  64998. // `coplanarFront` or `coplanarBack` depending on their orientation with
  64999. // respect to this plane. Polygons in front or in back of this plane go into
  65000. // either `front` or `back`.
  65001. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  65002. var COPLANAR = 0;
  65003. var FRONT = 1;
  65004. var BACK = 2;
  65005. var SPANNING = 3;
  65006. // Classify each point as well as the entire polygon into one of the above
  65007. // four classes.
  65008. var polygonType = 0;
  65009. var types = [];
  65010. var i;
  65011. var t;
  65012. for (i = 0; i < polygon.vertices.length; i++) {
  65013. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  65014. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  65015. polygonType |= type;
  65016. types.push(type);
  65017. }
  65018. // Put the polygon in the correct list, splitting it when necessary.
  65019. switch (polygonType) {
  65020. case COPLANAR:
  65021. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  65022. break;
  65023. case FRONT:
  65024. front.push(polygon);
  65025. break;
  65026. case BACK:
  65027. back.push(polygon);
  65028. break;
  65029. case SPANNING:
  65030. var f = [], b = [];
  65031. for (i = 0; i < polygon.vertices.length; i++) {
  65032. var j = (i + 1) % polygon.vertices.length;
  65033. var ti = types[i], tj = types[j];
  65034. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  65035. if (ti !== BACK)
  65036. f.push(vi);
  65037. if (ti !== FRONT)
  65038. b.push(ti !== BACK ? vi.clone() : vi);
  65039. if ((ti | tj) === SPANNING) {
  65040. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  65041. var v = vi.interpolate(vj, t);
  65042. f.push(v);
  65043. b.push(v.clone());
  65044. }
  65045. }
  65046. var poly;
  65047. if (f.length >= 3) {
  65048. poly = new Polygon(f, polygon.shared);
  65049. if (poly.plane)
  65050. front.push(poly);
  65051. }
  65052. if (b.length >= 3) {
  65053. poly = new Polygon(b, polygon.shared);
  65054. if (poly.plane)
  65055. back.push(poly);
  65056. }
  65057. break;
  65058. }
  65059. };
  65060. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  65061. // point is on the plane.
  65062. Plane.EPSILON = 1e-5;
  65063. return Plane;
  65064. }());
  65065. // # class Polygon
  65066. // Represents a convex polygon. The vertices used to initialize a polygon must
  65067. // be coplanar and form a convex loop.
  65068. //
  65069. // Each convex polygon has a `shared` property, which is shared between all
  65070. // polygons that are clones of each other or were split from the same polygon.
  65071. // This can be used to define per-polygon properties (such as surface color).
  65072. var Polygon = /** @class */ (function () {
  65073. function Polygon(vertices, shared) {
  65074. this.vertices = vertices;
  65075. this.shared = shared;
  65076. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  65077. }
  65078. Polygon.prototype.clone = function () {
  65079. var vertices = this.vertices.map(function (v) { return v.clone(); });
  65080. return new Polygon(vertices, this.shared);
  65081. };
  65082. Polygon.prototype.flip = function () {
  65083. this.vertices.reverse().map(function (v) { v.flip(); });
  65084. this.plane.flip();
  65085. };
  65086. return Polygon;
  65087. }());
  65088. // # class Node
  65089. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  65090. // by picking a polygon to split along. That polygon (and all other coplanar
  65091. // polygons) are added directly to that node and the other polygons are added to
  65092. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  65093. // no distinction between internal and leaf nodes.
  65094. var Node = /** @class */ (function () {
  65095. function Node(polygons) {
  65096. this.plane = null;
  65097. this.front = null;
  65098. this.back = null;
  65099. this.polygons = new Array();
  65100. if (polygons) {
  65101. this.build(polygons);
  65102. }
  65103. }
  65104. Node.prototype.clone = function () {
  65105. var node = new Node();
  65106. node.plane = this.plane && this.plane.clone();
  65107. node.front = this.front && this.front.clone();
  65108. node.back = this.back && this.back.clone();
  65109. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  65110. return node;
  65111. };
  65112. // Convert solid space to empty space and empty space to solid space.
  65113. Node.prototype.invert = function () {
  65114. for (var i = 0; i < this.polygons.length; i++) {
  65115. this.polygons[i].flip();
  65116. }
  65117. if (this.plane) {
  65118. this.plane.flip();
  65119. }
  65120. if (this.front) {
  65121. this.front.invert();
  65122. }
  65123. if (this.back) {
  65124. this.back.invert();
  65125. }
  65126. var temp = this.front;
  65127. this.front = this.back;
  65128. this.back = temp;
  65129. };
  65130. // Recursively remove all polygons in `polygons` that are inside this BSP
  65131. // tree.
  65132. Node.prototype.clipPolygons = function (polygons) {
  65133. if (!this.plane)
  65134. return polygons.slice();
  65135. var front = new Array(), back = new Array();
  65136. for (var i = 0; i < polygons.length; i++) {
  65137. this.plane.splitPolygon(polygons[i], front, back, front, back);
  65138. }
  65139. if (this.front) {
  65140. front = this.front.clipPolygons(front);
  65141. }
  65142. if (this.back) {
  65143. back = this.back.clipPolygons(back);
  65144. }
  65145. else {
  65146. back = [];
  65147. }
  65148. return front.concat(back);
  65149. };
  65150. // Remove all polygons in this BSP tree that are inside the other BSP tree
  65151. // `bsp`.
  65152. Node.prototype.clipTo = function (bsp) {
  65153. this.polygons = bsp.clipPolygons(this.polygons);
  65154. if (this.front)
  65155. this.front.clipTo(bsp);
  65156. if (this.back)
  65157. this.back.clipTo(bsp);
  65158. };
  65159. // Return a list of all polygons in this BSP tree.
  65160. Node.prototype.allPolygons = function () {
  65161. var polygons = this.polygons.slice();
  65162. if (this.front)
  65163. polygons = polygons.concat(this.front.allPolygons());
  65164. if (this.back)
  65165. polygons = polygons.concat(this.back.allPolygons());
  65166. return polygons;
  65167. };
  65168. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  65169. // new polygons are filtered down to the bottom of the tree and become new
  65170. // nodes there. Each set of polygons is partitioned using the first polygon
  65171. // (no heuristic is used to pick a good split).
  65172. Node.prototype.build = function (polygons) {
  65173. if (!polygons.length)
  65174. return;
  65175. if (!this.plane)
  65176. this.plane = polygons[0].plane.clone();
  65177. var front = new Array(), back = new Array();
  65178. for (var i = 0; i < polygons.length; i++) {
  65179. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  65180. }
  65181. if (front.length) {
  65182. if (!this.front)
  65183. this.front = new Node();
  65184. this.front.build(front);
  65185. }
  65186. if (back.length) {
  65187. if (!this.back)
  65188. this.back = new Node();
  65189. this.back.build(back);
  65190. }
  65191. };
  65192. return Node;
  65193. }());
  65194. var CSG = /** @class */ (function () {
  65195. function CSG() {
  65196. this.polygons = new Array();
  65197. }
  65198. // Convert BABYLON.Mesh to BABYLON.CSG
  65199. CSG.FromMesh = function (mesh) {
  65200. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  65201. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  65202. if (mesh instanceof BABYLON.Mesh) {
  65203. mesh.computeWorldMatrix(true);
  65204. matrix = mesh.getWorldMatrix();
  65205. meshPosition = mesh.position.clone();
  65206. meshRotation = mesh.rotation.clone();
  65207. if (mesh.rotationQuaternion) {
  65208. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  65209. }
  65210. meshScaling = mesh.scaling.clone();
  65211. }
  65212. else {
  65213. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  65214. }
  65215. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65216. var subMeshes = mesh.subMeshes;
  65217. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  65218. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  65219. vertices = [];
  65220. for (var j = 0; j < 3; j++) {
  65221. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  65222. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  65223. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  65224. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  65225. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  65226. vertex = new Vertex(position, normal, uv);
  65227. vertices.push(vertex);
  65228. }
  65229. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  65230. // To handle the case of degenerated triangle
  65231. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  65232. if (polygon.plane)
  65233. polygons.push(polygon);
  65234. }
  65235. }
  65236. var csg = CSG.FromPolygons(polygons);
  65237. csg.matrix = matrix;
  65238. csg.position = meshPosition;
  65239. csg.rotation = meshRotation;
  65240. csg.scaling = meshScaling;
  65241. csg.rotationQuaternion = meshRotationQuaternion;
  65242. currentCSGMeshId++;
  65243. return csg;
  65244. };
  65245. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  65246. CSG.FromPolygons = function (polygons) {
  65247. var csg = new CSG();
  65248. csg.polygons = polygons;
  65249. return csg;
  65250. };
  65251. CSG.prototype.clone = function () {
  65252. var csg = new CSG();
  65253. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  65254. csg.copyTransformAttributes(this);
  65255. return csg;
  65256. };
  65257. CSG.prototype.union = function (csg) {
  65258. var a = new Node(this.clone().polygons);
  65259. var b = new Node(csg.clone().polygons);
  65260. a.clipTo(b);
  65261. b.clipTo(a);
  65262. b.invert();
  65263. b.clipTo(a);
  65264. b.invert();
  65265. a.build(b.allPolygons());
  65266. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65267. };
  65268. CSG.prototype.unionInPlace = function (csg) {
  65269. var a = new Node(this.polygons);
  65270. var b = new Node(csg.polygons);
  65271. a.clipTo(b);
  65272. b.clipTo(a);
  65273. b.invert();
  65274. b.clipTo(a);
  65275. b.invert();
  65276. a.build(b.allPolygons());
  65277. this.polygons = a.allPolygons();
  65278. };
  65279. CSG.prototype.subtract = function (csg) {
  65280. var a = new Node(this.clone().polygons);
  65281. var b = new Node(csg.clone().polygons);
  65282. a.invert();
  65283. a.clipTo(b);
  65284. b.clipTo(a);
  65285. b.invert();
  65286. b.clipTo(a);
  65287. b.invert();
  65288. a.build(b.allPolygons());
  65289. a.invert();
  65290. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65291. };
  65292. CSG.prototype.subtractInPlace = function (csg) {
  65293. var a = new Node(this.polygons);
  65294. var b = new Node(csg.polygons);
  65295. a.invert();
  65296. a.clipTo(b);
  65297. b.clipTo(a);
  65298. b.invert();
  65299. b.clipTo(a);
  65300. b.invert();
  65301. a.build(b.allPolygons());
  65302. a.invert();
  65303. this.polygons = a.allPolygons();
  65304. };
  65305. CSG.prototype.intersect = function (csg) {
  65306. var a = new Node(this.clone().polygons);
  65307. var b = new Node(csg.clone().polygons);
  65308. a.invert();
  65309. b.clipTo(a);
  65310. b.invert();
  65311. a.clipTo(b);
  65312. b.clipTo(a);
  65313. a.build(b.allPolygons());
  65314. a.invert();
  65315. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65316. };
  65317. CSG.prototype.intersectInPlace = function (csg) {
  65318. var a = new Node(this.polygons);
  65319. var b = new Node(csg.polygons);
  65320. a.invert();
  65321. b.clipTo(a);
  65322. b.invert();
  65323. a.clipTo(b);
  65324. b.clipTo(a);
  65325. a.build(b.allPolygons());
  65326. a.invert();
  65327. this.polygons = a.allPolygons();
  65328. };
  65329. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  65330. // not modified.
  65331. CSG.prototype.inverse = function () {
  65332. var csg = this.clone();
  65333. csg.inverseInPlace();
  65334. return csg;
  65335. };
  65336. CSG.prototype.inverseInPlace = function () {
  65337. this.polygons.map(function (p) { p.flip(); });
  65338. };
  65339. // This is used to keep meshes transformations so they can be restored
  65340. // when we build back a Babylon Mesh
  65341. // NB : All CSG operations are performed in world coordinates
  65342. CSG.prototype.copyTransformAttributes = function (csg) {
  65343. this.matrix = csg.matrix;
  65344. this.position = csg.position;
  65345. this.rotation = csg.rotation;
  65346. this.scaling = csg.scaling;
  65347. this.rotationQuaternion = csg.rotationQuaternion;
  65348. return this;
  65349. };
  65350. // Build Raw mesh from CSG
  65351. // Coordinates here are in world space
  65352. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  65353. var matrix = this.matrix.clone();
  65354. matrix.invert();
  65355. 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;
  65356. if (keepSubMeshes) {
  65357. // Sort Polygons, since subMeshes are indices range
  65358. polygons.sort(function (a, b) {
  65359. if (a.shared.meshId === b.shared.meshId) {
  65360. return a.shared.subMeshId - b.shared.subMeshId;
  65361. }
  65362. else {
  65363. return a.shared.meshId - b.shared.meshId;
  65364. }
  65365. });
  65366. }
  65367. for (var i = 0, il = polygons.length; i < il; i++) {
  65368. polygon = polygons[i];
  65369. // Building SubMeshes
  65370. if (!subMesh_dict[polygon.shared.meshId]) {
  65371. subMesh_dict[polygon.shared.meshId] = {};
  65372. }
  65373. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  65374. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  65375. indexStart: +Infinity,
  65376. indexEnd: -Infinity,
  65377. materialIndex: polygon.shared.materialIndex
  65378. };
  65379. }
  65380. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  65381. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  65382. polygonIndices[0] = 0;
  65383. polygonIndices[1] = j - 1;
  65384. polygonIndices[2] = j;
  65385. for (var k = 0; k < 3; k++) {
  65386. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  65387. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  65388. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  65389. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  65390. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  65391. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  65392. // Check if 2 points can be merged
  65393. if (!(typeof vertex_idx !== 'undefined' &&
  65394. normals[vertex_idx * 3] === localNormal.x &&
  65395. normals[vertex_idx * 3 + 1] === localNormal.y &&
  65396. normals[vertex_idx * 3 + 2] === localNormal.z &&
  65397. uvs[vertex_idx * 2] === uv.x &&
  65398. uvs[vertex_idx * 2 + 1] === uv.y)) {
  65399. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  65400. uvs.push(uv.x, uv.y);
  65401. normals.push(normal.x, normal.y, normal.z);
  65402. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  65403. }
  65404. indices.push(vertex_idx);
  65405. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  65406. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  65407. currentIndex++;
  65408. }
  65409. }
  65410. }
  65411. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  65412. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  65413. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  65414. mesh.setIndices(indices, null);
  65415. if (keepSubMeshes) {
  65416. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  65417. var materialIndexOffset = 0, materialMaxIndex;
  65418. mesh.subMeshes = new Array();
  65419. for (var m in subMesh_dict) {
  65420. materialMaxIndex = -1;
  65421. for (var sm in subMesh_dict[m]) {
  65422. subMesh_obj = subMesh_dict[m][sm];
  65423. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  65424. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  65425. }
  65426. materialIndexOffset += ++materialMaxIndex;
  65427. }
  65428. }
  65429. return mesh;
  65430. };
  65431. // Build Mesh from CSG taking material and transforms into account
  65432. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  65433. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  65434. mesh.material = material;
  65435. mesh.position.copyFrom(this.position);
  65436. mesh.rotation.copyFrom(this.rotation);
  65437. if (this.rotationQuaternion) {
  65438. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  65439. }
  65440. mesh.scaling.copyFrom(this.scaling);
  65441. mesh.computeWorldMatrix(true);
  65442. return mesh;
  65443. };
  65444. return CSG;
  65445. }());
  65446. BABYLON.CSG = CSG;
  65447. })(BABYLON || (BABYLON = {}));
  65448. //# sourceMappingURL=babylon.csg.js.map
  65449. var BABYLON;
  65450. (function (BABYLON) {
  65451. var LensFlare = /** @class */ (function () {
  65452. function LensFlare(size, position, color, imgUrl, system) {
  65453. this.size = size;
  65454. this.position = position;
  65455. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  65456. this.color = color || new BABYLON.Color3(1, 1, 1);
  65457. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  65458. this._system = system;
  65459. system.lensFlares.push(this);
  65460. }
  65461. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  65462. return new LensFlare(size, position, color, imgUrl, system);
  65463. };
  65464. LensFlare.prototype.dispose = function () {
  65465. if (this.texture) {
  65466. this.texture.dispose();
  65467. }
  65468. // Remove from scene
  65469. var index = this._system.lensFlares.indexOf(this);
  65470. this._system.lensFlares.splice(index, 1);
  65471. };
  65472. ;
  65473. return LensFlare;
  65474. }());
  65475. BABYLON.LensFlare = LensFlare;
  65476. })(BABYLON || (BABYLON = {}));
  65477. //# sourceMappingURL=babylon.lensFlare.js.map
  65478. var BABYLON;
  65479. (function (BABYLON) {
  65480. var LensFlareSystem = /** @class */ (function () {
  65481. function LensFlareSystem(name, emitter, scene) {
  65482. this.name = name;
  65483. this.lensFlares = new Array();
  65484. this.borderLimit = 300;
  65485. this.viewportBorder = 0;
  65486. this.layerMask = 0x0FFFFFFF;
  65487. this._vertexBuffers = {};
  65488. this._isEnabled = true;
  65489. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65490. this._emitter = emitter;
  65491. this.id = name;
  65492. scene.lensFlareSystems.push(this);
  65493. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  65494. var engine = scene.getEngine();
  65495. // VBO
  65496. var vertices = [];
  65497. vertices.push(1, 1);
  65498. vertices.push(-1, 1);
  65499. vertices.push(-1, -1);
  65500. vertices.push(1, -1);
  65501. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65502. // Indices
  65503. var indices = [];
  65504. indices.push(0);
  65505. indices.push(1);
  65506. indices.push(2);
  65507. indices.push(0);
  65508. indices.push(2);
  65509. indices.push(3);
  65510. this._indexBuffer = engine.createIndexBuffer(indices);
  65511. // Effects
  65512. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  65513. }
  65514. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  65515. get: function () {
  65516. return this._isEnabled;
  65517. },
  65518. set: function (value) {
  65519. this._isEnabled = value;
  65520. },
  65521. enumerable: true,
  65522. configurable: true
  65523. });
  65524. LensFlareSystem.prototype.getScene = function () {
  65525. return this._scene;
  65526. };
  65527. LensFlareSystem.prototype.getEmitter = function () {
  65528. return this._emitter;
  65529. };
  65530. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  65531. this._emitter = newEmitter;
  65532. };
  65533. LensFlareSystem.prototype.getEmitterPosition = function () {
  65534. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  65535. };
  65536. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  65537. var position = this.getEmitterPosition();
  65538. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  65539. this._positionX = position.x;
  65540. this._positionY = position.y;
  65541. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  65542. if (this.viewportBorder > 0) {
  65543. globalViewport.x -= this.viewportBorder;
  65544. globalViewport.y -= this.viewportBorder;
  65545. globalViewport.width += this.viewportBorder * 2;
  65546. globalViewport.height += this.viewportBorder * 2;
  65547. position.x += this.viewportBorder;
  65548. position.y += this.viewportBorder;
  65549. this._positionX += this.viewportBorder;
  65550. this._positionY += this.viewportBorder;
  65551. }
  65552. if (position.z > 0) {
  65553. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  65554. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  65555. return true;
  65556. }
  65557. return true;
  65558. }
  65559. return false;
  65560. };
  65561. LensFlareSystem.prototype._isVisible = function () {
  65562. if (!this._isEnabled || !this._scene.activeCamera) {
  65563. return false;
  65564. }
  65565. var emitterPosition = this.getEmitterPosition();
  65566. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  65567. var distance = direction.length();
  65568. direction.normalize();
  65569. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  65570. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  65571. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  65572. };
  65573. LensFlareSystem.prototype.render = function () {
  65574. if (!this._effect.isReady() || !this._scene.activeCamera)
  65575. return false;
  65576. var engine = this._scene.getEngine();
  65577. var viewport = this._scene.activeCamera.viewport;
  65578. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  65579. // Position
  65580. if (!this.computeEffectivePosition(globalViewport)) {
  65581. return false;
  65582. }
  65583. // Visibility
  65584. if (!this._isVisible()) {
  65585. return false;
  65586. }
  65587. // Intensity
  65588. var awayX;
  65589. var awayY;
  65590. if (this._positionX < this.borderLimit + globalViewport.x) {
  65591. awayX = this.borderLimit + globalViewport.x - this._positionX;
  65592. }
  65593. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  65594. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  65595. }
  65596. else {
  65597. awayX = 0;
  65598. }
  65599. if (this._positionY < this.borderLimit + globalViewport.y) {
  65600. awayY = this.borderLimit + globalViewport.y - this._positionY;
  65601. }
  65602. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  65603. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  65604. }
  65605. else {
  65606. awayY = 0;
  65607. }
  65608. var away = (awayX > awayY) ? awayX : awayY;
  65609. away -= this.viewportBorder;
  65610. if (away > this.borderLimit) {
  65611. away = this.borderLimit;
  65612. }
  65613. var intensity = 1.0 - (away / this.borderLimit);
  65614. if (intensity < 0) {
  65615. return false;
  65616. }
  65617. if (intensity > 1.0) {
  65618. intensity = 1.0;
  65619. }
  65620. if (this.viewportBorder > 0) {
  65621. globalViewport.x += this.viewportBorder;
  65622. globalViewport.y += this.viewportBorder;
  65623. globalViewport.width -= this.viewportBorder * 2;
  65624. globalViewport.height -= this.viewportBorder * 2;
  65625. this._positionX -= this.viewportBorder;
  65626. this._positionY -= this.viewportBorder;
  65627. }
  65628. // Position
  65629. var centerX = globalViewport.x + globalViewport.width / 2;
  65630. var centerY = globalViewport.y + globalViewport.height / 2;
  65631. var distX = centerX - this._positionX;
  65632. var distY = centerY - this._positionY;
  65633. // Effects
  65634. engine.enableEffect(this._effect);
  65635. engine.setState(false);
  65636. engine.setDepthBuffer(false);
  65637. // VBOs
  65638. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65639. // Flares
  65640. for (var index = 0; index < this.lensFlares.length; index++) {
  65641. var flare = this.lensFlares[index];
  65642. engine.setAlphaMode(flare.alphaMode);
  65643. var x = centerX - (distX * flare.position);
  65644. var y = centerY - (distY * flare.position);
  65645. var cw = flare.size;
  65646. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  65647. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  65648. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  65649. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  65650. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  65651. // Texture
  65652. this._effect.setTexture("textureSampler", flare.texture);
  65653. // Color
  65654. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  65655. // Draw order
  65656. engine.draw(true, 0, 6);
  65657. }
  65658. engine.setDepthBuffer(true);
  65659. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65660. return true;
  65661. };
  65662. LensFlareSystem.prototype.dispose = function () {
  65663. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65664. if (vertexBuffer) {
  65665. vertexBuffer.dispose();
  65666. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65667. }
  65668. if (this._indexBuffer) {
  65669. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65670. this._indexBuffer = null;
  65671. }
  65672. while (this.lensFlares.length) {
  65673. this.lensFlares[0].dispose();
  65674. }
  65675. // Remove from scene
  65676. var index = this._scene.lensFlareSystems.indexOf(this);
  65677. this._scene.lensFlareSystems.splice(index, 1);
  65678. };
  65679. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  65680. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  65681. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  65682. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  65683. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  65684. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  65685. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  65686. var parsedFlare = parsedLensFlareSystem.flares[index];
  65687. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  65688. }
  65689. return lensFlareSystem;
  65690. };
  65691. LensFlareSystem.prototype.serialize = function () {
  65692. var serializationObject = {};
  65693. serializationObject.id = this.id;
  65694. serializationObject.name = this.name;
  65695. serializationObject.emitterId = this.getEmitter().id;
  65696. serializationObject.borderLimit = this.borderLimit;
  65697. serializationObject.flares = [];
  65698. for (var index = 0; index < this.lensFlares.length; index++) {
  65699. var flare = this.lensFlares[index];
  65700. serializationObject.flares.push({
  65701. size: flare.size,
  65702. position: flare.position,
  65703. color: flare.color.asArray(),
  65704. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  65705. });
  65706. }
  65707. return serializationObject;
  65708. };
  65709. return LensFlareSystem;
  65710. }());
  65711. BABYLON.LensFlareSystem = LensFlareSystem;
  65712. })(BABYLON || (BABYLON = {}));
  65713. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  65714. var BABYLON;
  65715. (function (BABYLON) {
  65716. /**
  65717. * This is a holder class for the physics joint created by the physics plugin.
  65718. * It holds a set of functions to control the underlying joint.
  65719. */
  65720. var PhysicsJoint = /** @class */ (function () {
  65721. function PhysicsJoint(type, jointData) {
  65722. this.type = type;
  65723. this.jointData = jointData;
  65724. jointData.nativeParams = jointData.nativeParams || {};
  65725. }
  65726. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  65727. get: function () {
  65728. return this._physicsJoint;
  65729. },
  65730. set: function (newJoint) {
  65731. if (this._physicsJoint) {
  65732. //remove from the wolrd
  65733. }
  65734. this._physicsJoint = newJoint;
  65735. },
  65736. enumerable: true,
  65737. configurable: true
  65738. });
  65739. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  65740. set: function (physicsPlugin) {
  65741. this._physicsPlugin = physicsPlugin;
  65742. },
  65743. enumerable: true,
  65744. configurable: true
  65745. });
  65746. /**
  65747. * Execute a function that is physics-plugin specific.
  65748. * @param {Function} func the function that will be executed.
  65749. * It accepts two parameters: the physics world and the physics joint.
  65750. */
  65751. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  65752. func(this._physicsPlugin.world, this._physicsJoint);
  65753. };
  65754. //TODO check if the native joints are the same
  65755. //Joint Types
  65756. PhysicsJoint.DistanceJoint = 0;
  65757. PhysicsJoint.HingeJoint = 1;
  65758. PhysicsJoint.BallAndSocketJoint = 2;
  65759. PhysicsJoint.WheelJoint = 3;
  65760. PhysicsJoint.SliderJoint = 4;
  65761. //OIMO
  65762. PhysicsJoint.PrismaticJoint = 5;
  65763. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  65764. PhysicsJoint.UniversalJoint = 6;
  65765. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  65766. //Cannon
  65767. //Similar to a Ball-Joint. Different in params
  65768. PhysicsJoint.PointToPointJoint = 8;
  65769. //Cannon only at the moment
  65770. PhysicsJoint.SpringJoint = 9;
  65771. PhysicsJoint.LockJoint = 10;
  65772. return PhysicsJoint;
  65773. }());
  65774. BABYLON.PhysicsJoint = PhysicsJoint;
  65775. /**
  65776. * A class representing a physics distance joint.
  65777. */
  65778. var DistanceJoint = /** @class */ (function (_super) {
  65779. __extends(DistanceJoint, _super);
  65780. function DistanceJoint(jointData) {
  65781. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  65782. }
  65783. /**
  65784. * Update the predefined distance.
  65785. */
  65786. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  65787. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  65788. };
  65789. return DistanceJoint;
  65790. }(PhysicsJoint));
  65791. BABYLON.DistanceJoint = DistanceJoint;
  65792. var MotorEnabledJoint = /** @class */ (function (_super) {
  65793. __extends(MotorEnabledJoint, _super);
  65794. function MotorEnabledJoint(type, jointData) {
  65795. return _super.call(this, type, jointData) || this;
  65796. }
  65797. /**
  65798. * Set the motor values.
  65799. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65800. * @param {number} force the force to apply
  65801. * @param {number} maxForce max force for this motor.
  65802. */
  65803. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  65804. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65805. };
  65806. /**
  65807. * Set the motor's limits.
  65808. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65809. */
  65810. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65811. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65812. };
  65813. return MotorEnabledJoint;
  65814. }(PhysicsJoint));
  65815. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  65816. /**
  65817. * This class represents a single hinge physics joint
  65818. */
  65819. var HingeJoint = /** @class */ (function (_super) {
  65820. __extends(HingeJoint, _super);
  65821. function HingeJoint(jointData) {
  65822. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  65823. }
  65824. /**
  65825. * Set the motor values.
  65826. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65827. * @param {number} force the force to apply
  65828. * @param {number} maxForce max force for this motor.
  65829. */
  65830. HingeJoint.prototype.setMotor = function (force, maxForce) {
  65831. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65832. };
  65833. /**
  65834. * Set the motor's limits.
  65835. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65836. */
  65837. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65838. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65839. };
  65840. return HingeJoint;
  65841. }(MotorEnabledJoint));
  65842. BABYLON.HingeJoint = HingeJoint;
  65843. /**
  65844. * This class represents a dual hinge physics joint (same as wheel joint)
  65845. */
  65846. var Hinge2Joint = /** @class */ (function (_super) {
  65847. __extends(Hinge2Joint, _super);
  65848. function Hinge2Joint(jointData) {
  65849. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  65850. }
  65851. /**
  65852. * Set the motor values.
  65853. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65854. * @param {number} force the force to apply
  65855. * @param {number} maxForce max force for this motor.
  65856. * @param {motorIndex} the motor's index, 0 or 1.
  65857. */
  65858. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  65859. if (motorIndex === void 0) { motorIndex = 0; }
  65860. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  65861. };
  65862. /**
  65863. * Set the motor limits.
  65864. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65865. * @param {number} upperLimit the upper limit
  65866. * @param {number} lowerLimit lower limit
  65867. * @param {motorIndex} the motor's index, 0 or 1.
  65868. */
  65869. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  65870. if (motorIndex === void 0) { motorIndex = 0; }
  65871. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  65872. };
  65873. return Hinge2Joint;
  65874. }(MotorEnabledJoint));
  65875. BABYLON.Hinge2Joint = Hinge2Joint;
  65876. })(BABYLON || (BABYLON = {}));
  65877. //# sourceMappingURL=babylon.physicsJoint.js.map
  65878. var BABYLON;
  65879. (function (BABYLON) {
  65880. var PhysicsImpostor = /** @class */ (function () {
  65881. function PhysicsImpostor(object, type, _options, _scene) {
  65882. if (_options === void 0) { _options = { mass: 0 }; }
  65883. var _this = this;
  65884. this.object = object;
  65885. this.type = type;
  65886. this._options = _options;
  65887. this._scene = _scene;
  65888. this._bodyUpdateRequired = false;
  65889. this._onBeforePhysicsStepCallbacks = new Array();
  65890. this._onAfterPhysicsStepCallbacks = new Array();
  65891. this._onPhysicsCollideCallbacks = [];
  65892. this._deltaPosition = BABYLON.Vector3.Zero();
  65893. this._isDisposed = false;
  65894. //temp variables for parent rotation calculations
  65895. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  65896. this._tmpQuat = new BABYLON.Quaternion();
  65897. this._tmpQuat2 = new BABYLON.Quaternion();
  65898. /**
  65899. * this function is executed by the physics engine.
  65900. */
  65901. this.beforeStep = function () {
  65902. if (!_this._physicsEngine) {
  65903. return;
  65904. }
  65905. _this.object.translate(_this._deltaPosition, -1);
  65906. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  65907. _this.object.computeWorldMatrix(false);
  65908. if (_this.object.parent && _this.object.rotationQuaternion) {
  65909. _this.getParentsRotation();
  65910. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  65911. }
  65912. else {
  65913. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  65914. }
  65915. if (!_this._options.disableBidirectionalTransformation) {
  65916. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  65917. }
  65918. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  65919. func(_this);
  65920. });
  65921. };
  65922. /**
  65923. * this function is executed by the physics engine.
  65924. */
  65925. this.afterStep = function () {
  65926. if (!_this._physicsEngine) {
  65927. return;
  65928. }
  65929. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  65930. func(_this);
  65931. });
  65932. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  65933. // object has now its world rotation. needs to be converted to local.
  65934. if (_this.object.parent && _this.object.rotationQuaternion) {
  65935. _this.getParentsRotation();
  65936. _this._tmpQuat.conjugateInPlace();
  65937. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  65938. }
  65939. // take the position set and make it the absolute position of this object.
  65940. _this.object.setAbsolutePosition(_this.object.position);
  65941. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  65942. _this.object.translate(_this._deltaPosition, 1);
  65943. };
  65944. /**
  65945. * Legacy collision detection event support
  65946. */
  65947. this.onCollideEvent = null;
  65948. //event and body object due to cannon's event-based architecture.
  65949. this.onCollide = function (e) {
  65950. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  65951. return;
  65952. }
  65953. if (!_this._physicsEngine) {
  65954. return;
  65955. }
  65956. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  65957. if (otherImpostor) {
  65958. // Legacy collision detection event support
  65959. if (_this.onCollideEvent) {
  65960. _this.onCollideEvent(_this, otherImpostor);
  65961. }
  65962. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  65963. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  65964. }).forEach(function (obj) {
  65965. obj.callback(_this, otherImpostor);
  65966. });
  65967. }
  65968. };
  65969. //sanity check!
  65970. if (!this.object) {
  65971. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  65972. return;
  65973. }
  65974. //legacy support for old syntax.
  65975. if (!this._scene && object.getScene) {
  65976. this._scene = object.getScene();
  65977. }
  65978. if (!this._scene) {
  65979. return;
  65980. }
  65981. this._physicsEngine = this._scene.getPhysicsEngine();
  65982. if (!this._physicsEngine) {
  65983. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  65984. }
  65985. else {
  65986. //set the object's quaternion, if not set
  65987. if (!this.object.rotationQuaternion) {
  65988. if (this.object.rotation) {
  65989. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  65990. }
  65991. else {
  65992. this.object.rotationQuaternion = new BABYLON.Quaternion();
  65993. }
  65994. }
  65995. //default options params
  65996. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  65997. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  65998. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  65999. this._joints = [];
  66000. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  66001. if (!this.object.parent || this._options.ignoreParent) {
  66002. this._init();
  66003. }
  66004. else if (this.object.parent.physicsImpostor) {
  66005. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  66006. }
  66007. }
  66008. }
  66009. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  66010. get: function () {
  66011. return this._isDisposed;
  66012. },
  66013. enumerable: true,
  66014. configurable: true
  66015. });
  66016. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  66017. get: function () {
  66018. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  66019. },
  66020. set: function (value) {
  66021. this.setMass(value);
  66022. },
  66023. enumerable: true,
  66024. configurable: true
  66025. });
  66026. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  66027. get: function () {
  66028. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  66029. },
  66030. set: function (value) {
  66031. if (!this._physicsEngine) {
  66032. return;
  66033. }
  66034. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  66035. },
  66036. enumerable: true,
  66037. configurable: true
  66038. });
  66039. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  66040. get: function () {
  66041. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  66042. },
  66043. set: function (value) {
  66044. if (!this._physicsEngine) {
  66045. return;
  66046. }
  66047. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  66048. },
  66049. enumerable: true,
  66050. configurable: true
  66051. });
  66052. /**
  66053. * This function will completly initialize this impostor.
  66054. * It will create a new body - but only if this mesh has no parent.
  66055. * If it has, this impostor will not be used other than to define the impostor
  66056. * of the child mesh.
  66057. */
  66058. PhysicsImpostor.prototype._init = function () {
  66059. if (!this._physicsEngine) {
  66060. return;
  66061. }
  66062. this._physicsEngine.removeImpostor(this);
  66063. this.physicsBody = null;
  66064. this._parent = this._parent || this._getPhysicsParent();
  66065. if (!this.parent || this._options.ignoreParent) {
  66066. this._physicsEngine.addImpostor(this);
  66067. }
  66068. };
  66069. PhysicsImpostor.prototype._getPhysicsParent = function () {
  66070. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  66071. var parentMesh = this.object.parent;
  66072. return parentMesh.physicsImpostor;
  66073. }
  66074. return null;
  66075. };
  66076. /**
  66077. * Should a new body be generated.
  66078. */
  66079. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  66080. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  66081. };
  66082. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  66083. this.forceUpdate();
  66084. };
  66085. /**
  66086. * Force a regeneration of this or the parent's impostor's body.
  66087. * Use under cautious - This will remove all joints already implemented.
  66088. */
  66089. PhysicsImpostor.prototype.forceUpdate = function () {
  66090. this._init();
  66091. if (this.parent && !this._options.ignoreParent) {
  66092. this.parent.forceUpdate();
  66093. }
  66094. };
  66095. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  66096. /*public get mesh(): AbstractMesh {
  66097. return this._mesh;
  66098. }*/
  66099. /**
  66100. * Gets the body that holds this impostor. Either its own, or its parent.
  66101. */
  66102. get: function () {
  66103. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  66104. },
  66105. /**
  66106. * Set the physics body. Used mainly by the physics engine/plugin
  66107. */
  66108. set: function (physicsBody) {
  66109. if (this._physicsBody && this._physicsEngine) {
  66110. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  66111. }
  66112. this._physicsBody = physicsBody;
  66113. this.resetUpdateFlags();
  66114. },
  66115. enumerable: true,
  66116. configurable: true
  66117. });
  66118. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  66119. get: function () {
  66120. return !this._options.ignoreParent && this._parent ? this._parent : null;
  66121. },
  66122. set: function (value) {
  66123. this._parent = value;
  66124. },
  66125. enumerable: true,
  66126. configurable: true
  66127. });
  66128. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  66129. this._bodyUpdateRequired = false;
  66130. };
  66131. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  66132. if (this.object.getBoundingInfo) {
  66133. var q = this.object.rotationQuaternion;
  66134. //reset rotation
  66135. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  66136. //calculate the world matrix with no rotation
  66137. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66138. var boundingInfo = this.object.getBoundingInfo();
  66139. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  66140. //bring back the rotation
  66141. this.object.rotationQuaternion = q;
  66142. //calculate the world matrix with the new rotation
  66143. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66144. return size;
  66145. }
  66146. else {
  66147. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  66148. }
  66149. };
  66150. PhysicsImpostor.prototype.getObjectCenter = function () {
  66151. if (this.object.getBoundingInfo) {
  66152. var boundingInfo = this.object.getBoundingInfo();
  66153. return boundingInfo.boundingBox.centerWorld;
  66154. }
  66155. else {
  66156. return this.object.position;
  66157. }
  66158. };
  66159. /**
  66160. * Get a specific parametes from the options parameter.
  66161. */
  66162. PhysicsImpostor.prototype.getParam = function (paramName) {
  66163. return this._options[paramName];
  66164. };
  66165. /**
  66166. * Sets a specific parameter in the options given to the physics plugin
  66167. */
  66168. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  66169. this._options[paramName] = value;
  66170. this._bodyUpdateRequired = true;
  66171. };
  66172. /**
  66173. * Specifically change the body's mass option. Won't recreate the physics body object
  66174. */
  66175. PhysicsImpostor.prototype.setMass = function (mass) {
  66176. if (this.getParam("mass") !== mass) {
  66177. this.setParam("mass", mass);
  66178. }
  66179. if (this._physicsEngine) {
  66180. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  66181. }
  66182. };
  66183. PhysicsImpostor.prototype.getLinearVelocity = function () {
  66184. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  66185. };
  66186. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  66187. if (this._physicsEngine) {
  66188. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  66189. }
  66190. };
  66191. PhysicsImpostor.prototype.getAngularVelocity = function () {
  66192. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  66193. };
  66194. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  66195. if (this._physicsEngine) {
  66196. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  66197. }
  66198. };
  66199. /**
  66200. * Execute a function with the physics plugin native code.
  66201. * Provide a function the will have two variables - the world object and the physics body object.
  66202. */
  66203. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  66204. if (this._physicsEngine) {
  66205. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  66206. }
  66207. };
  66208. /**
  66209. * Register a function that will be executed before the physics world is stepping forward.
  66210. */
  66211. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  66212. this._onBeforePhysicsStepCallbacks.push(func);
  66213. };
  66214. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  66215. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  66216. if (index > -1) {
  66217. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  66218. }
  66219. else {
  66220. BABYLON.Tools.Warn("Function to remove was not found");
  66221. }
  66222. };
  66223. /**
  66224. * Register a function that will be executed after the physics step
  66225. */
  66226. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  66227. this._onAfterPhysicsStepCallbacks.push(func);
  66228. };
  66229. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  66230. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  66231. if (index > -1) {
  66232. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  66233. }
  66234. else {
  66235. BABYLON.Tools.Warn("Function to remove was not found");
  66236. }
  66237. };
  66238. /**
  66239. * register a function that will be executed when this impostor collides against a different body.
  66240. */
  66241. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  66242. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  66243. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  66244. };
  66245. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  66246. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  66247. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  66248. if (index > -1) {
  66249. this._onPhysicsCollideCallbacks.splice(index, 1);
  66250. }
  66251. else {
  66252. BABYLON.Tools.Warn("Function to remove was not found");
  66253. }
  66254. };
  66255. PhysicsImpostor.prototype.getParentsRotation = function () {
  66256. var parent = this.object.parent;
  66257. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  66258. while (parent) {
  66259. if (parent.rotationQuaternion) {
  66260. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  66261. }
  66262. else {
  66263. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  66264. }
  66265. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  66266. parent = parent.parent;
  66267. }
  66268. return this._tmpQuat;
  66269. };
  66270. /**
  66271. * Apply a force
  66272. */
  66273. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  66274. if (this._physicsEngine) {
  66275. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  66276. }
  66277. return this;
  66278. };
  66279. /**
  66280. * Apply an impulse
  66281. */
  66282. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  66283. if (this._physicsEngine) {
  66284. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  66285. }
  66286. return this;
  66287. };
  66288. /**
  66289. * A help function to create a joint.
  66290. */
  66291. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  66292. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  66293. this.addJoint(otherImpostor, joint);
  66294. return this;
  66295. };
  66296. /**
  66297. * Add a joint to this impostor with a different impostor.
  66298. */
  66299. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  66300. this._joints.push({
  66301. otherImpostor: otherImpostor,
  66302. joint: joint
  66303. });
  66304. if (this._physicsEngine) {
  66305. this._physicsEngine.addJoint(this, otherImpostor, joint);
  66306. }
  66307. return this;
  66308. };
  66309. /**
  66310. * Will keep this body still, in a sleep mode.
  66311. */
  66312. PhysicsImpostor.prototype.sleep = function () {
  66313. if (this._physicsEngine) {
  66314. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  66315. }
  66316. return this;
  66317. };
  66318. /**
  66319. * Wake the body up.
  66320. */
  66321. PhysicsImpostor.prototype.wakeUp = function () {
  66322. if (this._physicsEngine) {
  66323. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  66324. }
  66325. return this;
  66326. };
  66327. PhysicsImpostor.prototype.clone = function (newObject) {
  66328. if (!newObject)
  66329. return null;
  66330. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  66331. };
  66332. PhysicsImpostor.prototype.dispose = function () {
  66333. var _this = this;
  66334. //no dispose if no physics engine is available.
  66335. if (!this._physicsEngine) {
  66336. return;
  66337. }
  66338. this._joints.forEach(function (j) {
  66339. if (_this._physicsEngine) {
  66340. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  66341. }
  66342. });
  66343. //dispose the physics body
  66344. this._physicsEngine.removeImpostor(this);
  66345. if (this.parent) {
  66346. this.parent.forceUpdate();
  66347. }
  66348. else {
  66349. /*this._object.getChildMeshes().forEach(function(mesh) {
  66350. if (mesh.physicsImpostor) {
  66351. if (disposeChildren) {
  66352. mesh.physicsImpostor.dispose();
  66353. mesh.physicsImpostor = null;
  66354. }
  66355. }
  66356. })*/
  66357. }
  66358. this._isDisposed = true;
  66359. };
  66360. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  66361. this._deltaPosition.copyFrom(position);
  66362. };
  66363. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  66364. if (!this._deltaRotation) {
  66365. this._deltaRotation = new BABYLON.Quaternion();
  66366. }
  66367. this._deltaRotation.copyFrom(rotation);
  66368. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  66369. };
  66370. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  66371. if (this._physicsEngine) {
  66372. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  66373. }
  66374. return this;
  66375. };
  66376. PhysicsImpostor.prototype.getRadius = function () {
  66377. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  66378. };
  66379. /**
  66380. * Sync a bone with this impostor
  66381. * @param bone The bone to sync to the impostor.
  66382. * @param boneMesh The mesh that the bone is influencing.
  66383. * @param jointPivot The pivot of the joint / bone in local space.
  66384. * @param distToJoint Optional distance from the impostor to the joint.
  66385. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  66386. */
  66387. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  66388. var tempVec = PhysicsImpostor._tmpVecs[0];
  66389. var mesh = this.object;
  66390. if (mesh.rotationQuaternion) {
  66391. if (adjustRotation) {
  66392. var tempQuat = PhysicsImpostor._tmpQuat;
  66393. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  66394. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  66395. }
  66396. else {
  66397. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  66398. }
  66399. }
  66400. tempVec.x = 0;
  66401. tempVec.y = 0;
  66402. tempVec.z = 0;
  66403. if (jointPivot) {
  66404. tempVec.x = jointPivot.x;
  66405. tempVec.y = jointPivot.y;
  66406. tempVec.z = jointPivot.z;
  66407. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  66408. if (distToJoint === undefined || distToJoint === null) {
  66409. distToJoint = jointPivot.length();
  66410. }
  66411. tempVec.x *= distToJoint;
  66412. tempVec.y *= distToJoint;
  66413. tempVec.z *= distToJoint;
  66414. }
  66415. if (bone.getParent()) {
  66416. tempVec.addInPlace(mesh.getAbsolutePosition());
  66417. bone.setAbsolutePosition(tempVec, boneMesh);
  66418. }
  66419. else {
  66420. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  66421. boneMesh.position.x -= tempVec.x;
  66422. boneMesh.position.y -= tempVec.y;
  66423. boneMesh.position.z -= tempVec.z;
  66424. }
  66425. };
  66426. /**
  66427. * Sync impostor to a bone
  66428. * @param bone The bone that the impostor will be synced to.
  66429. * @param boneMesh The mesh that the bone is influencing.
  66430. * @param jointPivot The pivot of the joint / bone in local space.
  66431. * @param distToJoint Optional distance from the impostor to the joint.
  66432. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  66433. * @param boneAxis Optional vector3 axis the bone is aligned with
  66434. */
  66435. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  66436. var mesh = this.object;
  66437. if (mesh.rotationQuaternion) {
  66438. if (adjustRotation) {
  66439. var tempQuat = PhysicsImpostor._tmpQuat;
  66440. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  66441. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  66442. }
  66443. else {
  66444. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  66445. }
  66446. }
  66447. var pos = PhysicsImpostor._tmpVecs[0];
  66448. var boneDir = PhysicsImpostor._tmpVecs[1];
  66449. if (!boneAxis) {
  66450. boneAxis = PhysicsImpostor._tmpVecs[2];
  66451. boneAxis.x = 0;
  66452. boneAxis.y = 1;
  66453. boneAxis.z = 0;
  66454. }
  66455. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  66456. bone.getAbsolutePositionToRef(boneMesh, pos);
  66457. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  66458. distToJoint = jointPivot.length();
  66459. }
  66460. if (distToJoint !== undefined && distToJoint !== null) {
  66461. pos.x += boneDir.x * distToJoint;
  66462. pos.y += boneDir.y * distToJoint;
  66463. pos.z += boneDir.z * distToJoint;
  66464. }
  66465. mesh.setAbsolutePosition(pos);
  66466. };
  66467. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  66468. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  66469. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66470. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  66471. //Impostor types
  66472. PhysicsImpostor.NoImpostor = 0;
  66473. PhysicsImpostor.SphereImpostor = 1;
  66474. PhysicsImpostor.BoxImpostor = 2;
  66475. PhysicsImpostor.PlaneImpostor = 3;
  66476. PhysicsImpostor.MeshImpostor = 4;
  66477. PhysicsImpostor.CylinderImpostor = 7;
  66478. PhysicsImpostor.ParticleImpostor = 8;
  66479. PhysicsImpostor.HeightmapImpostor = 9;
  66480. return PhysicsImpostor;
  66481. }());
  66482. BABYLON.PhysicsImpostor = PhysicsImpostor;
  66483. })(BABYLON || (BABYLON = {}));
  66484. //# sourceMappingURL=babylon.physicsImpostor.js.map
  66485. var BABYLON;
  66486. (function (BABYLON) {
  66487. var PhysicsEngine = /** @class */ (function () {
  66488. function PhysicsEngine(gravity, _physicsPlugin) {
  66489. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  66490. this._physicsPlugin = _physicsPlugin;
  66491. //new methods and parameters
  66492. this._impostors = [];
  66493. this._joints = [];
  66494. if (!this._physicsPlugin.isSupported()) {
  66495. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  66496. + "Please make sure it is included.");
  66497. }
  66498. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  66499. this.setGravity(gravity);
  66500. this.setTimeStep();
  66501. }
  66502. PhysicsEngine.prototype.setGravity = function (gravity) {
  66503. this.gravity = gravity;
  66504. this._physicsPlugin.setGravity(this.gravity);
  66505. };
  66506. /**
  66507. * Set the time step of the physics engine.
  66508. * default is 1/60.
  66509. * To slow it down, enter 1/600 for example.
  66510. * To speed it up, 1/30
  66511. * @param {number} newTimeStep the new timestep to apply to this world.
  66512. */
  66513. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  66514. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  66515. this._physicsPlugin.setTimeStep(newTimeStep);
  66516. };
  66517. /**
  66518. * Get the time step of the physics engine.
  66519. */
  66520. PhysicsEngine.prototype.getTimeStep = function () {
  66521. return this._physicsPlugin.getTimeStep();
  66522. };
  66523. PhysicsEngine.prototype.dispose = function () {
  66524. this._impostors.forEach(function (impostor) {
  66525. impostor.dispose();
  66526. });
  66527. this._physicsPlugin.dispose();
  66528. };
  66529. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  66530. return this._physicsPlugin.name;
  66531. };
  66532. /**
  66533. * Adding a new impostor for the impostor tracking.
  66534. * This will be done by the impostor itself.
  66535. * @param {PhysicsImpostor} impostor the impostor to add
  66536. */
  66537. PhysicsEngine.prototype.addImpostor = function (impostor) {
  66538. impostor.uniqueId = this._impostors.push(impostor);
  66539. //if no parent, generate the body
  66540. if (!impostor.parent) {
  66541. this._physicsPlugin.generatePhysicsBody(impostor);
  66542. }
  66543. };
  66544. /**
  66545. * Remove an impostor from the engine.
  66546. * This impostor and its mesh will not longer be updated by the physics engine.
  66547. * @param {PhysicsImpostor} impostor the impostor to remove
  66548. */
  66549. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  66550. var index = this._impostors.indexOf(impostor);
  66551. if (index > -1) {
  66552. var removed = this._impostors.splice(index, 1);
  66553. //Is it needed?
  66554. if (removed.length) {
  66555. //this will also remove it from the world.
  66556. removed[0].physicsBody = null;
  66557. }
  66558. }
  66559. };
  66560. /**
  66561. * Add a joint to the physics engine
  66562. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  66563. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  66564. * @param {PhysicsJoint} the joint that will connect both impostors.
  66565. */
  66566. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  66567. var impostorJoint = {
  66568. mainImpostor: mainImpostor,
  66569. connectedImpostor: connectedImpostor,
  66570. joint: joint
  66571. };
  66572. joint.physicsPlugin = this._physicsPlugin;
  66573. this._joints.push(impostorJoint);
  66574. this._physicsPlugin.generateJoint(impostorJoint);
  66575. };
  66576. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  66577. var matchingJoints = this._joints.filter(function (impostorJoint) {
  66578. return (impostorJoint.connectedImpostor === connectedImpostor
  66579. && impostorJoint.joint === joint
  66580. && impostorJoint.mainImpostor === mainImpostor);
  66581. });
  66582. if (matchingJoints.length) {
  66583. this._physicsPlugin.removeJoint(matchingJoints[0]);
  66584. //TODO remove it from the list as well
  66585. }
  66586. };
  66587. /**
  66588. * Called by the scene. no need to call it.
  66589. */
  66590. PhysicsEngine.prototype._step = function (delta) {
  66591. var _this = this;
  66592. //check if any mesh has no body / requires an update
  66593. this._impostors.forEach(function (impostor) {
  66594. if (impostor.isBodyInitRequired()) {
  66595. _this._physicsPlugin.generatePhysicsBody(impostor);
  66596. }
  66597. });
  66598. if (delta > 0.1) {
  66599. delta = 0.1;
  66600. }
  66601. else if (delta <= 0) {
  66602. delta = 1.0 / 60.0;
  66603. }
  66604. this._physicsPlugin.executeStep(delta, this._impostors);
  66605. };
  66606. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  66607. return this._physicsPlugin;
  66608. };
  66609. PhysicsEngine.prototype.getImpostors = function () {
  66610. return this._impostors;
  66611. };
  66612. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  66613. for (var i = 0; i < this._impostors.length; ++i) {
  66614. if (this._impostors[i].object === object) {
  66615. return this._impostors[i];
  66616. }
  66617. }
  66618. return null;
  66619. };
  66620. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  66621. for (var i = 0; i < this._impostors.length; ++i) {
  66622. if (this._impostors[i].physicsBody === body) {
  66623. return this._impostors[i];
  66624. }
  66625. }
  66626. return null;
  66627. };
  66628. // Statics
  66629. PhysicsEngine.Epsilon = 0.001;
  66630. return PhysicsEngine;
  66631. }());
  66632. BABYLON.PhysicsEngine = PhysicsEngine;
  66633. })(BABYLON || (BABYLON = {}));
  66634. //# sourceMappingURL=babylon.physicsEngine.js.map
  66635. var BABYLON;
  66636. (function (BABYLON) {
  66637. /**
  66638. * The strenght of the force in correspondence to the distance of the affected object
  66639. */
  66640. var PhysicsRadialImpulseFallof;
  66641. (function (PhysicsRadialImpulseFallof) {
  66642. PhysicsRadialImpulseFallof[PhysicsRadialImpulseFallof["Constant"] = 0] = "Constant";
  66643. PhysicsRadialImpulseFallof[PhysicsRadialImpulseFallof["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  66644. })(PhysicsRadialImpulseFallof = BABYLON.PhysicsRadialImpulseFallof || (BABYLON.PhysicsRadialImpulseFallof = {}));
  66645. var PhysicsHelper = /** @class */ (function () {
  66646. function PhysicsHelper(scene) {
  66647. this._scene = scene;
  66648. this._physicsEngine = this._scene.getPhysicsEngine();
  66649. if (!this._physicsEngine) {
  66650. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  66651. }
  66652. }
  66653. /**
  66654. * @param {Vector3} origin the origin of the explosion
  66655. * @param {number} radius the explosion radius
  66656. * @param {number} strength the explosion strength
  66657. * @param {PhysicsRadialImpulseFallof} falloff possible options: Constant & Linear. Defaults to Constant
  66658. */
  66659. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  66660. if (falloff === void 0) { falloff = PhysicsRadialImpulseFallof.Constant; }
  66661. if (!this._physicsEngine) {
  66662. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  66663. return null;
  66664. }
  66665. var impostors = this._physicsEngine.getImpostors();
  66666. if (impostors.length === 0) {
  66667. return null;
  66668. }
  66669. var event = new PhysicsRadialExplosionEvent(this._scene);
  66670. impostors.forEach(function (impostor) {
  66671. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  66672. if (!impostorForceAndContactPoint) {
  66673. return;
  66674. }
  66675. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  66676. });
  66677. event.cleanup(false);
  66678. return event;
  66679. };
  66680. /**
  66681. * @param {Vector3} origin the origin of the explosion
  66682. * @param {number} radius the explosion radius
  66683. * @param {number} strength the explosion strength
  66684. * @param {PhysicsRadialImpulseFallof} falloff possible options: Constant & Linear. Defaults to Constant
  66685. */
  66686. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  66687. if (falloff === void 0) { falloff = PhysicsRadialImpulseFallof.Constant; }
  66688. if (!this._physicsEngine) {
  66689. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  66690. return null;
  66691. }
  66692. var impostors = this._physicsEngine.getImpostors();
  66693. if (impostors.length === 0) {
  66694. return null;
  66695. }
  66696. var event = new PhysicsRadialExplosionEvent(this._scene);
  66697. impostors.forEach(function (impostor) {
  66698. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  66699. if (!impostorForceAndContactPoint) {
  66700. return;
  66701. }
  66702. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  66703. });
  66704. event.cleanup(false);
  66705. return event;
  66706. };
  66707. /**
  66708. * @param {Vector3} origin the origin of the explosion
  66709. * @param {number} radius the explosion radius
  66710. * @param {number} strength the explosion strength
  66711. * @param {PhysicsRadialImpulseFallof} falloff possible options: Constant & Linear. Defaults to Constant
  66712. */
  66713. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  66714. if (falloff === void 0) { falloff = PhysicsRadialImpulseFallof.Constant; }
  66715. if (!this._physicsEngine) {
  66716. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  66717. return null;
  66718. }
  66719. var impostors = this._physicsEngine.getImpostors();
  66720. if (impostors.length === 0) {
  66721. return null;
  66722. }
  66723. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  66724. event.cleanup(false);
  66725. return event;
  66726. };
  66727. return PhysicsHelper;
  66728. }());
  66729. BABYLON.PhysicsHelper = PhysicsHelper;
  66730. /***** Radial explosion *****/
  66731. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  66732. function PhysicsRadialExplosionEvent(scene) {
  66733. this._rays = [];
  66734. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  66735. this._scene = scene;
  66736. }
  66737. /**
  66738. * Returns the data related to the radial explosion event (radialSphere & rays).
  66739. * @returns {PhysicsRadialExplosionEventData}
  66740. */
  66741. PhysicsRadialExplosionEvent.prototype.getData = function () {
  66742. this._dataFetched = true;
  66743. return {
  66744. radialSphere: this._radialSphere,
  66745. rays: this._rays,
  66746. };
  66747. };
  66748. /**
  66749. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  66750. * @param impostor
  66751. * @param {Vector3} origin the origin of the explosion
  66752. * @param {number} radius the explosion radius
  66753. * @param {number} strength the explosion strength
  66754. * @param {PhysicsRadialImpulseFallof} falloff possible options: Constant & Linear
  66755. * @returns {Nullable<PhysicsForceAndContactPoint>}
  66756. */
  66757. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  66758. if (impostor.mass === 0) {
  66759. return null;
  66760. }
  66761. if (!this._intersectsWithRadialSphere(impostor, origin, radius)) {
  66762. return null;
  66763. }
  66764. var impostorObject = impostor.object;
  66765. var impostorObjectCenter = impostor.getObjectCenter();
  66766. var direction = impostorObjectCenter.subtract(origin);
  66767. var ray = new BABYLON.Ray(origin, direction, radius);
  66768. this._rays.push(ray);
  66769. var hit = ray.intersectsMesh(impostorObject);
  66770. var contactPoint = hit.pickedPoint;
  66771. if (!contactPoint) {
  66772. return null;
  66773. }
  66774. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  66775. if (distanceFromOrigin > radius) {
  66776. return null;
  66777. }
  66778. var multiplier = falloff === PhysicsRadialImpulseFallof.Constant
  66779. ? strength
  66780. : strength * (1 - (distanceFromOrigin / radius));
  66781. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  66782. return { force: force, contactPoint: contactPoint };
  66783. };
  66784. /**
  66785. * Disposes the radialSphere.
  66786. * @param {bolean} force
  66787. */
  66788. PhysicsRadialExplosionEvent.prototype.cleanup = function (force) {
  66789. var _this = this;
  66790. if (force === void 0) { force = true; }
  66791. if (force) {
  66792. this._radialSphere.dispose();
  66793. }
  66794. else {
  66795. setTimeout(function () {
  66796. if (!_this._dataFetched) {
  66797. _this._radialSphere.dispose();
  66798. }
  66799. }, 0);
  66800. }
  66801. };
  66802. /*** Helpers ***/
  66803. PhysicsRadialExplosionEvent.prototype._prepareRadialSphere = function () {
  66804. if (!this._radialSphere) {
  66805. this._radialSphere = BABYLON.MeshBuilder.CreateSphere("radialSphere", { segments: 32, diameter: 1 }, this._scene);
  66806. this._radialSphere.isVisible = false;
  66807. }
  66808. };
  66809. PhysicsRadialExplosionEvent.prototype._intersectsWithRadialSphere = function (impostor, origin, radius) {
  66810. var impostorObject = impostor.object;
  66811. this._prepareRadialSphere();
  66812. this._radialSphere.position = origin;
  66813. this._radialSphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  66814. this._radialSphere._updateBoundingInfo();
  66815. this._radialSphere.computeWorldMatrix(true);
  66816. return this._radialSphere.intersectsMesh(impostorObject, true);
  66817. };
  66818. return PhysicsRadialExplosionEvent;
  66819. }());
  66820. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  66821. /***** Gravitational Field *****/
  66822. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  66823. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  66824. if (falloff === void 0) { falloff = PhysicsRadialImpulseFallof.Constant; }
  66825. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  66826. this._physicsHelper = physicsHelper;
  66827. this._scene = scene;
  66828. this._origin = origin;
  66829. this._radius = radius;
  66830. this._strength = strength;
  66831. this._falloff = falloff;
  66832. this._tickCallback = this._tick.bind(this);
  66833. }
  66834. /**
  66835. * Returns the data related to the gravitational field event (radialSphere).
  66836. * @returns {PhysicsGravitationalFieldEventData}
  66837. */
  66838. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  66839. this._dataFetched = true;
  66840. return {
  66841. radialSphere: this._radialSphere,
  66842. };
  66843. };
  66844. /**
  66845. * Enables the gravitational field.
  66846. */
  66847. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  66848. this._tickCallback.call(this);
  66849. this._scene.registerBeforeRender(this._tickCallback);
  66850. };
  66851. /**
  66852. * Disables the gravitational field.
  66853. */
  66854. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  66855. this._scene.unregisterBeforeRender(this._tickCallback);
  66856. };
  66857. /**
  66858. * Disposes the radialSphere.
  66859. * @param {bolean} force
  66860. */
  66861. PhysicsGravitationalFieldEvent.prototype.cleanup = function (force) {
  66862. var _this = this;
  66863. if (force === void 0) { force = true; }
  66864. if (force) {
  66865. this._radialSphere.dispose();
  66866. }
  66867. else {
  66868. setTimeout(function () {
  66869. if (!_this._dataFetched) {
  66870. _this._radialSphere.dispose();
  66871. }
  66872. }, 0);
  66873. }
  66874. };
  66875. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  66876. // Since the params won't change, we fetch the event only once
  66877. if (this._radialSphere) {
  66878. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  66879. }
  66880. else {
  66881. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  66882. if (radialExplosionEvent) {
  66883. this._radialSphere = radialExplosionEvent.getData().radialSphere.clone('radialSphereClone');
  66884. }
  66885. }
  66886. };
  66887. return PhysicsGravitationalFieldEvent;
  66888. }());
  66889. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  66890. })(BABYLON || (BABYLON = {}));
  66891. //# sourceMappingURL=babylon.physicsHelper.js.map
  66892. var BABYLON;
  66893. (function (BABYLON) {
  66894. var CannonJSPlugin = /** @class */ (function () {
  66895. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  66896. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  66897. if (iterations === void 0) { iterations = 10; }
  66898. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  66899. this.name = "CannonJSPlugin";
  66900. this._physicsMaterials = new Array();
  66901. this._fixedTimeStep = 1 / 60;
  66902. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  66903. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  66904. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  66905. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  66906. this._tmpPosition = BABYLON.Vector3.Zero();
  66907. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  66908. this._tmpUnityRotation = new BABYLON.Quaternion();
  66909. if (!this.isSupported()) {
  66910. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  66911. return;
  66912. }
  66913. this.world = new this.BJSCANNON.World();
  66914. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  66915. this.world.solver.iterations = iterations;
  66916. }
  66917. CannonJSPlugin.prototype.setGravity = function (gravity) {
  66918. this.world.gravity.copy(gravity);
  66919. };
  66920. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  66921. this._fixedTimeStep = timeStep;
  66922. };
  66923. CannonJSPlugin.prototype.getTimeStep = function () {
  66924. return this._fixedTimeStep;
  66925. };
  66926. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  66927. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  66928. };
  66929. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66930. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  66931. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  66932. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  66933. };
  66934. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66935. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  66936. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  66937. impostor.physicsBody.applyForce(impulse, worldPoint);
  66938. };
  66939. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66940. //parent-child relationship. Does this impostor has a parent impostor?
  66941. if (impostor.parent) {
  66942. if (impostor.physicsBody) {
  66943. this.removePhysicsBody(impostor);
  66944. //TODO is that needed?
  66945. impostor.forceUpdate();
  66946. }
  66947. return;
  66948. }
  66949. //should a new body be created for this impostor?
  66950. if (impostor.isBodyInitRequired()) {
  66951. var shape = this._createShape(impostor);
  66952. //unregister events, if body is being changed
  66953. var oldBody = impostor.physicsBody;
  66954. if (oldBody) {
  66955. this.removePhysicsBody(impostor);
  66956. }
  66957. //create the body and material
  66958. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  66959. var bodyCreationObject = {
  66960. mass: impostor.getParam("mass"),
  66961. material: material
  66962. };
  66963. // A simple extend, in case native options were used.
  66964. var nativeOptions = impostor.getParam("nativeOptions");
  66965. for (var key in nativeOptions) {
  66966. if (nativeOptions.hasOwnProperty(key)) {
  66967. bodyCreationObject[key] = nativeOptions[key];
  66968. }
  66969. }
  66970. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  66971. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  66972. this.world.addEventListener("preStep", impostor.beforeStep);
  66973. this.world.addEventListener("postStep", impostor.afterStep);
  66974. impostor.physicsBody.addShape(shape);
  66975. this.world.add(impostor.physicsBody);
  66976. //try to keep the body moving in the right direction by taking old properties.
  66977. //Should be tested!
  66978. if (oldBody) {
  66979. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  66980. impostor.physicsBody[param].copy(oldBody[param]);
  66981. });
  66982. }
  66983. this._processChildMeshes(impostor);
  66984. }
  66985. //now update the body's transformation
  66986. this._updatePhysicsBodyTransformation(impostor);
  66987. };
  66988. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  66989. var _this = this;
  66990. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  66991. var currentRotation = mainImpostor.object.rotationQuaternion;
  66992. if (meshChildren.length) {
  66993. var processMesh = function (localPosition, mesh) {
  66994. if (!currentRotation || !mesh.rotationQuaternion) {
  66995. return;
  66996. }
  66997. var childImpostor = mesh.getPhysicsImpostor();
  66998. if (childImpostor) {
  66999. var parent = childImpostor.parent;
  67000. if (parent !== mainImpostor) {
  67001. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  67002. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  67003. if (childImpostor.physicsBody) {
  67004. _this.removePhysicsBody(childImpostor);
  67005. childImpostor.physicsBody = null;
  67006. }
  67007. childImpostor.parent = mainImpostor;
  67008. childImpostor.resetUpdateFlags();
  67009. 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));
  67010. //Add the mass of the children.
  67011. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  67012. }
  67013. }
  67014. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  67015. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  67016. };
  67017. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  67018. }
  67019. };
  67020. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  67021. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  67022. this.world.removeEventListener("preStep", impostor.beforeStep);
  67023. this.world.removeEventListener("postStep", impostor.afterStep);
  67024. this.world.remove(impostor.physicsBody);
  67025. };
  67026. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  67027. var mainBody = impostorJoint.mainImpostor.physicsBody;
  67028. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  67029. if (!mainBody || !connectedBody) {
  67030. return;
  67031. }
  67032. var constraint;
  67033. var jointData = impostorJoint.joint.jointData;
  67034. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  67035. var constraintData = {
  67036. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  67037. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  67038. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  67039. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  67040. maxForce: jointData.nativeParams.maxForce,
  67041. collideConnected: !!jointData.collision
  67042. };
  67043. switch (impostorJoint.joint.type) {
  67044. case BABYLON.PhysicsJoint.HingeJoint:
  67045. case BABYLON.PhysicsJoint.Hinge2Joint:
  67046. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  67047. break;
  67048. case BABYLON.PhysicsJoint.DistanceJoint:
  67049. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  67050. break;
  67051. case BABYLON.PhysicsJoint.SpringJoint:
  67052. var springData = jointData;
  67053. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  67054. restLength: springData.length,
  67055. stiffness: springData.stiffness,
  67056. damping: springData.damping,
  67057. localAnchorA: constraintData.pivotA,
  67058. localAnchorB: constraintData.pivotB
  67059. });
  67060. break;
  67061. case BABYLON.PhysicsJoint.LockJoint:
  67062. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  67063. break;
  67064. case BABYLON.PhysicsJoint.PointToPointJoint:
  67065. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  67066. default:
  67067. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  67068. break;
  67069. }
  67070. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  67071. constraint.collideConnected = !!jointData.collision;
  67072. impostorJoint.joint.physicsJoint = constraint;
  67073. //don't add spring as constraint, as it is not one.
  67074. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  67075. this.world.addConstraint(constraint);
  67076. }
  67077. else {
  67078. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  67079. constraint.applyForce();
  67080. });
  67081. }
  67082. };
  67083. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  67084. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  67085. };
  67086. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  67087. var index;
  67088. var mat;
  67089. for (index = 0; index < this._physicsMaterials.length; index++) {
  67090. mat = this._physicsMaterials[index];
  67091. if (mat.friction === friction && mat.restitution === restitution) {
  67092. return mat;
  67093. }
  67094. }
  67095. var currentMat = new this.BJSCANNON.Material(name);
  67096. currentMat.friction = friction;
  67097. currentMat.restitution = restitution;
  67098. this._physicsMaterials.push(currentMat);
  67099. return currentMat;
  67100. };
  67101. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  67102. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  67103. };
  67104. CannonJSPlugin.prototype._createShape = function (impostor) {
  67105. var object = impostor.object;
  67106. var returnValue;
  67107. var extendSize = impostor.getObjectExtendSize();
  67108. switch (impostor.type) {
  67109. case BABYLON.PhysicsImpostor.SphereImpostor:
  67110. var radiusX = extendSize.x;
  67111. var radiusY = extendSize.y;
  67112. var radiusZ = extendSize.z;
  67113. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  67114. break;
  67115. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  67116. case BABYLON.PhysicsImpostor.CylinderImpostor:
  67117. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  67118. break;
  67119. case BABYLON.PhysicsImpostor.BoxImpostor:
  67120. var box = extendSize.scale(0.5);
  67121. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  67122. break;
  67123. case BABYLON.PhysicsImpostor.PlaneImpostor:
  67124. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  67125. returnValue = new this.BJSCANNON.Plane();
  67126. break;
  67127. case BABYLON.PhysicsImpostor.MeshImpostor:
  67128. // should transform the vertex data to world coordinates!!
  67129. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  67130. var rawFaces = object.getIndices ? object.getIndices() : [];
  67131. if (!rawVerts)
  67132. return;
  67133. // get only scale! so the object could transform correctly.
  67134. var oldPosition = object.position.clone();
  67135. var oldRotation = object.rotation && object.rotation.clone();
  67136. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  67137. object.position.copyFromFloats(0, 0, 0);
  67138. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  67139. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  67140. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  67141. var transform = object.computeWorldMatrix(true);
  67142. // convert rawVerts to object space
  67143. var temp = new Array();
  67144. var index;
  67145. for (index = 0; index < rawVerts.length; index += 3) {
  67146. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  67147. }
  67148. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  67149. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  67150. //now set back the transformation!
  67151. object.position.copyFrom(oldPosition);
  67152. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  67153. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  67154. break;
  67155. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  67156. var oldPosition2 = object.position.clone();
  67157. var oldRotation2 = object.rotation && object.rotation.clone();
  67158. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  67159. object.position.copyFromFloats(0, 0, 0);
  67160. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  67161. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  67162. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  67163. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  67164. returnValue = this._createHeightmap(object);
  67165. object.position.copyFrom(oldPosition2);
  67166. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  67167. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  67168. object.computeWorldMatrix(true);
  67169. break;
  67170. case BABYLON.PhysicsImpostor.ParticleImpostor:
  67171. returnValue = new this.BJSCANNON.Particle();
  67172. break;
  67173. }
  67174. return returnValue;
  67175. };
  67176. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  67177. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  67178. var transform = object.computeWorldMatrix(true);
  67179. // convert rawVerts to object space
  67180. var temp = new Array();
  67181. var index;
  67182. for (index = 0; index < pos.length; index += 3) {
  67183. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  67184. }
  67185. pos = temp;
  67186. var matrix = new Array();
  67187. //For now pointDepth will not be used and will be automatically calculated.
  67188. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  67189. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  67190. var boundingInfo = object.getBoundingInfo();
  67191. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  67192. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  67193. var elementSize = dim * 2 / arraySize;
  67194. for (var i = 0; i < pos.length; i = i + 3) {
  67195. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  67196. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  67197. var y = -pos[i + 2] + minY;
  67198. if (!matrix[x]) {
  67199. matrix[x] = [];
  67200. }
  67201. if (!matrix[x][z]) {
  67202. matrix[x][z] = y;
  67203. }
  67204. matrix[x][z] = Math.max(y, matrix[x][z]);
  67205. }
  67206. for (var x = 0; x <= arraySize; ++x) {
  67207. if (!matrix[x]) {
  67208. var loc = 1;
  67209. while (!matrix[(x + loc) % arraySize]) {
  67210. loc++;
  67211. }
  67212. matrix[x] = matrix[(x + loc) % arraySize].slice();
  67213. //console.log("missing x", x);
  67214. }
  67215. for (var z = 0; z <= arraySize; ++z) {
  67216. if (!matrix[x][z]) {
  67217. var loc = 1;
  67218. var newValue;
  67219. while (newValue === undefined) {
  67220. newValue = matrix[x][(z + loc++) % arraySize];
  67221. }
  67222. matrix[x][z] = newValue;
  67223. }
  67224. }
  67225. }
  67226. var shape = new this.BJSCANNON.Heightfield(matrix, {
  67227. elementSize: elementSize
  67228. });
  67229. //For future reference, needed for body transformation
  67230. shape.minY = minY;
  67231. return shape;
  67232. };
  67233. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  67234. var object = impostor.object;
  67235. //make sure it is updated...
  67236. object.computeWorldMatrix && object.computeWorldMatrix(true);
  67237. // The delta between the mesh position and the mesh bounding box center
  67238. var bInfo = object.getBoundingInfo();
  67239. if (!bInfo)
  67240. return;
  67241. var center = impostor.getObjectCenter();
  67242. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  67243. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  67244. this._tmpPosition.copyFrom(center);
  67245. var quaternion = object.rotationQuaternion;
  67246. if (!quaternion) {
  67247. return;
  67248. }
  67249. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  67250. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  67251. //-90 DEG in X, precalculated
  67252. quaternion = quaternion.multiply(this._minus90X);
  67253. //Invert! (Precalculated, 90 deg in X)
  67254. //No need to clone. this will never change.
  67255. impostor.setDeltaRotation(this._plus90X);
  67256. }
  67257. //If it is a heightfield, if should be centered.
  67258. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  67259. var mesh = object;
  67260. var boundingInfo = mesh.getBoundingInfo();
  67261. //calculate the correct body position:
  67262. var rotationQuaternion = mesh.rotationQuaternion;
  67263. mesh.rotationQuaternion = this._tmpUnityRotation;
  67264. mesh.computeWorldMatrix(true);
  67265. //get original center with no rotation
  67266. var c = center.clone();
  67267. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  67268. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  67269. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  67270. mesh.setPivotMatrix(p);
  67271. mesh.computeWorldMatrix(true);
  67272. //calculate the translation
  67273. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  67274. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  67275. //add it inverted to the delta
  67276. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  67277. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  67278. //rotation is back
  67279. mesh.rotationQuaternion = rotationQuaternion;
  67280. mesh.setPivotMatrix(oldPivot);
  67281. mesh.computeWorldMatrix(true);
  67282. }
  67283. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  67284. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  67285. //this._tmpPosition.copyFrom(object.position);
  67286. }
  67287. impostor.setDeltaPosition(this._tmpDeltaPosition);
  67288. //Now update the impostor object
  67289. impostor.physicsBody.position.copy(this._tmpPosition);
  67290. impostor.physicsBody.quaternion.copy(quaternion);
  67291. };
  67292. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  67293. impostor.object.position.copyFrom(impostor.physicsBody.position);
  67294. if (impostor.object.rotationQuaternion) {
  67295. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  67296. }
  67297. };
  67298. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  67299. impostor.physicsBody.position.copy(newPosition);
  67300. impostor.physicsBody.quaternion.copy(newRotation);
  67301. };
  67302. CannonJSPlugin.prototype.isSupported = function () {
  67303. return this.BJSCANNON !== undefined;
  67304. };
  67305. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  67306. impostor.physicsBody.velocity.copy(velocity);
  67307. };
  67308. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  67309. impostor.physicsBody.angularVelocity.copy(velocity);
  67310. };
  67311. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  67312. var v = impostor.physicsBody.velocity;
  67313. if (!v) {
  67314. return null;
  67315. }
  67316. return new BABYLON.Vector3(v.x, v.y, v.z);
  67317. };
  67318. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  67319. var v = impostor.physicsBody.angularVelocity;
  67320. if (!v) {
  67321. return null;
  67322. }
  67323. return new BABYLON.Vector3(v.x, v.y, v.z);
  67324. };
  67325. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  67326. impostor.physicsBody.mass = mass;
  67327. impostor.physicsBody.updateMassProperties();
  67328. };
  67329. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  67330. return impostor.physicsBody.mass;
  67331. };
  67332. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  67333. return impostor.physicsBody.material.friction;
  67334. };
  67335. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  67336. impostor.physicsBody.material.friction = friction;
  67337. };
  67338. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  67339. return impostor.physicsBody.material.restitution;
  67340. };
  67341. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  67342. impostor.physicsBody.material.restitution = restitution;
  67343. };
  67344. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  67345. impostor.physicsBody.sleep();
  67346. };
  67347. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  67348. impostor.physicsBody.wakeUp();
  67349. };
  67350. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  67351. joint.physicsJoint.distance = maxDistance;
  67352. };
  67353. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  67354. // if (!motorIndex) {
  67355. // joint.physicsJoint.enableMotor();
  67356. // }
  67357. // }
  67358. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  67359. // if (!motorIndex) {
  67360. // joint.physicsJoint.disableMotor();
  67361. // }
  67362. // }
  67363. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  67364. if (!motorIndex) {
  67365. joint.physicsJoint.enableMotor();
  67366. joint.physicsJoint.setMotorSpeed(speed);
  67367. if (maxForce) {
  67368. this.setLimit(joint, maxForce);
  67369. }
  67370. }
  67371. };
  67372. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  67373. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  67374. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  67375. };
  67376. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  67377. var body = impostor.physicsBody;
  67378. mesh.position.x = body.position.x;
  67379. mesh.position.y = body.position.y;
  67380. mesh.position.z = body.position.z;
  67381. if (mesh.rotationQuaternion) {
  67382. mesh.rotationQuaternion.x = body.quaternion.x;
  67383. mesh.rotationQuaternion.y = body.quaternion.y;
  67384. mesh.rotationQuaternion.z = body.quaternion.z;
  67385. mesh.rotationQuaternion.w = body.quaternion.w;
  67386. }
  67387. };
  67388. CannonJSPlugin.prototype.getRadius = function (impostor) {
  67389. var shape = impostor.physicsBody.shapes[0];
  67390. return shape.boundingSphereRadius;
  67391. };
  67392. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  67393. var shape = impostor.physicsBody.shapes[0];
  67394. result.x = shape.halfExtents.x * 2;
  67395. result.y = shape.halfExtents.y * 2;
  67396. result.z = shape.halfExtents.z * 2;
  67397. };
  67398. CannonJSPlugin.prototype.dispose = function () {
  67399. };
  67400. return CannonJSPlugin;
  67401. }());
  67402. BABYLON.CannonJSPlugin = CannonJSPlugin;
  67403. })(BABYLON || (BABYLON = {}));
  67404. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  67405. var BABYLON;
  67406. (function (BABYLON) {
  67407. var OimoJSPlugin = /** @class */ (function () {
  67408. function OimoJSPlugin(iterations) {
  67409. this.name = "OimoJSPlugin";
  67410. this._tmpImpostorsArray = [];
  67411. this._tmpPositionVector = BABYLON.Vector3.Zero();
  67412. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  67413. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  67414. this.world.worldscale(1);
  67415. this.world.clear();
  67416. //making sure no stats are calculated
  67417. this.world.isNoStat = true;
  67418. }
  67419. OimoJSPlugin.prototype.setGravity = function (gravity) {
  67420. this.world.gravity.copy(gravity);
  67421. };
  67422. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  67423. this.world.timeStep = timeStep;
  67424. };
  67425. OimoJSPlugin.prototype.getTimeStep = function () {
  67426. return this.world.timeStep;
  67427. };
  67428. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  67429. var _this = this;
  67430. impostors.forEach(function (impostor) {
  67431. impostor.beforeStep();
  67432. });
  67433. this.world.step();
  67434. impostors.forEach(function (impostor) {
  67435. impostor.afterStep();
  67436. //update the ordered impostors array
  67437. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  67438. });
  67439. //check for collisions
  67440. var contact = this.world.contacts;
  67441. while (contact !== null) {
  67442. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  67443. contact = contact.next;
  67444. continue;
  67445. }
  67446. //is this body colliding with any other? get the impostor
  67447. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  67448. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  67449. if (!mainImpostor || !collidingImpostor) {
  67450. contact = contact.next;
  67451. continue;
  67452. }
  67453. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  67454. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  67455. contact = contact.next;
  67456. }
  67457. };
  67458. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  67459. var mass = impostor.physicsBody.massInfo.mass;
  67460. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  67461. };
  67462. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  67463. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  67464. this.applyImpulse(impostor, force, contactPoint);
  67465. };
  67466. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  67467. var _this = this;
  67468. //parent-child relationship. Does this impostor has a parent impostor?
  67469. if (impostor.parent) {
  67470. if (impostor.physicsBody) {
  67471. this.removePhysicsBody(impostor);
  67472. //TODO is that needed?
  67473. impostor.forceUpdate();
  67474. }
  67475. return;
  67476. }
  67477. if (impostor.isBodyInitRequired()) {
  67478. var bodyConfig = {
  67479. name: impostor.uniqueId,
  67480. //Oimo must have mass, also for static objects.
  67481. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  67482. size: [],
  67483. type: [],
  67484. pos: [],
  67485. rot: [],
  67486. move: impostor.getParam("mass") !== 0,
  67487. //Supporting older versions of Oimo
  67488. world: this.world
  67489. };
  67490. var impostors = [impostor];
  67491. var addToArray = function (parent) {
  67492. if (!parent.getChildMeshes)
  67493. return;
  67494. parent.getChildMeshes().forEach(function (m) {
  67495. if (m.physicsImpostor) {
  67496. impostors.push(m.physicsImpostor);
  67497. //m.physicsImpostor._init();
  67498. }
  67499. });
  67500. };
  67501. addToArray(impostor.object);
  67502. var checkWithEpsilon_1 = function (value) {
  67503. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  67504. };
  67505. impostors.forEach(function (i) {
  67506. if (!impostor.object.rotationQuaternion) {
  67507. return;
  67508. }
  67509. //get the correct bounding box
  67510. var oldQuaternion = i.object.rotationQuaternion;
  67511. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  67512. x: impostor.object.rotationQuaternion.x,
  67513. y: impostor.object.rotationQuaternion.y,
  67514. z: impostor.object.rotationQuaternion.z,
  67515. s: impostor.object.rotationQuaternion.w
  67516. });
  67517. var extendSize = i.getObjectExtendSize();
  67518. if (i === impostor) {
  67519. var center = impostor.getObjectCenter();
  67520. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  67521. //Can also use Array.prototype.push.apply
  67522. bodyConfig.pos.push(center.x);
  67523. bodyConfig.pos.push(center.y);
  67524. bodyConfig.pos.push(center.z);
  67525. //tmp solution
  67526. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67527. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67528. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67529. }
  67530. else {
  67531. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  67532. bodyConfig.pos.push(localPosition.x);
  67533. bodyConfig.pos.push(localPosition.y);
  67534. bodyConfig.pos.push(localPosition.z);
  67535. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  67536. bodyConfig.rot.push(0);
  67537. bodyConfig.rot.push(0);
  67538. bodyConfig.rot.push(0);
  67539. }
  67540. // register mesh
  67541. switch (i.type) {
  67542. case BABYLON.PhysicsImpostor.ParticleImpostor:
  67543. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  67544. case BABYLON.PhysicsImpostor.SphereImpostor:
  67545. var radiusX = extendSize.x;
  67546. var radiusY = extendSize.y;
  67547. var radiusZ = extendSize.z;
  67548. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  67549. bodyConfig.type.push('sphere');
  67550. //due to the way oimo works with compounds, add 3 times
  67551. bodyConfig.size.push(size);
  67552. bodyConfig.size.push(size);
  67553. bodyConfig.size.push(size);
  67554. break;
  67555. case BABYLON.PhysicsImpostor.CylinderImpostor:
  67556. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  67557. var sizeY = checkWithEpsilon_1(extendSize.y);
  67558. bodyConfig.type.push('cylinder');
  67559. bodyConfig.size.push(sizeX);
  67560. bodyConfig.size.push(sizeY);
  67561. //due to the way oimo works with compounds, add one more value.
  67562. bodyConfig.size.push(sizeY);
  67563. break;
  67564. case BABYLON.PhysicsImpostor.PlaneImpostor:
  67565. case BABYLON.PhysicsImpostor.BoxImpostor:
  67566. default:
  67567. var sizeX = checkWithEpsilon_1(extendSize.x);
  67568. var sizeY = checkWithEpsilon_1(extendSize.y);
  67569. var sizeZ = checkWithEpsilon_1(extendSize.z);
  67570. bodyConfig.type.push('box');
  67571. bodyConfig.size.push(sizeX);
  67572. bodyConfig.size.push(sizeY);
  67573. bodyConfig.size.push(sizeZ);
  67574. break;
  67575. }
  67576. //actually not needed, but hey...
  67577. i.object.rotationQuaternion = oldQuaternion;
  67578. });
  67579. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  67580. }
  67581. else {
  67582. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  67583. }
  67584. impostor.setDeltaPosition(this._tmpPositionVector);
  67585. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  67586. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  67587. };
  67588. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  67589. //impostor.physicsBody.dispose();
  67590. //Same as : (older oimo versions)
  67591. this.world.removeRigidBody(impostor.physicsBody);
  67592. };
  67593. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  67594. var mainBody = impostorJoint.mainImpostor.physicsBody;
  67595. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  67596. if (!mainBody || !connectedBody) {
  67597. return;
  67598. }
  67599. var jointData = impostorJoint.joint.jointData;
  67600. var options = jointData.nativeParams || {};
  67601. var type;
  67602. var nativeJointData = {
  67603. body1: mainBody,
  67604. body2: connectedBody,
  67605. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  67606. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  67607. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  67608. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  67609. min: options.min,
  67610. max: options.max,
  67611. collision: options.collision || jointData.collision,
  67612. spring: options.spring,
  67613. //supporting older version of Oimo
  67614. world: this.world
  67615. };
  67616. switch (impostorJoint.joint.type) {
  67617. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  67618. type = "jointBall";
  67619. break;
  67620. case BABYLON.PhysicsJoint.SpringJoint:
  67621. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  67622. var springData = jointData;
  67623. nativeJointData.min = springData.length || nativeJointData.min;
  67624. //Max should also be set, just make sure it is at least min
  67625. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  67626. case BABYLON.PhysicsJoint.DistanceJoint:
  67627. type = "jointDistance";
  67628. nativeJointData.max = jointData.maxDistance;
  67629. break;
  67630. case BABYLON.PhysicsJoint.PrismaticJoint:
  67631. type = "jointPrisme";
  67632. break;
  67633. case BABYLON.PhysicsJoint.SliderJoint:
  67634. type = "jointSlide";
  67635. break;
  67636. case BABYLON.PhysicsJoint.WheelJoint:
  67637. type = "jointWheel";
  67638. break;
  67639. case BABYLON.PhysicsJoint.HingeJoint:
  67640. default:
  67641. type = "jointHinge";
  67642. break;
  67643. }
  67644. nativeJointData.type = type;
  67645. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  67646. };
  67647. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  67648. //Bug in Oimo prevents us from disposing a joint in the playground
  67649. //joint.joint.physicsJoint.dispose();
  67650. //So we will bruteforce it!
  67651. try {
  67652. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  67653. }
  67654. catch (e) {
  67655. BABYLON.Tools.Warn(e);
  67656. }
  67657. };
  67658. OimoJSPlugin.prototype.isSupported = function () {
  67659. return this.BJSOIMO !== undefined;
  67660. };
  67661. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  67662. if (!impostor.physicsBody.sleeping) {
  67663. //TODO check that
  67664. if (impostor.physicsBody.shapes.next) {
  67665. var parentShape = this._getLastShape(impostor.physicsBody);
  67666. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  67667. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  67668. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  67669. }
  67670. else {
  67671. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  67672. }
  67673. if (impostor.object.rotationQuaternion) {
  67674. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  67675. impostor.object.rotationQuaternion.normalize();
  67676. }
  67677. }
  67678. };
  67679. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  67680. var body = impostor.physicsBody;
  67681. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  67682. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  67683. body.syncShapes();
  67684. body.awake();
  67685. };
  67686. OimoJSPlugin.prototype._getLastShape = function (body) {
  67687. var lastShape = body.shapes;
  67688. while (lastShape.next) {
  67689. lastShape = lastShape.next;
  67690. }
  67691. return lastShape;
  67692. };
  67693. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  67694. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  67695. };
  67696. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  67697. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  67698. };
  67699. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  67700. var v = impostor.physicsBody.linearVelocity;
  67701. if (!v) {
  67702. return null;
  67703. }
  67704. return new BABYLON.Vector3(v.x, v.y, v.z);
  67705. };
  67706. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  67707. var v = impostor.physicsBody.angularVelocity;
  67708. if (!v) {
  67709. return null;
  67710. }
  67711. return new BABYLON.Vector3(v.x, v.y, v.z);
  67712. };
  67713. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  67714. var staticBody = mass === 0;
  67715. //this will actually set the body's density and not its mass.
  67716. //But this is how oimo treats the mass variable.
  67717. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  67718. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  67719. };
  67720. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  67721. return impostor.physicsBody.shapes.density;
  67722. };
  67723. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  67724. return impostor.physicsBody.shapes.friction;
  67725. };
  67726. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  67727. impostor.physicsBody.shapes.friction = friction;
  67728. };
  67729. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  67730. return impostor.physicsBody.shapes.restitution;
  67731. };
  67732. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  67733. impostor.physicsBody.shapes.restitution = restitution;
  67734. };
  67735. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  67736. impostor.physicsBody.sleep();
  67737. };
  67738. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  67739. impostor.physicsBody.awake();
  67740. };
  67741. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  67742. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  67743. if (minDistance !== void 0) {
  67744. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  67745. }
  67746. };
  67747. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  67748. //TODO separate rotational and transational motors.
  67749. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  67750. if (motor) {
  67751. motor.setMotor(speed, maxForce);
  67752. }
  67753. };
  67754. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  67755. //TODO separate rotational and transational motors.
  67756. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  67757. if (motor) {
  67758. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  67759. }
  67760. };
  67761. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  67762. var body = impostor.physicsBody;
  67763. mesh.position.x = body.position.x;
  67764. mesh.position.y = body.position.y;
  67765. mesh.position.z = body.position.z;
  67766. if (mesh.rotationQuaternion) {
  67767. mesh.rotationQuaternion.x = body.orientation.x;
  67768. mesh.rotationQuaternion.y = body.orientation.y;
  67769. mesh.rotationQuaternion.z = body.orientation.z;
  67770. mesh.rotationQuaternion.w = body.orientation.s;
  67771. }
  67772. };
  67773. OimoJSPlugin.prototype.getRadius = function (impostor) {
  67774. return impostor.physicsBody.shapes.radius;
  67775. };
  67776. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  67777. var shape = impostor.physicsBody.shapes;
  67778. result.x = shape.halfWidth * 2;
  67779. result.y = shape.halfHeight * 2;
  67780. result.z = shape.halfDepth * 2;
  67781. };
  67782. OimoJSPlugin.prototype.dispose = function () {
  67783. this.world.clear();
  67784. };
  67785. return OimoJSPlugin;
  67786. }());
  67787. BABYLON.OimoJSPlugin = OimoJSPlugin;
  67788. })(BABYLON || (BABYLON = {}));
  67789. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  67790. var BABYLON;
  67791. (function (BABYLON) {
  67792. var Internals;
  67793. (function (Internals) {
  67794. /*
  67795. * Based on jsTGALoader - Javascript loader for TGA file
  67796. * By Vincent Thibault
  67797. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  67798. */
  67799. var TGATools = /** @class */ (function () {
  67800. function TGATools() {
  67801. }
  67802. TGATools.GetTGAHeader = function (data) {
  67803. var offset = 0;
  67804. var header = {
  67805. id_length: data[offset++],
  67806. colormap_type: data[offset++],
  67807. image_type: data[offset++],
  67808. colormap_index: data[offset++] | data[offset++] << 8,
  67809. colormap_length: data[offset++] | data[offset++] << 8,
  67810. colormap_size: data[offset++],
  67811. origin: [
  67812. data[offset++] | data[offset++] << 8,
  67813. data[offset++] | data[offset++] << 8
  67814. ],
  67815. width: data[offset++] | data[offset++] << 8,
  67816. height: data[offset++] | data[offset++] << 8,
  67817. pixel_size: data[offset++],
  67818. flags: data[offset++]
  67819. };
  67820. return header;
  67821. };
  67822. TGATools.UploadContent = function (gl, data) {
  67823. // Not enough data to contain header ?
  67824. if (data.length < 19) {
  67825. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  67826. return;
  67827. }
  67828. // Read Header
  67829. var offset = 18;
  67830. var header = TGATools.GetTGAHeader(data);
  67831. // Assume it's a valid Targa file.
  67832. if (header.id_length + offset > data.length) {
  67833. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  67834. return;
  67835. }
  67836. // Skip not needed data
  67837. offset += header.id_length;
  67838. var use_rle = false;
  67839. var use_pal = false;
  67840. var use_grey = false;
  67841. // Get some informations.
  67842. switch (header.image_type) {
  67843. case TGATools._TYPE_RLE_INDEXED:
  67844. use_rle = true;
  67845. case TGATools._TYPE_INDEXED:
  67846. use_pal = true;
  67847. break;
  67848. case TGATools._TYPE_RLE_RGB:
  67849. use_rle = true;
  67850. case TGATools._TYPE_RGB:
  67851. // use_rgb = true;
  67852. break;
  67853. case TGATools._TYPE_RLE_GREY:
  67854. use_rle = true;
  67855. case TGATools._TYPE_GREY:
  67856. use_grey = true;
  67857. break;
  67858. }
  67859. var pixel_data;
  67860. // var numAlphaBits = header.flags & 0xf;
  67861. var pixel_size = header.pixel_size >> 3;
  67862. var pixel_total = header.width * header.height * pixel_size;
  67863. // Read palettes
  67864. var palettes;
  67865. if (use_pal) {
  67866. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  67867. }
  67868. // Read LRE
  67869. if (use_rle) {
  67870. pixel_data = new Uint8Array(pixel_total);
  67871. var c, count, i;
  67872. var localOffset = 0;
  67873. var pixels = new Uint8Array(pixel_size);
  67874. while (offset < pixel_total && localOffset < pixel_total) {
  67875. c = data[offset++];
  67876. count = (c & 0x7f) + 1;
  67877. // RLE pixels
  67878. if (c & 0x80) {
  67879. // Bind pixel tmp array
  67880. for (i = 0; i < pixel_size; ++i) {
  67881. pixels[i] = data[offset++];
  67882. }
  67883. // Copy pixel array
  67884. for (i = 0; i < count; ++i) {
  67885. pixel_data.set(pixels, localOffset + i * pixel_size);
  67886. }
  67887. localOffset += pixel_size * count;
  67888. }
  67889. else {
  67890. count *= pixel_size;
  67891. for (i = 0; i < count; ++i) {
  67892. pixel_data[localOffset + i] = data[offset++];
  67893. }
  67894. localOffset += count;
  67895. }
  67896. }
  67897. }
  67898. else {
  67899. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  67900. }
  67901. // Load to texture
  67902. var x_start, y_start, x_step, y_step, y_end, x_end;
  67903. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  67904. default:
  67905. case TGATools._ORIGIN_UL:
  67906. x_start = 0;
  67907. x_step = 1;
  67908. x_end = header.width;
  67909. y_start = 0;
  67910. y_step = 1;
  67911. y_end = header.height;
  67912. break;
  67913. case TGATools._ORIGIN_BL:
  67914. x_start = 0;
  67915. x_step = 1;
  67916. x_end = header.width;
  67917. y_start = header.height - 1;
  67918. y_step = -1;
  67919. y_end = -1;
  67920. break;
  67921. case TGATools._ORIGIN_UR:
  67922. x_start = header.width - 1;
  67923. x_step = -1;
  67924. x_end = -1;
  67925. y_start = 0;
  67926. y_step = 1;
  67927. y_end = header.height;
  67928. break;
  67929. case TGATools._ORIGIN_BR:
  67930. x_start = header.width - 1;
  67931. x_step = -1;
  67932. x_end = -1;
  67933. y_start = header.height - 1;
  67934. y_step = -1;
  67935. y_end = -1;
  67936. break;
  67937. }
  67938. // Load the specify method
  67939. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  67940. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  67941. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  67942. };
  67943. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67944. var image = pixel_data, colormap = palettes;
  67945. var width = header.width, height = header.height;
  67946. var color, i = 0, x, y;
  67947. var imageData = new Uint8Array(width * height * 4);
  67948. for (y = y_start; y !== y_end; y += y_step) {
  67949. for (x = x_start; x !== x_end; x += x_step, i++) {
  67950. color = image[i];
  67951. imageData[(x + width * y) * 4 + 3] = 255;
  67952. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  67953. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  67954. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  67955. }
  67956. }
  67957. return imageData;
  67958. };
  67959. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67960. var image = pixel_data;
  67961. var width = header.width, height = header.height;
  67962. var color, i = 0, x, y;
  67963. var imageData = new Uint8Array(width * height * 4);
  67964. for (y = y_start; y !== y_end; y += y_step) {
  67965. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  67966. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  67967. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  67968. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  67969. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  67970. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  67971. }
  67972. }
  67973. return imageData;
  67974. };
  67975. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67976. var image = pixel_data;
  67977. var width = header.width, height = header.height;
  67978. var i = 0, x, y;
  67979. var imageData = new Uint8Array(width * height * 4);
  67980. for (y = y_start; y !== y_end; y += y_step) {
  67981. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  67982. imageData[(x + width * y) * 4 + 3] = 255;
  67983. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67984. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  67985. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  67986. }
  67987. }
  67988. return imageData;
  67989. };
  67990. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67991. var image = pixel_data;
  67992. var width = header.width, height = header.height;
  67993. var i = 0, x, y;
  67994. var imageData = new Uint8Array(width * height * 4);
  67995. for (y = y_start; y !== y_end; y += y_step) {
  67996. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  67997. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67998. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  67999. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  68000. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  68001. }
  68002. }
  68003. return imageData;
  68004. };
  68005. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68006. var image = pixel_data;
  68007. var width = header.width, height = header.height;
  68008. var color, i = 0, x, y;
  68009. var imageData = new Uint8Array(width * height * 4);
  68010. for (y = y_start; y !== y_end; y += y_step) {
  68011. for (x = x_start; x !== x_end; x += x_step, i++) {
  68012. color = image[i];
  68013. imageData[(x + width * y) * 4 + 0] = color;
  68014. imageData[(x + width * y) * 4 + 1] = color;
  68015. imageData[(x + width * y) * 4 + 2] = color;
  68016. imageData[(x + width * y) * 4 + 3] = 255;
  68017. }
  68018. }
  68019. return imageData;
  68020. };
  68021. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68022. var image = pixel_data;
  68023. var width = header.width, height = header.height;
  68024. var i = 0, x, y;
  68025. var imageData = new Uint8Array(width * height * 4);
  68026. for (y = y_start; y !== y_end; y += y_step) {
  68027. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  68028. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  68029. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  68030. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  68031. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  68032. }
  68033. }
  68034. return imageData;
  68035. };
  68036. //private static _TYPE_NO_DATA = 0;
  68037. TGATools._TYPE_INDEXED = 1;
  68038. TGATools._TYPE_RGB = 2;
  68039. TGATools._TYPE_GREY = 3;
  68040. TGATools._TYPE_RLE_INDEXED = 9;
  68041. TGATools._TYPE_RLE_RGB = 10;
  68042. TGATools._TYPE_RLE_GREY = 11;
  68043. TGATools._ORIGIN_MASK = 0x30;
  68044. TGATools._ORIGIN_SHIFT = 0x04;
  68045. TGATools._ORIGIN_BL = 0x00;
  68046. TGATools._ORIGIN_BR = 0x01;
  68047. TGATools._ORIGIN_UL = 0x02;
  68048. TGATools._ORIGIN_UR = 0x03;
  68049. return TGATools;
  68050. }());
  68051. Internals.TGATools = TGATools;
  68052. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68053. })(BABYLON || (BABYLON = {}));
  68054. //# sourceMappingURL=babylon.tga.js.map
  68055. var BABYLON;
  68056. (function (BABYLON) {
  68057. var Internals;
  68058. (function (Internals) {
  68059. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  68060. // All values and structures referenced from:
  68061. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  68062. var DDS_MAGIC = 0x20534444;
  68063. var
  68064. //DDSD_CAPS = 0x1,
  68065. //DDSD_HEIGHT = 0x2,
  68066. //DDSD_WIDTH = 0x4,
  68067. //DDSD_PITCH = 0x8,
  68068. //DDSD_PIXELFORMAT = 0x1000,
  68069. DDSD_MIPMAPCOUNT = 0x20000;
  68070. //DDSD_LINEARSIZE = 0x80000,
  68071. //DDSD_DEPTH = 0x800000;
  68072. // var DDSCAPS_COMPLEX = 0x8,
  68073. // DDSCAPS_MIPMAP = 0x400000,
  68074. // DDSCAPS_TEXTURE = 0x1000;
  68075. var DDSCAPS2_CUBEMAP = 0x200;
  68076. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  68077. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  68078. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  68079. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  68080. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  68081. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  68082. // DDSCAPS2_VOLUME = 0x200000;
  68083. var
  68084. //DDPF_ALPHAPIXELS = 0x1,
  68085. //DDPF_ALPHA = 0x2,
  68086. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  68087. //DDPF_YUV = 0x200,
  68088. DDPF_LUMINANCE = 0x20000;
  68089. function FourCCToInt32(value) {
  68090. return value.charCodeAt(0) +
  68091. (value.charCodeAt(1) << 8) +
  68092. (value.charCodeAt(2) << 16) +
  68093. (value.charCodeAt(3) << 24);
  68094. }
  68095. function Int32ToFourCC(value) {
  68096. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  68097. }
  68098. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  68099. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  68100. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  68101. var FOURCC_DX10 = FourCCToInt32("DX10");
  68102. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  68103. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  68104. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  68105. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  68106. var headerLengthInt = 31; // The header length in 32 bit ints
  68107. // Offsets into the header array
  68108. var off_magic = 0;
  68109. var off_size = 1;
  68110. var off_flags = 2;
  68111. var off_height = 3;
  68112. var off_width = 4;
  68113. var off_mipmapCount = 7;
  68114. var off_pfFlags = 20;
  68115. var off_pfFourCC = 21;
  68116. var off_RGBbpp = 22;
  68117. // var off_RMask = 23;
  68118. // var off_GMask = 24;
  68119. // var off_BMask = 25;
  68120. // var off_AMask = 26;
  68121. // var off_caps1 = 27;
  68122. var off_caps2 = 28;
  68123. // var off_caps3 = 29;
  68124. // var off_caps4 = 30;
  68125. var off_dxgiFormat = 32;
  68126. ;
  68127. var DDSTools = /** @class */ (function () {
  68128. function DDSTools() {
  68129. }
  68130. DDSTools.GetDDSInfo = function (arrayBuffer) {
  68131. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  68132. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  68133. var mipmapCount = 1;
  68134. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  68135. mipmapCount = Math.max(1, header[off_mipmapCount]);
  68136. }
  68137. var fourCC = header[off_pfFourCC];
  68138. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  68139. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68140. switch (fourCC) {
  68141. case FOURCC_D3DFMT_R16G16B16A16F:
  68142. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68143. break;
  68144. case FOURCC_D3DFMT_R32G32B32A32F:
  68145. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68146. break;
  68147. case FOURCC_DX10:
  68148. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  68149. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68150. break;
  68151. }
  68152. }
  68153. return {
  68154. width: header[off_width],
  68155. height: header[off_height],
  68156. mipmapCount: mipmapCount,
  68157. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  68158. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  68159. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  68160. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  68161. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  68162. dxgiFormat: dxgiFormat,
  68163. textureType: textureType
  68164. };
  68165. };
  68166. DDSTools._ToHalfFloat = function (value) {
  68167. if (!DDSTools._FloatView) {
  68168. DDSTools._FloatView = new Float32Array(1);
  68169. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  68170. }
  68171. DDSTools._FloatView[0] = value;
  68172. var x = DDSTools._Int32View[0];
  68173. var bits = (x >> 16) & 0x8000; /* Get the sign */
  68174. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  68175. var e = (x >> 23) & 0xff; /* Using int is faster here */
  68176. /* If zero, or denormal, or exponent underflows too much for a denormal
  68177. * half, return signed zero. */
  68178. if (e < 103) {
  68179. return bits;
  68180. }
  68181. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  68182. if (e > 142) {
  68183. bits |= 0x7c00;
  68184. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  68185. * not Inf, so make sure we set one mantissa bit too. */
  68186. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  68187. return bits;
  68188. }
  68189. /* If exponent underflows but not too much, return a denormal */
  68190. if (e < 113) {
  68191. m |= 0x0800;
  68192. /* Extra rounding may overflow and set mantissa to 0 and exponent
  68193. * to 1, which is OK. */
  68194. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  68195. return bits;
  68196. }
  68197. bits |= ((e - 112) << 10) | (m >> 1);
  68198. bits += m & 1;
  68199. return bits;
  68200. };
  68201. DDSTools._FromHalfFloat = function (value) {
  68202. var s = (value & 0x8000) >> 15;
  68203. var e = (value & 0x7C00) >> 10;
  68204. var f = value & 0x03FF;
  68205. if (e === 0) {
  68206. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  68207. }
  68208. else if (e == 0x1F) {
  68209. return f ? NaN : ((s ? -1 : 1) * Infinity);
  68210. }
  68211. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  68212. };
  68213. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68214. var destArray = new Float32Array(dataLength);
  68215. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  68216. var index = 0;
  68217. for (var y = 0; y < height; y++) {
  68218. for (var x = 0; x < width; x++) {
  68219. var srcPos = (x + y * width) * 4;
  68220. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  68221. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  68222. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  68223. if (DDSTools.StoreLODInAlphaChannel) {
  68224. destArray[index + 3] = lod;
  68225. }
  68226. else {
  68227. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  68228. }
  68229. index += 4;
  68230. }
  68231. }
  68232. return destArray;
  68233. };
  68234. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68235. if (DDSTools.StoreLODInAlphaChannel) {
  68236. var destArray = new Uint16Array(dataLength);
  68237. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  68238. var index = 0;
  68239. for (var y = 0; y < height; y++) {
  68240. for (var x = 0; x < width; x++) {
  68241. var srcPos = (x + y * width) * 4;
  68242. destArray[index] = srcData[srcPos];
  68243. destArray[index + 1] = srcData[srcPos + 1];
  68244. destArray[index + 2] = srcData[srcPos + 2];
  68245. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  68246. index += 4;
  68247. }
  68248. }
  68249. return destArray;
  68250. }
  68251. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  68252. };
  68253. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68254. if (DDSTools.StoreLODInAlphaChannel) {
  68255. var destArray = new Float32Array(dataLength);
  68256. var srcData = new Float32Array(arrayBuffer, dataOffset);
  68257. var index = 0;
  68258. for (var y = 0; y < height; y++) {
  68259. for (var x = 0; x < width; x++) {
  68260. var srcPos = (x + y * width) * 4;
  68261. destArray[index] = srcData[srcPos];
  68262. destArray[index + 1] = srcData[srcPos + 1];
  68263. destArray[index + 2] = srcData[srcPos + 2];
  68264. destArray[index + 3] = lod;
  68265. index += 4;
  68266. }
  68267. }
  68268. return destArray;
  68269. }
  68270. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  68271. };
  68272. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68273. var destArray = new Uint8Array(dataLength);
  68274. var srcData = new Float32Array(arrayBuffer, dataOffset);
  68275. var index = 0;
  68276. for (var y = 0; y < height; y++) {
  68277. for (var x = 0; x < width; x++) {
  68278. var srcPos = (x + y * width) * 4;
  68279. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  68280. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  68281. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  68282. if (DDSTools.StoreLODInAlphaChannel) {
  68283. destArray[index + 3] = lod;
  68284. }
  68285. else {
  68286. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  68287. }
  68288. index += 4;
  68289. }
  68290. }
  68291. return destArray;
  68292. };
  68293. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68294. var destArray = new Uint8Array(dataLength);
  68295. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  68296. var index = 0;
  68297. for (var y = 0; y < height; y++) {
  68298. for (var x = 0; x < width; x++) {
  68299. var srcPos = (x + y * width) * 4;
  68300. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  68301. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  68302. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  68303. if (DDSTools.StoreLODInAlphaChannel) {
  68304. destArray[index + 3] = lod;
  68305. }
  68306. else {
  68307. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  68308. }
  68309. index += 4;
  68310. }
  68311. }
  68312. return destArray;
  68313. };
  68314. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  68315. var byteArray = new Uint8Array(dataLength);
  68316. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68317. var index = 0;
  68318. for (var y = 0; y < height; y++) {
  68319. for (var x = 0; x < width; x++) {
  68320. var srcPos = (x + y * width) * 4;
  68321. byteArray[index] = srcData[srcPos + 2];
  68322. byteArray[index + 1] = srcData[srcPos + 1];
  68323. byteArray[index + 2] = srcData[srcPos];
  68324. byteArray[index + 3] = srcData[srcPos + 3];
  68325. index += 4;
  68326. }
  68327. }
  68328. return byteArray;
  68329. };
  68330. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  68331. var byteArray = new Uint8Array(dataLength);
  68332. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68333. var index = 0;
  68334. for (var y = 0; y < height; y++) {
  68335. for (var x = 0; x < width; x++) {
  68336. var srcPos = (x + y * width) * 3;
  68337. byteArray[index] = srcData[srcPos + 2];
  68338. byteArray[index + 1] = srcData[srcPos + 1];
  68339. byteArray[index + 2] = srcData[srcPos];
  68340. index += 3;
  68341. }
  68342. }
  68343. return byteArray;
  68344. };
  68345. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  68346. var byteArray = new Uint8Array(dataLength);
  68347. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68348. var index = 0;
  68349. for (var y = 0; y < height; y++) {
  68350. for (var x = 0; x < width; x++) {
  68351. var srcPos = (x + y * width);
  68352. byteArray[index] = srcData[srcPos];
  68353. index++;
  68354. }
  68355. }
  68356. return byteArray;
  68357. };
  68358. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  68359. if (lodIndex === void 0) { lodIndex = -1; }
  68360. var ext = engine.getCaps().s3tc;
  68361. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  68362. var fourCC, width, height, dataLength = 0, dataOffset;
  68363. var byteArray, mipmapCount, mip;
  68364. var internalFormat = 0;
  68365. var format = 0;
  68366. var blockBytes = 1;
  68367. if (header[off_magic] !== DDS_MAGIC) {
  68368. BABYLON.Tools.Error("Invalid magic number in DDS header");
  68369. return;
  68370. }
  68371. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  68372. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  68373. return;
  68374. }
  68375. if (info.isCompressed && !ext) {
  68376. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  68377. return;
  68378. }
  68379. var bpp = header[off_RGBbpp];
  68380. dataOffset = header[off_size] + 4;
  68381. var computeFormats = false;
  68382. if (info.isFourCC) {
  68383. fourCC = header[off_pfFourCC];
  68384. switch (fourCC) {
  68385. case FOURCC_DXT1:
  68386. blockBytes = 8;
  68387. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  68388. break;
  68389. case FOURCC_DXT3:
  68390. blockBytes = 16;
  68391. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  68392. break;
  68393. case FOURCC_DXT5:
  68394. blockBytes = 16;
  68395. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  68396. break;
  68397. case FOURCC_D3DFMT_R16G16B16A16F:
  68398. computeFormats = true;
  68399. break;
  68400. case FOURCC_D3DFMT_R32G32B32A32F:
  68401. computeFormats = true;
  68402. break;
  68403. case FOURCC_DX10:
  68404. // There is an additionnal header so dataOffset need to be changed
  68405. dataOffset += 5 * 4; // 5 uints
  68406. var supported = false;
  68407. switch (info.dxgiFormat) {
  68408. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  68409. computeFormats = true;
  68410. supported = true;
  68411. break;
  68412. case DXGI_FORMAT_B8G8R8X8_UNORM:
  68413. info.isRGB = true;
  68414. info.isFourCC = false;
  68415. bpp = 32;
  68416. supported = true;
  68417. break;
  68418. }
  68419. if (supported) {
  68420. break;
  68421. }
  68422. default:
  68423. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  68424. return;
  68425. }
  68426. }
  68427. if (computeFormats) {
  68428. format = engine._getWebGLTextureType(info.textureType);
  68429. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68430. }
  68431. mipmapCount = 1;
  68432. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  68433. mipmapCount = Math.max(1, header[off_mipmapCount]);
  68434. }
  68435. for (var face = 0; face < faces; face++) {
  68436. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  68437. width = header[off_width];
  68438. height = header[off_height];
  68439. for (mip = 0; mip < mipmapCount; ++mip) {
  68440. if (lodIndex === -1 || lodIndex === mip) {
  68441. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  68442. var i = (lodIndex === -1) ? mip : 0;
  68443. if (!info.isCompressed && info.isFourCC) {
  68444. dataLength = width * height * 4;
  68445. var floatArray = null;
  68446. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  68447. if (bpp === 128) {
  68448. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68449. }
  68450. else if (bpp === 64) {
  68451. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68452. }
  68453. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68454. format = engine._getWebGLTextureType(info.textureType);
  68455. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68456. }
  68457. else {
  68458. if (bpp === 128) {
  68459. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68460. }
  68461. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  68462. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68463. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68464. format = engine._getWebGLTextureType(info.textureType);
  68465. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68466. }
  68467. else {
  68468. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68469. }
  68470. }
  68471. if (floatArray) {
  68472. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  68473. }
  68474. }
  68475. else if (info.isRGB) {
  68476. if (bpp === 24) {
  68477. dataLength = width * height * 3;
  68478. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68479. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  68480. }
  68481. else {
  68482. dataLength = width * height * 4;
  68483. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68484. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  68485. }
  68486. }
  68487. else if (info.isLuminance) {
  68488. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  68489. var unpaddedRowSize = width;
  68490. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  68491. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  68492. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68493. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  68494. }
  68495. else {
  68496. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  68497. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  68498. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  68499. }
  68500. }
  68501. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  68502. width *= 0.5;
  68503. height *= 0.5;
  68504. width = Math.max(1.0, width);
  68505. height = Math.max(1.0, height);
  68506. }
  68507. if (currentFace !== undefined) {
  68508. // Loading a single face
  68509. break;
  68510. }
  68511. }
  68512. };
  68513. DDSTools.StoreLODInAlphaChannel = false;
  68514. return DDSTools;
  68515. }());
  68516. Internals.DDSTools = DDSTools;
  68517. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68518. })(BABYLON || (BABYLON = {}));
  68519. //# sourceMappingURL=babylon.dds.js.map
  68520. var BABYLON;
  68521. (function (BABYLON) {
  68522. var Internals;
  68523. (function (Internals) {
  68524. /**
  68525. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  68526. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  68527. */
  68528. var KhronosTextureContainer = /** @class */ (function () {
  68529. /**
  68530. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  68531. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  68532. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  68533. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  68534. */
  68535. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  68536. this.arrayBuffer = arrayBuffer;
  68537. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  68538. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  68539. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  68540. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  68541. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  68542. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  68543. BABYLON.Tools.Error("texture missing KTX identifier");
  68544. return;
  68545. }
  68546. // load the reset of the header in native 32 bit int
  68547. var header = new Int32Array(this.arrayBuffer, 12, 13);
  68548. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  68549. var oppositeEndianess = header[0] === 0x01020304;
  68550. // read all the header elements in order they exist in the file, without modification (sans endainness)
  68551. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  68552. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  68553. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  68554. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  68555. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  68556. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  68557. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  68558. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  68559. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  68560. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  68561. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  68562. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  68563. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  68564. if (this.glType !== 0) {
  68565. BABYLON.Tools.Error("only compressed formats currently supported");
  68566. return;
  68567. }
  68568. else {
  68569. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  68570. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  68571. }
  68572. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  68573. BABYLON.Tools.Error("only 2D textures currently supported");
  68574. return;
  68575. }
  68576. if (this.numberOfArrayElements !== 0) {
  68577. BABYLON.Tools.Error("texture arrays not currently supported");
  68578. return;
  68579. }
  68580. if (this.numberOfFaces !== facesExpected) {
  68581. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  68582. return;
  68583. }
  68584. // we now have a completely validated file, so could use existence of loadType as success
  68585. // would need to make this more elaborate & adjust checks above to support more than one load type
  68586. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  68587. }
  68588. // not as fast hardware based, but will probably never need to use
  68589. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  68590. return ((val & 0xFF) << 24)
  68591. | ((val & 0xFF00) << 8)
  68592. | ((val >> 8) & 0xFF00)
  68593. | ((val >> 24) & 0xFF);
  68594. };
  68595. /**
  68596. * It is assumed that the texture has already been created & is currently bound
  68597. */
  68598. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  68599. switch (this.loadType) {
  68600. case KhronosTextureContainer.COMPRESSED_2D:
  68601. this._upload2DCompressedLevels(gl, loadMipmaps);
  68602. break;
  68603. case KhronosTextureContainer.TEX_2D:
  68604. case KhronosTextureContainer.COMPRESSED_3D:
  68605. case KhronosTextureContainer.TEX_3D:
  68606. }
  68607. };
  68608. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  68609. // initialize width & height for level 1
  68610. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  68611. var width = this.pixelWidth;
  68612. var height = this.pixelHeight;
  68613. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  68614. for (var level = 0; level < mipmapCount; level++) {
  68615. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  68616. for (var face = 0; face < this.numberOfFaces; face++) {
  68617. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  68618. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  68619. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  68620. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  68621. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  68622. }
  68623. width = Math.max(1.0, width * 0.5);
  68624. height = Math.max(1.0, height * 0.5);
  68625. }
  68626. };
  68627. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  68628. // load types
  68629. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  68630. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  68631. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  68632. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  68633. return KhronosTextureContainer;
  68634. }());
  68635. Internals.KhronosTextureContainer = KhronosTextureContainer;
  68636. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68637. })(BABYLON || (BABYLON = {}));
  68638. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  68639. var BABYLON;
  68640. (function (BABYLON) {
  68641. var Debug;
  68642. (function (Debug) {
  68643. /**
  68644. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  68645. */
  68646. var SkeletonViewer = /** @class */ (function () {
  68647. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  68648. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  68649. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  68650. this.skeleton = skeleton;
  68651. this.mesh = mesh;
  68652. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  68653. this.renderingGroupId = renderingGroupId;
  68654. this.color = BABYLON.Color3.White();
  68655. this._debugLines = new Array();
  68656. this._isEnabled = false;
  68657. this._scene = scene;
  68658. this.update();
  68659. this._renderFunction = this.update.bind(this);
  68660. }
  68661. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  68662. get: function () {
  68663. return this._isEnabled;
  68664. },
  68665. set: function (value) {
  68666. if (this._isEnabled === value) {
  68667. return;
  68668. }
  68669. this._isEnabled = value;
  68670. if (value) {
  68671. this._scene.registerBeforeRender(this._renderFunction);
  68672. }
  68673. else {
  68674. this._scene.unregisterBeforeRender(this._renderFunction);
  68675. }
  68676. },
  68677. enumerable: true,
  68678. configurable: true
  68679. });
  68680. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  68681. if (x === void 0) { x = 0; }
  68682. if (y === void 0) { y = 0; }
  68683. if (z === void 0) { z = 0; }
  68684. var tmat = BABYLON.Tmp.Matrix[0];
  68685. var parentBone = bone.getParent();
  68686. tmat.copyFrom(bone.getLocalMatrix());
  68687. if (x !== 0 || y !== 0 || z !== 0) {
  68688. var tmat2 = BABYLON.Tmp.Matrix[1];
  68689. BABYLON.Matrix.IdentityToRef(tmat2);
  68690. tmat2.m[12] = x;
  68691. tmat2.m[13] = y;
  68692. tmat2.m[14] = z;
  68693. tmat2.multiplyToRef(tmat, tmat);
  68694. }
  68695. if (parentBone) {
  68696. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  68697. }
  68698. tmat.multiplyToRef(meshMat, tmat);
  68699. position.x = tmat.m[12];
  68700. position.y = tmat.m[13];
  68701. position.z = tmat.m[14];
  68702. };
  68703. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  68704. var len = bones.length;
  68705. var meshPos = this.mesh.position;
  68706. for (var i = 0; i < len; i++) {
  68707. var bone = bones[i];
  68708. var points = this._debugLines[i];
  68709. if (!points) {
  68710. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68711. this._debugLines[i] = points;
  68712. }
  68713. this._getBonePosition(points[0], bone, meshMat);
  68714. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  68715. points[0].subtractInPlace(meshPos);
  68716. points[1].subtractInPlace(meshPos);
  68717. }
  68718. };
  68719. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  68720. var len = bones.length;
  68721. var boneNum = 0;
  68722. var meshPos = this.mesh.position;
  68723. for (var i = len - 1; i >= 0; i--) {
  68724. var childBone = bones[i];
  68725. var parentBone = childBone.getParent();
  68726. if (!parentBone) {
  68727. continue;
  68728. }
  68729. var points = this._debugLines[boneNum];
  68730. if (!points) {
  68731. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68732. this._debugLines[boneNum] = points;
  68733. }
  68734. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  68735. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  68736. points[0].subtractInPlace(meshPos);
  68737. points[1].subtractInPlace(meshPos);
  68738. boneNum++;
  68739. }
  68740. };
  68741. SkeletonViewer.prototype.update = function () {
  68742. if (this.autoUpdateBonesMatrices) {
  68743. this.skeleton.computeAbsoluteTransforms();
  68744. }
  68745. if (this.skeleton.bones[0].length === undefined) {
  68746. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  68747. }
  68748. else {
  68749. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  68750. }
  68751. if (!this._debugMesh) {
  68752. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  68753. this._debugMesh.renderingGroupId = this.renderingGroupId;
  68754. }
  68755. else {
  68756. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  68757. }
  68758. this._debugMesh.position.copyFrom(this.mesh.position);
  68759. this._debugMesh.color = this.color;
  68760. };
  68761. SkeletonViewer.prototype.dispose = function () {
  68762. if (this._debugMesh) {
  68763. this.isEnabled = false;
  68764. this._debugMesh.dispose();
  68765. this._debugMesh = null;
  68766. }
  68767. };
  68768. return SkeletonViewer;
  68769. }());
  68770. Debug.SkeletonViewer = SkeletonViewer;
  68771. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68772. })(BABYLON || (BABYLON = {}));
  68773. //# sourceMappingURL=babylon.skeletonViewer.js.map
  68774. var BABYLON;
  68775. (function (BABYLON) {
  68776. var Debug;
  68777. (function (Debug) {
  68778. var AxesViewer = /** @class */ (function () {
  68779. function AxesViewer(scene, scaleLines) {
  68780. if (scaleLines === void 0) { scaleLines = 1; }
  68781. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68782. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68783. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68784. this.scaleLines = 1;
  68785. this.scaleLines = scaleLines;
  68786. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  68787. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  68788. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  68789. this._xmesh.renderingGroupId = 2;
  68790. this._ymesh.renderingGroupId = 2;
  68791. this._zmesh.renderingGroupId = 2;
  68792. this._xmesh.material.checkReadyOnlyOnce = true;
  68793. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  68794. this._ymesh.material.checkReadyOnlyOnce = true;
  68795. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  68796. this._zmesh.material.checkReadyOnlyOnce = true;
  68797. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  68798. this.scene = scene;
  68799. }
  68800. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  68801. var scaleLines = this.scaleLines;
  68802. if (this._xmesh) {
  68803. this._xmesh.position.copyFrom(position);
  68804. }
  68805. if (this._ymesh) {
  68806. this._ymesh.position.copyFrom(position);
  68807. }
  68808. if (this._zmesh) {
  68809. this._zmesh.position.copyFrom(position);
  68810. }
  68811. var point2 = this._xline[1];
  68812. point2.x = xaxis.x * scaleLines;
  68813. point2.y = xaxis.y * scaleLines;
  68814. point2.z = xaxis.z * scaleLines;
  68815. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  68816. point2 = this._yline[1];
  68817. point2.x = yaxis.x * scaleLines;
  68818. point2.y = yaxis.y * scaleLines;
  68819. point2.z = yaxis.z * scaleLines;
  68820. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  68821. point2 = this._zline[1];
  68822. point2.x = zaxis.x * scaleLines;
  68823. point2.y = zaxis.y * scaleLines;
  68824. point2.z = zaxis.z * scaleLines;
  68825. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  68826. };
  68827. AxesViewer.prototype.dispose = function () {
  68828. if (this._xmesh) {
  68829. this._xmesh.dispose();
  68830. }
  68831. if (this._ymesh) {
  68832. this._ymesh.dispose();
  68833. }
  68834. if (this._zmesh) {
  68835. this._zmesh.dispose();
  68836. }
  68837. this._xmesh = null;
  68838. this._ymesh = null;
  68839. this._zmesh = null;
  68840. this.scene = null;
  68841. };
  68842. return AxesViewer;
  68843. }());
  68844. Debug.AxesViewer = AxesViewer;
  68845. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68846. })(BABYLON || (BABYLON = {}));
  68847. //# sourceMappingURL=babylon.axesViewer.js.map
  68848. var BABYLON;
  68849. (function (BABYLON) {
  68850. var Debug;
  68851. (function (Debug) {
  68852. var BoneAxesViewer = /** @class */ (function (_super) {
  68853. __extends(BoneAxesViewer, _super);
  68854. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  68855. if (scaleLines === void 0) { scaleLines = 1; }
  68856. var _this = _super.call(this, scene, scaleLines) || this;
  68857. _this.pos = BABYLON.Vector3.Zero();
  68858. _this.xaxis = BABYLON.Vector3.Zero();
  68859. _this.yaxis = BABYLON.Vector3.Zero();
  68860. _this.zaxis = BABYLON.Vector3.Zero();
  68861. _this.mesh = mesh;
  68862. _this.bone = bone;
  68863. return _this;
  68864. }
  68865. BoneAxesViewer.prototype.update = function () {
  68866. if (!this.mesh || !this.bone) {
  68867. return;
  68868. }
  68869. var bone = this.bone;
  68870. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  68871. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  68872. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  68873. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  68874. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  68875. };
  68876. BoneAxesViewer.prototype.dispose = function () {
  68877. if (this.mesh) {
  68878. this.mesh = null;
  68879. this.bone = null;
  68880. _super.prototype.dispose.call(this);
  68881. }
  68882. };
  68883. return BoneAxesViewer;
  68884. }(Debug.AxesViewer));
  68885. Debug.BoneAxesViewer = BoneAxesViewer;
  68886. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68887. })(BABYLON || (BABYLON = {}));
  68888. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  68889. var BABYLON;
  68890. (function (BABYLON) {
  68891. var RayHelper = /** @class */ (function () {
  68892. function RayHelper(ray) {
  68893. this.ray = ray;
  68894. }
  68895. RayHelper.CreateAndShow = function (ray, scene, color) {
  68896. var helper = new RayHelper(ray);
  68897. helper.show(scene, color);
  68898. return helper;
  68899. };
  68900. RayHelper.prototype.show = function (scene, color) {
  68901. if (!this._renderFunction && this.ray) {
  68902. var ray = this.ray;
  68903. this._renderFunction = this._render.bind(this);
  68904. this._scene = scene;
  68905. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  68906. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  68907. if (this._renderFunction) {
  68908. this._scene.registerBeforeRender(this._renderFunction);
  68909. }
  68910. }
  68911. if (color && this._renderLine) {
  68912. this._renderLine.color.copyFrom(color);
  68913. }
  68914. };
  68915. RayHelper.prototype.hide = function () {
  68916. if (this._renderFunction && this._scene) {
  68917. this._scene.unregisterBeforeRender(this._renderFunction);
  68918. this._scene = null;
  68919. this._renderFunction = null;
  68920. if (this._renderLine) {
  68921. this._renderLine.dispose();
  68922. this._renderLine = null;
  68923. }
  68924. this._renderPoints = [];
  68925. }
  68926. };
  68927. RayHelper.prototype._render = function () {
  68928. var ray = this.ray;
  68929. if (!ray) {
  68930. return;
  68931. }
  68932. var point = this._renderPoints[1];
  68933. var len = Math.min(ray.length, 1000000);
  68934. point.copyFrom(ray.direction);
  68935. point.scaleInPlace(len);
  68936. point.addInPlace(ray.origin);
  68937. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  68938. };
  68939. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  68940. this._attachedToMesh = mesh;
  68941. var ray = this.ray;
  68942. if (!ray) {
  68943. return;
  68944. }
  68945. if (!ray.direction) {
  68946. ray.direction = BABYLON.Vector3.Zero();
  68947. }
  68948. if (!ray.origin) {
  68949. ray.origin = BABYLON.Vector3.Zero();
  68950. }
  68951. if (length) {
  68952. ray.length = length;
  68953. }
  68954. if (!meshSpaceOrigin) {
  68955. meshSpaceOrigin = BABYLON.Vector3.Zero();
  68956. }
  68957. if (!meshSpaceDirection) {
  68958. // -1 so that this will work with Mesh.lookAt
  68959. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  68960. }
  68961. if (!this._meshSpaceDirection) {
  68962. this._meshSpaceDirection = meshSpaceDirection.clone();
  68963. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  68964. }
  68965. else {
  68966. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  68967. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  68968. }
  68969. if (!this._updateToMeshFunction) {
  68970. this._updateToMeshFunction = this._updateToMesh.bind(this);
  68971. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  68972. }
  68973. this._updateToMesh();
  68974. };
  68975. RayHelper.prototype.detachFromMesh = function () {
  68976. if (this._attachedToMesh) {
  68977. if (this._updateToMeshFunction) {
  68978. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  68979. }
  68980. this._attachedToMesh = null;
  68981. this._updateToMeshFunction = null;
  68982. }
  68983. };
  68984. RayHelper.prototype._updateToMesh = function () {
  68985. var ray = this.ray;
  68986. if (!this._attachedToMesh || !ray) {
  68987. return;
  68988. }
  68989. if (this._attachedToMesh._isDisposed) {
  68990. this.detachFromMesh();
  68991. return;
  68992. }
  68993. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  68994. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  68995. };
  68996. RayHelper.prototype.dispose = function () {
  68997. this.hide();
  68998. this.detachFromMesh();
  68999. this.ray = null;
  69000. };
  69001. return RayHelper;
  69002. }());
  69003. BABYLON.RayHelper = RayHelper;
  69004. })(BABYLON || (BABYLON = {}));
  69005. //# sourceMappingURL=babylon.rayHelper.js.map
  69006. var BABYLON;
  69007. (function (BABYLON) {
  69008. // load the inspector using require, if not present in the global namespace.
  69009. var DebugLayer = /** @class */ (function () {
  69010. function DebugLayer(scene) {
  69011. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  69012. this._scene = scene;
  69013. // load inspector using require, if it doesn't exist on the global namespace.
  69014. }
  69015. /** Creates the inspector window. */
  69016. DebugLayer.prototype._createInspector = function (config) {
  69017. if (config === void 0) { config = {}; }
  69018. var popup = config.popup || false;
  69019. var initialTab = config.initialTab || 0;
  69020. var parentElement = config.parentElement || null;
  69021. if (!this._inspector) {
  69022. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  69023. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  69024. } // else nothing to do,; instance is already existing
  69025. };
  69026. DebugLayer.prototype.isVisible = function () {
  69027. if (!this._inspector) {
  69028. return false;
  69029. }
  69030. return true;
  69031. };
  69032. DebugLayer.prototype.hide = function () {
  69033. if (this._inspector) {
  69034. try {
  69035. this._inspector.dispose();
  69036. }
  69037. catch (e) {
  69038. // If the inspector has been removed directly from the inspector tool
  69039. }
  69040. this._inspector = null;
  69041. }
  69042. };
  69043. DebugLayer.prototype.show = function (config) {
  69044. if (config === void 0) { config = {}; }
  69045. if (typeof this.BJSINSPECTOR == 'undefined') {
  69046. // Load inspector and add it to the DOM
  69047. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  69048. }
  69049. else {
  69050. // Otherwise creates the inspector
  69051. this._createInspector(config);
  69052. }
  69053. };
  69054. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  69055. return DebugLayer;
  69056. }());
  69057. BABYLON.DebugLayer = DebugLayer;
  69058. })(BABYLON || (BABYLON = {}));
  69059. //# sourceMappingURL=babylon.debugLayer.js.map
  69060. var BABYLON;
  69061. (function (BABYLON) {
  69062. var Debug;
  69063. (function (Debug) {
  69064. var PhysicsViewer = /** @class */ (function () {
  69065. function PhysicsViewer(scene) {
  69066. this._impostors = [];
  69067. this._meshes = [];
  69068. this._numMeshes = 0;
  69069. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69070. var physicEngine = this._scene.getPhysicsEngine();
  69071. if (physicEngine) {
  69072. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  69073. }
  69074. }
  69075. PhysicsViewer.prototype._updateDebugMeshes = function () {
  69076. var plugin = this._physicsEnginePlugin;
  69077. for (var i = 0; i < this._numMeshes; i++) {
  69078. var impostor = this._impostors[i];
  69079. if (!impostor) {
  69080. continue;
  69081. }
  69082. if (impostor.isDisposed) {
  69083. this.hideImpostor(this._impostors[i--]);
  69084. }
  69085. else {
  69086. var mesh = this._meshes[i];
  69087. if (mesh && plugin) {
  69088. plugin.syncMeshWithImpostor(mesh, impostor);
  69089. }
  69090. }
  69091. }
  69092. };
  69093. PhysicsViewer.prototype.showImpostor = function (impostor) {
  69094. if (!this._scene) {
  69095. return;
  69096. }
  69097. for (var i = 0; i < this._numMeshes; i++) {
  69098. if (this._impostors[i] == impostor) {
  69099. return;
  69100. }
  69101. }
  69102. var debugMesh = this._getDebugMesh(impostor, this._scene);
  69103. if (debugMesh) {
  69104. this._impostors[this._numMeshes] = impostor;
  69105. this._meshes[this._numMeshes] = debugMesh;
  69106. if (this._numMeshes === 0) {
  69107. this._renderFunction = this._updateDebugMeshes.bind(this);
  69108. this._scene.registerBeforeRender(this._renderFunction);
  69109. }
  69110. this._numMeshes++;
  69111. }
  69112. };
  69113. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  69114. if (!impostor || !this._scene) {
  69115. return;
  69116. }
  69117. var removed = false;
  69118. for (var i = 0; i < this._numMeshes; i++) {
  69119. if (this._impostors[i] == impostor) {
  69120. var mesh = this._meshes[i];
  69121. if (!mesh) {
  69122. continue;
  69123. }
  69124. this._scene.removeMesh(mesh);
  69125. mesh.dispose();
  69126. this._numMeshes--;
  69127. if (this._numMeshes > 0) {
  69128. this._meshes[i] = this._meshes[this._numMeshes];
  69129. this._impostors[i] = this._impostors[this._numMeshes];
  69130. this._meshes[this._numMeshes] = null;
  69131. this._impostors[this._numMeshes] = null;
  69132. }
  69133. else {
  69134. this._meshes[0] = null;
  69135. this._impostors[0] = null;
  69136. }
  69137. removed = true;
  69138. break;
  69139. }
  69140. }
  69141. if (removed && this._numMeshes === 0) {
  69142. this._scene.unregisterBeforeRender(this._renderFunction);
  69143. }
  69144. };
  69145. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  69146. if (!this._debugMaterial) {
  69147. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  69148. this._debugMaterial.wireframe = true;
  69149. }
  69150. return this._debugMaterial;
  69151. };
  69152. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  69153. if (!this._debugBoxMesh) {
  69154. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  69155. this._debugBoxMesh.renderingGroupId = 1;
  69156. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  69157. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  69158. scene.removeMesh(this._debugBoxMesh);
  69159. }
  69160. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  69161. };
  69162. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  69163. if (!this._debugSphereMesh) {
  69164. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  69165. this._debugSphereMesh.renderingGroupId = 1;
  69166. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  69167. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  69168. scene.removeMesh(this._debugSphereMesh);
  69169. }
  69170. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  69171. };
  69172. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  69173. var mesh = null;
  69174. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  69175. mesh = this._getDebugBoxMesh(scene);
  69176. impostor.getBoxSizeToRef(mesh.scaling);
  69177. }
  69178. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  69179. mesh = this._getDebugSphereMesh(scene);
  69180. var radius = impostor.getRadius();
  69181. mesh.scaling.x = radius * 2;
  69182. mesh.scaling.y = radius * 2;
  69183. mesh.scaling.z = radius * 2;
  69184. }
  69185. return mesh;
  69186. };
  69187. PhysicsViewer.prototype.dispose = function () {
  69188. for (var i = 0; i < this._numMeshes; i++) {
  69189. this.hideImpostor(this._impostors[i]);
  69190. }
  69191. if (this._debugBoxMesh) {
  69192. this._debugBoxMesh.dispose();
  69193. }
  69194. if (this._debugSphereMesh) {
  69195. this._debugSphereMesh.dispose();
  69196. }
  69197. if (this._debugMaterial) {
  69198. this._debugMaterial.dispose();
  69199. }
  69200. this._impostors.length = 0;
  69201. this._scene = null;
  69202. this._physicsEnginePlugin = null;
  69203. };
  69204. return PhysicsViewer;
  69205. }());
  69206. Debug.PhysicsViewer = PhysicsViewer;
  69207. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69208. })(BABYLON || (BABYLON = {}));
  69209. //# sourceMappingURL=babylon.physicsViewer.js.map
  69210. var BABYLON;
  69211. (function (BABYLON) {
  69212. var BoundingBoxRenderer = /** @class */ (function () {
  69213. function BoundingBoxRenderer(scene) {
  69214. this.frontColor = new BABYLON.Color3(1, 1, 1);
  69215. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  69216. this.showBackLines = true;
  69217. this.renderList = new BABYLON.SmartArray(32);
  69218. this._vertexBuffers = {};
  69219. this._scene = scene;
  69220. }
  69221. BoundingBoxRenderer.prototype._prepareRessources = function () {
  69222. if (this._colorShader) {
  69223. return;
  69224. }
  69225. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  69226. attributes: [BABYLON.VertexBuffer.PositionKind],
  69227. uniforms: ["world", "viewProjection", "color"]
  69228. });
  69229. var engine = this._scene.getEngine();
  69230. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  69231. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  69232. this._createIndexBuffer();
  69233. };
  69234. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  69235. var engine = this._scene.getEngine();
  69236. 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]);
  69237. };
  69238. BoundingBoxRenderer.prototype._rebuild = function () {
  69239. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69240. if (vb) {
  69241. vb._rebuild();
  69242. }
  69243. this._createIndexBuffer();
  69244. };
  69245. BoundingBoxRenderer.prototype.reset = function () {
  69246. this.renderList.reset();
  69247. };
  69248. BoundingBoxRenderer.prototype.render = function () {
  69249. if (this.renderList.length === 0) {
  69250. return;
  69251. }
  69252. this._prepareRessources();
  69253. if (!this._colorShader.isReady()) {
  69254. return;
  69255. }
  69256. var engine = this._scene.getEngine();
  69257. engine.setDepthWrite(false);
  69258. this._colorShader._preBind();
  69259. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  69260. var boundingBox = this.renderList.data[boundingBoxIndex];
  69261. var min = boundingBox.minimum;
  69262. var max = boundingBox.maximum;
  69263. var diff = max.subtract(min);
  69264. var median = min.add(diff.scale(0.5));
  69265. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  69266. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  69267. .multiply(boundingBox.getWorldMatrix());
  69268. // VBOs
  69269. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  69270. if (this.showBackLines) {
  69271. // Back
  69272. engine.setDepthFunctionToGreaterOrEqual();
  69273. this._scene.resetCachedMaterial();
  69274. this._colorShader.setColor4("color", this.backColor.toColor4());
  69275. this._colorShader.bind(worldMatrix);
  69276. // Draw order
  69277. engine.draw(false, 0, 24);
  69278. }
  69279. // Front
  69280. engine.setDepthFunctionToLess();
  69281. this._scene.resetCachedMaterial();
  69282. this._colorShader.setColor4("color", this.frontColor.toColor4());
  69283. this._colorShader.bind(worldMatrix);
  69284. // Draw order
  69285. engine.draw(false, 0, 24);
  69286. }
  69287. this._colorShader.unbind();
  69288. engine.setDepthFunctionToLessOrEqual();
  69289. engine.setDepthWrite(true);
  69290. };
  69291. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  69292. this._prepareRessources();
  69293. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  69294. return;
  69295. }
  69296. var engine = this._scene.getEngine();
  69297. engine.setDepthWrite(false);
  69298. engine.setColorWrite(false);
  69299. this._colorShader._preBind();
  69300. var boundingBox = mesh._boundingInfo.boundingBox;
  69301. var min = boundingBox.minimum;
  69302. var max = boundingBox.maximum;
  69303. var diff = max.subtract(min);
  69304. var median = min.add(diff.scale(0.5));
  69305. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  69306. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  69307. .multiply(boundingBox.getWorldMatrix());
  69308. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  69309. engine.setDepthFunctionToLess();
  69310. this._scene.resetCachedMaterial();
  69311. this._colorShader.bind(worldMatrix);
  69312. engine.draw(false, 0, 24);
  69313. this._colorShader.unbind();
  69314. engine.setDepthFunctionToLessOrEqual();
  69315. engine.setDepthWrite(true);
  69316. engine.setColorWrite(true);
  69317. };
  69318. BoundingBoxRenderer.prototype.dispose = function () {
  69319. if (!this._colorShader) {
  69320. return;
  69321. }
  69322. this.renderList.dispose();
  69323. this._colorShader.dispose();
  69324. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69325. if (buffer) {
  69326. buffer.dispose();
  69327. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69328. }
  69329. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69330. };
  69331. return BoundingBoxRenderer;
  69332. }());
  69333. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  69334. })(BABYLON || (BABYLON = {}));
  69335. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  69336. var BABYLON;
  69337. (function (BABYLON) {
  69338. var MorphTarget = /** @class */ (function () {
  69339. function MorphTarget(name, influence) {
  69340. if (influence === void 0) { influence = 0; }
  69341. this.name = name;
  69342. this.animations = new Array();
  69343. this._positions = null;
  69344. this._normals = null;
  69345. this._tangents = null;
  69346. this.onInfluenceChanged = new BABYLON.Observable();
  69347. this.influence = influence;
  69348. }
  69349. Object.defineProperty(MorphTarget.prototype, "influence", {
  69350. get: function () {
  69351. return this._influence;
  69352. },
  69353. set: function (influence) {
  69354. if (this._influence === influence) {
  69355. return;
  69356. }
  69357. var previous = this._influence;
  69358. this._influence = influence;
  69359. if (this.onInfluenceChanged.hasObservers) {
  69360. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  69361. }
  69362. },
  69363. enumerable: true,
  69364. configurable: true
  69365. });
  69366. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  69367. get: function () {
  69368. return !!this._positions;
  69369. },
  69370. enumerable: true,
  69371. configurable: true
  69372. });
  69373. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  69374. get: function () {
  69375. return !!this._normals;
  69376. },
  69377. enumerable: true,
  69378. configurable: true
  69379. });
  69380. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  69381. get: function () {
  69382. return !!this._tangents;
  69383. },
  69384. enumerable: true,
  69385. configurable: true
  69386. });
  69387. MorphTarget.prototype.setPositions = function (data) {
  69388. this._positions = data;
  69389. };
  69390. MorphTarget.prototype.getPositions = function () {
  69391. return this._positions;
  69392. };
  69393. MorphTarget.prototype.setNormals = function (data) {
  69394. this._normals = data;
  69395. };
  69396. MorphTarget.prototype.getNormals = function () {
  69397. return this._normals;
  69398. };
  69399. MorphTarget.prototype.setTangents = function (data) {
  69400. this._tangents = data;
  69401. };
  69402. MorphTarget.prototype.getTangents = function () {
  69403. return this._tangents;
  69404. };
  69405. /**
  69406. * Serializes the current target into a Serialization object.
  69407. * Returns the serialized object.
  69408. */
  69409. MorphTarget.prototype.serialize = function () {
  69410. var serializationObject = {};
  69411. serializationObject.name = this.name;
  69412. serializationObject.influence = this.influence;
  69413. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  69414. if (this.hasNormals) {
  69415. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  69416. }
  69417. if (this.hasTangents) {
  69418. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  69419. }
  69420. // Animations
  69421. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  69422. return serializationObject;
  69423. };
  69424. // Statics
  69425. MorphTarget.Parse = function (serializationObject) {
  69426. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  69427. result.setPositions(serializationObject.positions);
  69428. if (serializationObject.normals) {
  69429. result.setNormals(serializationObject.normals);
  69430. }
  69431. if (serializationObject.tangents) {
  69432. result.setTangents(serializationObject.tangents);
  69433. }
  69434. // Animations
  69435. if (serializationObject.animations) {
  69436. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  69437. var parsedAnimation = serializationObject.animations[animationIndex];
  69438. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  69439. }
  69440. }
  69441. return result;
  69442. };
  69443. MorphTarget.FromMesh = function (mesh, name, influence) {
  69444. if (!name) {
  69445. name = mesh.name;
  69446. }
  69447. var result = new MorphTarget(name, influence);
  69448. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  69449. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  69450. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  69451. }
  69452. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  69453. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  69454. }
  69455. return result;
  69456. };
  69457. return MorphTarget;
  69458. }());
  69459. BABYLON.MorphTarget = MorphTarget;
  69460. })(BABYLON || (BABYLON = {}));
  69461. //# sourceMappingURL=babylon.morphTarget.js.map
  69462. var BABYLON;
  69463. (function (BABYLON) {
  69464. var MorphTargetManager = /** @class */ (function () {
  69465. function MorphTargetManager(scene) {
  69466. if (scene === void 0) { scene = null; }
  69467. this._targets = new Array();
  69468. this._targetObservable = new Array();
  69469. this._activeTargets = new BABYLON.SmartArray(16);
  69470. this._supportsNormals = false;
  69471. this._supportsTangents = false;
  69472. this._vertexCount = 0;
  69473. this._uniqueId = 0;
  69474. this._tempInfluences = new Array();
  69475. if (!scene) {
  69476. scene = BABYLON.Engine.LastCreatedScene;
  69477. }
  69478. this._scene = scene;
  69479. if (this._scene) {
  69480. this._scene.morphTargetManagers.push(this);
  69481. this._uniqueId = this._scene.getUniqueId();
  69482. }
  69483. }
  69484. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  69485. get: function () {
  69486. return this._uniqueId;
  69487. },
  69488. enumerable: true,
  69489. configurable: true
  69490. });
  69491. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  69492. get: function () {
  69493. return this._vertexCount;
  69494. },
  69495. enumerable: true,
  69496. configurable: true
  69497. });
  69498. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  69499. get: function () {
  69500. return this._supportsNormals;
  69501. },
  69502. enumerable: true,
  69503. configurable: true
  69504. });
  69505. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  69506. get: function () {
  69507. return this._supportsTangents;
  69508. },
  69509. enumerable: true,
  69510. configurable: true
  69511. });
  69512. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  69513. get: function () {
  69514. return this._targets.length;
  69515. },
  69516. enumerable: true,
  69517. configurable: true
  69518. });
  69519. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  69520. get: function () {
  69521. return this._activeTargets.length;
  69522. },
  69523. enumerable: true,
  69524. configurable: true
  69525. });
  69526. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  69527. get: function () {
  69528. return this._influences;
  69529. },
  69530. enumerable: true,
  69531. configurable: true
  69532. });
  69533. MorphTargetManager.prototype.getActiveTarget = function (index) {
  69534. return this._activeTargets.data[index];
  69535. };
  69536. MorphTargetManager.prototype.getTarget = function (index) {
  69537. return this._targets[index];
  69538. };
  69539. MorphTargetManager.prototype.addTarget = function (target) {
  69540. var _this = this;
  69541. this._targets.push(target);
  69542. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  69543. _this._syncActiveTargets(needUpdate);
  69544. }));
  69545. this._syncActiveTargets(true);
  69546. };
  69547. MorphTargetManager.prototype.removeTarget = function (target) {
  69548. var index = this._targets.indexOf(target);
  69549. if (index >= 0) {
  69550. this._targets.splice(index, 1);
  69551. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  69552. this._syncActiveTargets(true);
  69553. }
  69554. };
  69555. /**
  69556. * Serializes the current manager into a Serialization object.
  69557. * Returns the serialized object.
  69558. */
  69559. MorphTargetManager.prototype.serialize = function () {
  69560. var serializationObject = {};
  69561. serializationObject.id = this.uniqueId;
  69562. serializationObject.targets = [];
  69563. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  69564. var target = _a[_i];
  69565. serializationObject.targets.push(target.serialize());
  69566. }
  69567. return serializationObject;
  69568. };
  69569. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  69570. var influenceCount = 0;
  69571. this._activeTargets.reset();
  69572. this._supportsNormals = true;
  69573. this._supportsTangents = true;
  69574. this._vertexCount = 0;
  69575. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  69576. var target = _a[_i];
  69577. if (target.influence > 0) {
  69578. this._activeTargets.push(target);
  69579. this._tempInfluences[influenceCount++] = target.influence;
  69580. this._supportsNormals = this._supportsNormals && target.hasNormals;
  69581. this._supportsTangents = this._supportsTangents && target.hasTangents;
  69582. var positions = target.getPositions();
  69583. if (!positions) {
  69584. BABYLON.Tools.Error("Invalid target. Target must positions.");
  69585. return;
  69586. }
  69587. var vertexCount = positions.length / 3;
  69588. if (this._vertexCount === 0) {
  69589. this._vertexCount = vertexCount;
  69590. }
  69591. else if (this._vertexCount !== vertexCount) {
  69592. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  69593. return;
  69594. }
  69595. }
  69596. }
  69597. if (!this._influences || this._influences.length !== influenceCount) {
  69598. this._influences = new Float32Array(influenceCount);
  69599. }
  69600. for (var index = 0; index < influenceCount; index++) {
  69601. this._influences[index] = this._tempInfluences[index];
  69602. }
  69603. if (needUpdate && this._scene) {
  69604. // Flag meshes as dirty to resync with the active targets
  69605. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  69606. var mesh = _c[_b];
  69607. if (mesh.morphTargetManager === this) {
  69608. mesh._syncGeometryWithMorphTargetManager();
  69609. }
  69610. }
  69611. }
  69612. };
  69613. // Statics
  69614. MorphTargetManager.Parse = function (serializationObject, scene) {
  69615. var result = new MorphTargetManager(scene);
  69616. result._uniqueId = serializationObject.id;
  69617. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  69618. var targetData = _a[_i];
  69619. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  69620. }
  69621. return result;
  69622. };
  69623. return MorphTargetManager;
  69624. }());
  69625. BABYLON.MorphTargetManager = MorphTargetManager;
  69626. })(BABYLON || (BABYLON = {}));
  69627. //# sourceMappingURL=babylon.morphTargetManager.js.map
  69628. var BABYLON;
  69629. (function (BABYLON) {
  69630. var Octree = /** @class */ (function () {
  69631. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  69632. if (maxDepth === void 0) { maxDepth = 2; }
  69633. this.maxDepth = maxDepth;
  69634. this.dynamicContent = new Array();
  69635. this._maxBlockCapacity = maxBlockCapacity || 64;
  69636. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  69637. this._creationFunc = creationFunc;
  69638. }
  69639. // Methods
  69640. Octree.prototype.update = function (worldMin, worldMax, entries) {
  69641. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  69642. };
  69643. Octree.prototype.addMesh = function (entry) {
  69644. for (var index = 0; index < this.blocks.length; index++) {
  69645. var block = this.blocks[index];
  69646. block.addEntry(entry);
  69647. }
  69648. };
  69649. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  69650. this._selectionContent.reset();
  69651. for (var index = 0; index < this.blocks.length; index++) {
  69652. var block = this.blocks[index];
  69653. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  69654. }
  69655. if (allowDuplicate) {
  69656. this._selectionContent.concat(this.dynamicContent);
  69657. }
  69658. else {
  69659. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  69660. }
  69661. return this._selectionContent;
  69662. };
  69663. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  69664. this._selectionContent.reset();
  69665. for (var index = 0; index < this.blocks.length; index++) {
  69666. var block = this.blocks[index];
  69667. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  69668. }
  69669. if (allowDuplicate) {
  69670. this._selectionContent.concat(this.dynamicContent);
  69671. }
  69672. else {
  69673. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  69674. }
  69675. return this._selectionContent;
  69676. };
  69677. Octree.prototype.intersectsRay = function (ray) {
  69678. this._selectionContent.reset();
  69679. for (var index = 0; index < this.blocks.length; index++) {
  69680. var block = this.blocks[index];
  69681. block.intersectsRay(ray, this._selectionContent);
  69682. }
  69683. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  69684. return this._selectionContent;
  69685. };
  69686. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  69687. target.blocks = new Array();
  69688. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  69689. // Segmenting space
  69690. for (var x = 0; x < 2; x++) {
  69691. for (var y = 0; y < 2; y++) {
  69692. for (var z = 0; z < 2; z++) {
  69693. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  69694. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  69695. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  69696. block.addEntries(entries);
  69697. target.blocks.push(block);
  69698. }
  69699. }
  69700. }
  69701. };
  69702. Octree.CreationFuncForMeshes = function (entry, block) {
  69703. var boundingInfo = entry.getBoundingInfo();
  69704. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  69705. block.entries.push(entry);
  69706. }
  69707. };
  69708. Octree.CreationFuncForSubMeshes = function (entry, block) {
  69709. var boundingInfo = entry.getBoundingInfo();
  69710. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  69711. block.entries.push(entry);
  69712. }
  69713. };
  69714. return Octree;
  69715. }());
  69716. BABYLON.Octree = Octree;
  69717. })(BABYLON || (BABYLON = {}));
  69718. //# sourceMappingURL=babylon.octree.js.map
  69719. var BABYLON;
  69720. (function (BABYLON) {
  69721. var OctreeBlock = /** @class */ (function () {
  69722. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  69723. this.entries = new Array();
  69724. this._boundingVectors = new Array();
  69725. this._capacity = capacity;
  69726. this._depth = depth;
  69727. this._maxDepth = maxDepth;
  69728. this._creationFunc = creationFunc;
  69729. this._minPoint = minPoint;
  69730. this._maxPoint = maxPoint;
  69731. this._boundingVectors.push(minPoint.clone());
  69732. this._boundingVectors.push(maxPoint.clone());
  69733. this._boundingVectors.push(minPoint.clone());
  69734. this._boundingVectors[2].x = maxPoint.x;
  69735. this._boundingVectors.push(minPoint.clone());
  69736. this._boundingVectors[3].y = maxPoint.y;
  69737. this._boundingVectors.push(minPoint.clone());
  69738. this._boundingVectors[4].z = maxPoint.z;
  69739. this._boundingVectors.push(maxPoint.clone());
  69740. this._boundingVectors[5].z = minPoint.z;
  69741. this._boundingVectors.push(maxPoint.clone());
  69742. this._boundingVectors[6].x = minPoint.x;
  69743. this._boundingVectors.push(maxPoint.clone());
  69744. this._boundingVectors[7].y = minPoint.y;
  69745. }
  69746. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  69747. // Property
  69748. get: function () {
  69749. return this._capacity;
  69750. },
  69751. enumerable: true,
  69752. configurable: true
  69753. });
  69754. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  69755. get: function () {
  69756. return this._minPoint;
  69757. },
  69758. enumerable: true,
  69759. configurable: true
  69760. });
  69761. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  69762. get: function () {
  69763. return this._maxPoint;
  69764. },
  69765. enumerable: true,
  69766. configurable: true
  69767. });
  69768. // Methods
  69769. OctreeBlock.prototype.addEntry = function (entry) {
  69770. if (this.blocks) {
  69771. for (var index = 0; index < this.blocks.length; index++) {
  69772. var block = this.blocks[index];
  69773. block.addEntry(entry);
  69774. }
  69775. return;
  69776. }
  69777. this._creationFunc(entry, this);
  69778. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  69779. this.createInnerBlocks();
  69780. }
  69781. };
  69782. OctreeBlock.prototype.addEntries = function (entries) {
  69783. for (var index = 0; index < entries.length; index++) {
  69784. var mesh = entries[index];
  69785. this.addEntry(mesh);
  69786. }
  69787. };
  69788. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  69789. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  69790. if (this.blocks) {
  69791. for (var index = 0; index < this.blocks.length; index++) {
  69792. var block = this.blocks[index];
  69793. block.select(frustumPlanes, selection, allowDuplicate);
  69794. }
  69795. return;
  69796. }
  69797. if (allowDuplicate) {
  69798. selection.concat(this.entries);
  69799. }
  69800. else {
  69801. selection.concatWithNoDuplicate(this.entries);
  69802. }
  69803. }
  69804. };
  69805. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  69806. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  69807. if (this.blocks) {
  69808. for (var index = 0; index < this.blocks.length; index++) {
  69809. var block = this.blocks[index];
  69810. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  69811. }
  69812. return;
  69813. }
  69814. if (allowDuplicate) {
  69815. selection.concat(this.entries);
  69816. }
  69817. else {
  69818. selection.concatWithNoDuplicate(this.entries);
  69819. }
  69820. }
  69821. };
  69822. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  69823. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  69824. if (this.blocks) {
  69825. for (var index = 0; index < this.blocks.length; index++) {
  69826. var block = this.blocks[index];
  69827. block.intersectsRay(ray, selection);
  69828. }
  69829. return;
  69830. }
  69831. selection.concatWithNoDuplicate(this.entries);
  69832. }
  69833. };
  69834. OctreeBlock.prototype.createInnerBlocks = function () {
  69835. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  69836. };
  69837. return OctreeBlock;
  69838. }());
  69839. BABYLON.OctreeBlock = OctreeBlock;
  69840. })(BABYLON || (BABYLON = {}));
  69841. //# sourceMappingURL=babylon.octreeBlock.js.map
  69842. var BABYLON;
  69843. (function (BABYLON) {
  69844. var SIMDVector3 = /** @class */ (function () {
  69845. function SIMDVector3() {
  69846. }
  69847. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  69848. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  69849. };
  69850. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  69851. var m = transformation.m;
  69852. var m0 = SIMD.Float32x4.load(m, 0);
  69853. var m1 = SIMD.Float32x4.load(m, 4);
  69854. var m2 = SIMD.Float32x4.load(m, 8);
  69855. var m3 = SIMD.Float32x4.load(m, 12);
  69856. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  69857. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  69858. result.x = SIMD.Float32x4.extractLane(r, 0);
  69859. result.y = SIMD.Float32x4.extractLane(r, 1);
  69860. result.z = SIMD.Float32x4.extractLane(r, 2);
  69861. };
  69862. return SIMDVector3;
  69863. }());
  69864. var SIMDMatrix = /** @class */ (function () {
  69865. function SIMDMatrix() {
  69866. }
  69867. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  69868. var tm = this.m;
  69869. var om = other.m;
  69870. var m0 = SIMD.Float32x4.load(om, 0);
  69871. var m1 = SIMD.Float32x4.load(om, 4);
  69872. var m2 = SIMD.Float32x4.load(om, 8);
  69873. var m3 = SIMD.Float32x4.load(om, 12);
  69874. for (var i = 0; i < 16; i += 4) {
  69875. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  69876. }
  69877. return this;
  69878. };
  69879. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  69880. var src = this.m;
  69881. var dest = other.m;
  69882. // Load the 4 rows
  69883. var src0 = SIMD.Float32x4.load(src, 0);
  69884. var src1 = SIMD.Float32x4.load(src, 4);
  69885. var src2 = SIMD.Float32x4.load(src, 8);
  69886. var src3 = SIMD.Float32x4.load(src, 12);
  69887. // Transpose the source matrix. Sort of. Not a true transpose operation
  69888. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  69889. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  69890. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  69891. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  69892. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  69893. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  69894. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  69895. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  69896. // This is a true transposition, but it will lead to an incorrect result
  69897. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  69898. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  69899. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  69900. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  69901. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  69902. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  69903. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  69904. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  69905. // ----
  69906. tmp1 = SIMD.Float32x4.mul(row2, row3);
  69907. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69908. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  69909. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  69910. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69911. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  69912. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  69913. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  69914. // ----
  69915. tmp1 = SIMD.Float32x4.mul(row1, row2);
  69916. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69917. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  69918. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  69919. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69920. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  69921. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  69922. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  69923. // ----
  69924. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  69925. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69926. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  69927. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  69928. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  69929. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69930. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  69931. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  69932. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  69933. // ----
  69934. tmp1 = SIMD.Float32x4.mul(row0, row1);
  69935. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69936. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  69937. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  69938. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69939. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  69940. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  69941. // ----
  69942. tmp1 = SIMD.Float32x4.mul(row0, row3);
  69943. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69944. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  69945. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  69946. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69947. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  69948. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  69949. // ----
  69950. tmp1 = SIMD.Float32x4.mul(row0, row2);
  69951. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69952. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  69953. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  69954. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69955. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  69956. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  69957. // Compute determinant
  69958. var det = SIMD.Float32x4.mul(row0, minor0);
  69959. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  69960. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  69961. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  69962. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  69963. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  69964. // These shuffles aren't necessary if the faulty transposition is done
  69965. // up at the top of this function.
  69966. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  69967. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  69968. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  69969. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  69970. // Compute final values by multiplying with 1/det
  69971. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  69972. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  69973. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  69974. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  69975. return this;
  69976. };
  69977. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  69978. var out = result.m;
  69979. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  69980. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  69981. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  69982. // cc.kmVec3Subtract(f, pCenter, pEye);
  69983. var f = SIMD.Float32x4.sub(center, eye);
  69984. // cc.kmVec3Normalize(f, f);
  69985. var tmp = SIMD.Float32x4.mul(f, f);
  69986. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69987. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69988. // cc.kmVec3Assign(up, pUp);
  69989. // cc.kmVec3Normalize(up, up);
  69990. tmp = SIMD.Float32x4.mul(up, up);
  69991. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69992. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69993. // cc.kmVec3Cross(s, f, up);
  69994. var s = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 1, 2, 0, 3), SIMD.Float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 2, 0, 1, 3), SIMD.Float32x4.swizzle(up, 1, 2, 0, 3)));
  69995. // cc.kmVec3Normalize(s, s);
  69996. tmp = SIMD.Float32x4.mul(s, s);
  69997. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69998. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69999. // cc.kmVec3Cross(u, s, f);
  70000. var u = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 1, 2, 0, 3), SIMD.Float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 2, 0, 1, 3), SIMD.Float32x4.swizzle(f, 1, 2, 0, 3)));
  70001. // cc.kmVec3Normalize(s, s);
  70002. tmp = SIMD.Float32x4.mul(s, s);
  70003. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70004. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70005. var zero = SIMD.Float32x4.splat(0.0);
  70006. s = SIMD.Float32x4.neg(s);
  70007. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  70008. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  70009. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  70010. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  70011. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  70012. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  70013. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  70014. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  70015. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  70016. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  70017. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  70018. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  70019. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  70020. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  70021. };
  70022. return SIMDMatrix;
  70023. }());
  70024. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  70025. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  70026. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  70027. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  70028. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  70029. var SIMDHelper = /** @class */ (function () {
  70030. function SIMDHelper() {
  70031. }
  70032. Object.defineProperty(SIMDHelper, "IsEnabled", {
  70033. get: function () {
  70034. return SIMDHelper._isEnabled;
  70035. },
  70036. enumerable: true,
  70037. configurable: true
  70038. });
  70039. SIMDHelper.DisableSIMD = function () {
  70040. // Replace functions
  70041. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  70042. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  70043. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  70044. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  70045. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  70046. SIMDHelper._isEnabled = false;
  70047. };
  70048. SIMDHelper.EnableSIMD = function () {
  70049. if (self.SIMD === undefined) {
  70050. return;
  70051. }
  70052. // check if polyfills needed
  70053. if (!self.Math.fround) {
  70054. self.Math.fround = (function (array) { return function (x) {
  70055. return array[0] = x, array[0];
  70056. }; })(new Float32Array(1));
  70057. }
  70058. if (!self.Math.imul) {
  70059. self.Math.imul = function (a, b) {
  70060. var ah = (a >>> 16) & 0xffff;
  70061. var al = a & 0xffff;
  70062. var bh = (b >>> 16) & 0xffff;
  70063. var bl = b & 0xffff;
  70064. // the shift by 0 fixes the sign on the high part
  70065. // the final |0 converts the unsigned value into a signed value
  70066. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  70067. };
  70068. }
  70069. // Replace functions
  70070. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  70071. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  70072. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  70073. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  70074. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  70075. SIMDHelper._isEnabled = true;
  70076. };
  70077. SIMDHelper._isEnabled = false;
  70078. return SIMDHelper;
  70079. }());
  70080. BABYLON.SIMDHelper = SIMDHelper;
  70081. })(BABYLON || (BABYLON = {}));
  70082. //# sourceMappingURL=babylon.math.SIMD.js.map
  70083. var BABYLON;
  70084. (function (BABYLON) {
  70085. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  70086. __extends(VRDistortionCorrectionPostProcess, _super);
  70087. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  70088. var _this = _super.call(this, name, "vrDistortionCorrection", [
  70089. 'LensCenter',
  70090. 'Scale',
  70091. 'ScaleIn',
  70092. 'HmdWarpParam'
  70093. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  70094. _this._isRightEye = isRightEye;
  70095. _this._distortionFactors = vrMetrics.distortionK;
  70096. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  70097. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  70098. _this.adaptScaleToCurrentViewport = true;
  70099. _this.onSizeChangedObservable.add(function () {
  70100. _this.aspectRatio = _this.width * .5 / _this.height;
  70101. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  70102. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  70103. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  70104. });
  70105. _this.onApplyObservable.add(function (effect) {
  70106. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  70107. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  70108. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  70109. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  70110. });
  70111. return _this;
  70112. }
  70113. return VRDistortionCorrectionPostProcess;
  70114. }(BABYLON.PostProcess));
  70115. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  70116. })(BABYLON || (BABYLON = {}));
  70117. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  70118. var BABYLON;
  70119. (function (BABYLON) {
  70120. var AnaglyphPostProcess = /** @class */ (function (_super) {
  70121. __extends(AnaglyphPostProcess, _super);
  70122. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  70123. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  70124. _this._passedProcess = rigCameras[0]._rigPostProcess;
  70125. _this.onApplyObservable.add(function (effect) {
  70126. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  70127. });
  70128. return _this;
  70129. }
  70130. return AnaglyphPostProcess;
  70131. }(BABYLON.PostProcess));
  70132. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  70133. })(BABYLON || (BABYLON = {}));
  70134. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  70135. var BABYLON;
  70136. (function (BABYLON) {
  70137. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  70138. __extends(StereoscopicInterlacePostProcess, _super);
  70139. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  70140. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  70141. _this._passedProcess = rigCameras[0]._rigPostProcess;
  70142. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  70143. _this.onSizeChangedObservable.add(function () {
  70144. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  70145. });
  70146. _this.onApplyObservable.add(function (effect) {
  70147. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  70148. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  70149. });
  70150. return _this;
  70151. }
  70152. return StereoscopicInterlacePostProcess;
  70153. }(BABYLON.PostProcess));
  70154. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  70155. })(BABYLON || (BABYLON = {}));
  70156. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  70157. var BABYLON;
  70158. (function (BABYLON) {
  70159. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  70160. function FreeCameraDeviceOrientationInput() {
  70161. var _this = this;
  70162. this._screenOrientationAngle = 0;
  70163. this._screenQuaternion = new BABYLON.Quaternion();
  70164. this._alpha = 0;
  70165. this._beta = 0;
  70166. this._gamma = 0;
  70167. this._orientationChanged = function () {
  70168. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  70169. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  70170. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  70171. };
  70172. this._deviceOrientation = function (evt) {
  70173. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  70174. _this._beta = evt.beta !== null ? evt.beta : 0;
  70175. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  70176. };
  70177. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  70178. this._orientationChanged();
  70179. }
  70180. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  70181. get: function () {
  70182. return this._camera;
  70183. },
  70184. set: function (camera) {
  70185. this._camera = camera;
  70186. if (this._camera != null && !this._camera.rotationQuaternion) {
  70187. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  70188. }
  70189. },
  70190. enumerable: true,
  70191. configurable: true
  70192. });
  70193. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  70194. window.addEventListener("orientationchange", this._orientationChanged);
  70195. window.addEventListener("deviceorientation", this._deviceOrientation);
  70196. //In certain cases, the attach control is called AFTER orientation was changed,
  70197. //So this is needed.
  70198. this._orientationChanged();
  70199. };
  70200. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  70201. window.removeEventListener("orientationchange", this._orientationChanged);
  70202. window.removeEventListener("deviceorientation", this._deviceOrientation);
  70203. };
  70204. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  70205. //if no device orientation provided, don't update the rotation.
  70206. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  70207. if (!this._alpha)
  70208. return;
  70209. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  70210. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  70211. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  70212. //Mirror on XY Plane
  70213. this._camera.rotationQuaternion.z *= -1;
  70214. this._camera.rotationQuaternion.w *= -1;
  70215. };
  70216. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  70217. return "FreeCameraDeviceOrientationInput";
  70218. };
  70219. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  70220. return "deviceOrientation";
  70221. };
  70222. return FreeCameraDeviceOrientationInput;
  70223. }());
  70224. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  70225. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  70226. })(BABYLON || (BABYLON = {}));
  70227. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  70228. var BABYLON;
  70229. (function (BABYLON) {
  70230. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  70231. function ArcRotateCameraVRDeviceOrientationInput() {
  70232. this.alphaCorrection = 1;
  70233. this.betaCorrection = 1;
  70234. this.gammaCorrection = 1;
  70235. this._alpha = 0;
  70236. this._gamma = 0;
  70237. this._dirty = false;
  70238. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  70239. }
  70240. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  70241. this.camera.attachControl(element, noPreventDefault);
  70242. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  70243. };
  70244. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  70245. if (evt.alpha !== null) {
  70246. this._alpha = +evt.alpha | 0;
  70247. }
  70248. if (evt.gamma !== null) {
  70249. this._gamma = +evt.gamma | 0;
  70250. }
  70251. this._dirty = true;
  70252. };
  70253. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  70254. if (this._dirty) {
  70255. this._dirty = false;
  70256. if (this._gamma < 0) {
  70257. this._gamma = 180 + this._gamma;
  70258. }
  70259. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  70260. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  70261. }
  70262. };
  70263. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  70264. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  70265. };
  70266. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  70267. return "ArcRotateCameraVRDeviceOrientationInput";
  70268. };
  70269. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  70270. return "VRDeviceOrientation";
  70271. };
  70272. return ArcRotateCameraVRDeviceOrientationInput;
  70273. }());
  70274. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  70275. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  70276. })(BABYLON || (BABYLON = {}));
  70277. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  70278. var BABYLON;
  70279. (function (BABYLON) {
  70280. var VRCameraMetrics = /** @class */ (function () {
  70281. function VRCameraMetrics() {
  70282. this.compensateDistortion = true;
  70283. }
  70284. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  70285. get: function () {
  70286. return this.hResolution / (2 * this.vResolution);
  70287. },
  70288. enumerable: true,
  70289. configurable: true
  70290. });
  70291. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  70292. get: function () {
  70293. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  70294. },
  70295. enumerable: true,
  70296. configurable: true
  70297. });
  70298. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  70299. get: function () {
  70300. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  70301. var h = (4 * meters) / this.hScreenSize;
  70302. return BABYLON.Matrix.Translation(h, 0, 0);
  70303. },
  70304. enumerable: true,
  70305. configurable: true
  70306. });
  70307. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  70308. get: function () {
  70309. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  70310. var h = (4 * meters) / this.hScreenSize;
  70311. return BABYLON.Matrix.Translation(-h, 0, 0);
  70312. },
  70313. enumerable: true,
  70314. configurable: true
  70315. });
  70316. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  70317. get: function () {
  70318. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  70319. },
  70320. enumerable: true,
  70321. configurable: true
  70322. });
  70323. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  70324. get: function () {
  70325. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  70326. },
  70327. enumerable: true,
  70328. configurable: true
  70329. });
  70330. VRCameraMetrics.GetDefault = function () {
  70331. var result = new VRCameraMetrics();
  70332. result.hResolution = 1280;
  70333. result.vResolution = 800;
  70334. result.hScreenSize = 0.149759993;
  70335. result.vScreenSize = 0.0935999975;
  70336. result.vScreenCenter = 0.0467999987;
  70337. result.eyeToScreenDistance = 0.0410000011;
  70338. result.lensSeparationDistance = 0.0635000020;
  70339. result.interpupillaryDistance = 0.0640000030;
  70340. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  70341. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  70342. result.postProcessScaleFactor = 1.714605507808412;
  70343. result.lensCenterOffset = 0.151976421;
  70344. return result;
  70345. };
  70346. return VRCameraMetrics;
  70347. }());
  70348. BABYLON.VRCameraMetrics = VRCameraMetrics;
  70349. })(BABYLON || (BABYLON = {}));
  70350. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  70351. var BABYLON;
  70352. (function (BABYLON) {
  70353. var WebVRFreeCamera = /** @class */ (function (_super) {
  70354. __extends(WebVRFreeCamera, _super);
  70355. function WebVRFreeCamera(name, position, scene, webVROptions) {
  70356. if (webVROptions === void 0) { webVROptions = {}; }
  70357. var _this = _super.call(this, name, position, scene) || this;
  70358. _this.webVROptions = webVROptions;
  70359. _this._vrDevice = null;
  70360. _this.rawPose = null;
  70361. _this._specsVersion = "1.1";
  70362. _this._attached = false;
  70363. _this._descendants = [];
  70364. _this.devicePosition = BABYLON.Vector3.Zero();
  70365. _this.deviceScaleFactor = 1;
  70366. _this.controllers = [];
  70367. _this.onControllersAttachedObservable = new BABYLON.Observable();
  70368. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  70369. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  70370. _this.minZ = 0.1;
  70371. //legacy support - the compensation boolean was removed.
  70372. if (arguments.length === 5) {
  70373. _this.webVROptions = arguments[4];
  70374. }
  70375. // default webVR options
  70376. if (_this.webVROptions.trackPosition == undefined) {
  70377. _this.webVROptions.trackPosition = true;
  70378. }
  70379. if (_this.webVROptions.controllerMeshes == undefined) {
  70380. _this.webVROptions.controllerMeshes = true;
  70381. }
  70382. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  70383. _this.webVROptions.defaultLightingOnControllers = true;
  70384. }
  70385. _this.rotationQuaternion = new BABYLON.Quaternion();
  70386. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70387. if (_this.webVROptions && _this.webVROptions.positionScale) {
  70388. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  70389. }
  70390. //enable VR
  70391. var engine = _this.getEngine();
  70392. _this._onVREnabled = function (success) { if (success) {
  70393. _this.initControllers();
  70394. } };
  70395. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  70396. engine.initWebVR().add(function (event) {
  70397. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  70398. return;
  70399. }
  70400. _this._vrDevice = event.vrDisplay;
  70401. //reset the rig parameters.
  70402. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  70403. if (_this._attached) {
  70404. _this.getEngine().enableVR();
  70405. }
  70406. });
  70407. if (typeof (VRFrameData) !== "undefined")
  70408. _this._frameData = new VRFrameData();
  70409. /**
  70410. * The idea behind the following lines:
  70411. * objects that have the camera as parent should actually have the rig cameras as a parent.
  70412. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  70413. * the second will not show it correctly.
  70414. *
  70415. * To solve this - each object that has the camera as parent will be added to a protected array.
  70416. * When the rig camera renders, it will take this array and set all of those to be its children.
  70417. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  70418. * Amazing!
  70419. */
  70420. scene.onBeforeCameraRenderObservable.add(function (camera) {
  70421. if (camera.parent === _this && _this.rigParenting) {
  70422. _this._descendants = _this.getDescendants(true, function (n) {
  70423. // don't take the cameras or the controllers!
  70424. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  70425. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  70426. return !isController && !isRigCamera;
  70427. });
  70428. _this._descendants.forEach(function (node) {
  70429. node.parent = camera;
  70430. });
  70431. }
  70432. });
  70433. scene.onAfterCameraRenderObservable.add(function (camera) {
  70434. if (camera.parent === _this && _this.rigParenting) {
  70435. _this._descendants.forEach(function (node) {
  70436. node.parent = _this;
  70437. });
  70438. }
  70439. });
  70440. return _this;
  70441. }
  70442. WebVRFreeCamera.prototype.dispose = function () {
  70443. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  70444. _super.prototype.dispose.call(this);
  70445. };
  70446. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  70447. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  70448. var gp = _a[_i];
  70449. if (gp.hand === name) {
  70450. return gp;
  70451. }
  70452. }
  70453. return null;
  70454. };
  70455. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  70456. get: function () {
  70457. if (!this._leftController) {
  70458. this._leftController = this.getControllerByName("left");
  70459. }
  70460. return this._leftController;
  70461. },
  70462. enumerable: true,
  70463. configurable: true
  70464. });
  70465. ;
  70466. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  70467. get: function () {
  70468. if (!this._rightController) {
  70469. this._rightController = this.getControllerByName("right");
  70470. }
  70471. return this._rightController;
  70472. },
  70473. enumerable: true,
  70474. configurable: true
  70475. });
  70476. ;
  70477. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  70478. if (length === void 0) { length = 100; }
  70479. if (this.leftCamera) {
  70480. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  70481. }
  70482. else {
  70483. return _super.prototype.getForwardRay.call(this, length);
  70484. }
  70485. };
  70486. WebVRFreeCamera.prototype._checkInputs = function () {
  70487. if (this._vrDevice && this._vrDevice.isPresenting) {
  70488. this._vrDevice.getFrameData(this._frameData);
  70489. this.updateFromDevice(this._frameData.pose);
  70490. }
  70491. _super.prototype._checkInputs.call(this);
  70492. };
  70493. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  70494. if (poseData && poseData.orientation) {
  70495. this.rawPose = poseData;
  70496. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  70497. if (this.getScene().useRightHandedSystem) {
  70498. this.deviceRotationQuaternion.z *= -1;
  70499. this.deviceRotationQuaternion.w *= -1;
  70500. }
  70501. if (this.webVROptions.trackPosition && this.rawPose.position) {
  70502. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  70503. if (this.getScene().useRightHandedSystem) {
  70504. this.devicePosition.z *= -1;
  70505. }
  70506. }
  70507. }
  70508. };
  70509. /**
  70510. * WebVR's attach control will start broadcasting frames to the device.
  70511. * Note that in certain browsers (chrome for example) this function must be called
  70512. * within a user-interaction callback. Example:
  70513. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  70514. *
  70515. * @param {HTMLElement} element
  70516. * @param {boolean} [noPreventDefault]
  70517. *
  70518. * @memberOf WebVRFreeCamera
  70519. */
  70520. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  70521. _super.prototype.attachControl.call(this, element, noPreventDefault);
  70522. this._attached = true;
  70523. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  70524. if (this._vrDevice) {
  70525. this.getEngine().enableVR();
  70526. }
  70527. };
  70528. WebVRFreeCamera.prototype.detachControl = function (element) {
  70529. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70530. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70531. _super.prototype.detachControl.call(this, element);
  70532. this._attached = false;
  70533. this.getEngine().disableVR();
  70534. };
  70535. WebVRFreeCamera.prototype.getClassName = function () {
  70536. return "WebVRFreeCamera";
  70537. };
  70538. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  70539. //uses the vrDisplay's "resetPose()".
  70540. //pitch and roll won't be affected.
  70541. this._vrDevice.resetPose();
  70542. };
  70543. WebVRFreeCamera.prototype._updateRigCameras = function () {
  70544. var camLeft = this._rigCameras[0];
  70545. var camRight = this._rigCameras[1];
  70546. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70547. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70548. camLeft.position.copyFrom(this.devicePosition);
  70549. camRight.position.copyFrom(this.devicePosition);
  70550. };
  70551. /**
  70552. * This function is called by the two RIG cameras.
  70553. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  70554. */
  70555. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  70556. var _this = this;
  70557. //WebVR 1.1
  70558. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  70559. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  70560. if (!this.getScene().useRightHandedSystem) {
  70561. [2, 6, 8, 9, 14].forEach(function (num) {
  70562. _this._webvrViewMatrix.m[num] *= -1;
  70563. });
  70564. }
  70565. // update the camera rotation matrix
  70566. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  70567. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  70568. // Computing target and final matrix
  70569. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  70570. var parentCamera = this._cameraRigParams["parentCamera"];
  70571. // should the view matrix be updated with scale and position offset?
  70572. if (parentCamera.deviceScaleFactor !== 1) {
  70573. this._webvrViewMatrix.invert();
  70574. // scale the position, if set
  70575. if (parentCamera.deviceScaleFactor) {
  70576. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  70577. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  70578. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  70579. }
  70580. this._webvrViewMatrix.invert();
  70581. }
  70582. return this._webvrViewMatrix;
  70583. };
  70584. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  70585. var _this = this;
  70586. var parentCamera = this.parent;
  70587. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  70588. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  70589. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  70590. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  70591. //babylon compatible matrix
  70592. if (!this.getScene().useRightHandedSystem) {
  70593. [8, 9, 10, 11].forEach(function (num) {
  70594. _this._projectionMatrix.m[num] *= -1;
  70595. });
  70596. }
  70597. return this._projectionMatrix;
  70598. };
  70599. WebVRFreeCamera.prototype.initControllers = function () {
  70600. var _this = this;
  70601. this.controllers = [];
  70602. var manager = this.getScene().gamepadManager;
  70603. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70604. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  70605. var webVrController = gamepad;
  70606. if (webVrController.defaultModel) {
  70607. webVrController.defaultModel.setEnabled(false);
  70608. }
  70609. }
  70610. });
  70611. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70612. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  70613. var webVrController_1 = gamepad;
  70614. if (_this.webVROptions.controllerMeshes) {
  70615. if (webVrController_1.defaultModel) {
  70616. webVrController_1.defaultModel.setEnabled(true);
  70617. }
  70618. else {
  70619. // Load the meshes
  70620. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  70621. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  70622. if (_this.webVROptions.defaultLightingOnControllers) {
  70623. if (!_this._lightOnControllers) {
  70624. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  70625. }
  70626. var activateLightOnSubMeshes_1 = function (mesh, light) {
  70627. var children = mesh.getChildren();
  70628. if (children.length !== 0) {
  70629. children.forEach(function (mesh) {
  70630. light.includedOnlyMeshes.push(mesh);
  70631. activateLightOnSubMeshes_1(mesh, light);
  70632. });
  70633. }
  70634. };
  70635. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  70636. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  70637. }
  70638. });
  70639. }
  70640. }
  70641. webVrController_1.attachToPoseControlledCamera(_this);
  70642. // since this is async - sanity check. Is the controller already stored?
  70643. if (_this.controllers.indexOf(webVrController_1) === -1) {
  70644. //add to the controllers array
  70645. _this.controllers.push(webVrController_1);
  70646. //did we find enough controllers? Great! let the developer know.
  70647. if (_this.controllers.length >= 2) {
  70648. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  70649. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  70650. // So we're overriding setting left & right manually to be sure
  70651. var firstViveWandDetected = false;
  70652. for (var i = 0; i < _this.controllers.length; i++) {
  70653. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  70654. if (!firstViveWandDetected) {
  70655. firstViveWandDetected = true;
  70656. _this.controllers[i].hand = "left";
  70657. }
  70658. else {
  70659. _this.controllers[i].hand = "right";
  70660. }
  70661. }
  70662. }
  70663. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  70664. }
  70665. }
  70666. }
  70667. });
  70668. };
  70669. return WebVRFreeCamera;
  70670. }(BABYLON.FreeCamera));
  70671. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  70672. })(BABYLON || (BABYLON = {}));
  70673. //# sourceMappingURL=babylon.webVRCamera.js.map
  70674. var BABYLON;
  70675. (function (BABYLON) {
  70676. // We're mainly based on the logic defined into the FreeCamera code
  70677. var DeviceOrientationCamera = /** @class */ (function (_super) {
  70678. __extends(DeviceOrientationCamera, _super);
  70679. function DeviceOrientationCamera(name, position, scene) {
  70680. var _this = _super.call(this, name, position, scene) || this;
  70681. _this._quaternionCache = new BABYLON.Quaternion();
  70682. _this.inputs.addDeviceOrientation();
  70683. return _this;
  70684. }
  70685. DeviceOrientationCamera.prototype.getClassName = function () {
  70686. return "DeviceOrientationCamera";
  70687. };
  70688. DeviceOrientationCamera.prototype._checkInputs = function () {
  70689. _super.prototype._checkInputs.call(this);
  70690. this._quaternionCache.copyFrom(this.rotationQuaternion);
  70691. if (this._initialQuaternion) {
  70692. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  70693. }
  70694. };
  70695. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  70696. var _this = this;
  70697. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  70698. //can only work if this camera has a rotation quaternion already.
  70699. if (!this.rotationQuaternion)
  70700. return;
  70701. if (!this._initialQuaternion) {
  70702. this._initialQuaternion = new BABYLON.Quaternion();
  70703. }
  70704. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  70705. ['x', 'y', 'z'].forEach(function (axisName) {
  70706. if (!axis[axisName]) {
  70707. _this._initialQuaternion[axisName] = 0;
  70708. }
  70709. else {
  70710. _this._initialQuaternion[axisName] *= -1;
  70711. }
  70712. });
  70713. this._initialQuaternion.normalize();
  70714. //force rotation update
  70715. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  70716. };
  70717. return DeviceOrientationCamera;
  70718. }(BABYLON.FreeCamera));
  70719. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  70720. })(BABYLON || (BABYLON = {}));
  70721. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  70722. var BABYLON;
  70723. (function (BABYLON) {
  70724. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  70725. __extends(VRDeviceOrientationFreeCamera, _super);
  70726. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  70727. if (compensateDistortion === void 0) { compensateDistortion = true; }
  70728. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  70729. var _this = _super.call(this, name, position, scene) || this;
  70730. vrCameraMetrics.compensateDistortion = compensateDistortion;
  70731. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  70732. return _this;
  70733. }
  70734. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  70735. return "VRDeviceOrientationFreeCamera";
  70736. };
  70737. return VRDeviceOrientationFreeCamera;
  70738. }(BABYLON.DeviceOrientationCamera));
  70739. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  70740. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  70741. __extends(VRDeviceOrientationGamepadCamera, _super);
  70742. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  70743. if (compensateDistortion === void 0) { compensateDistortion = true; }
  70744. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  70745. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  70746. _this.inputs.addGamepad();
  70747. return _this;
  70748. }
  70749. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  70750. return "VRDeviceOrientationGamepadCamera";
  70751. };
  70752. return VRDeviceOrientationGamepadCamera;
  70753. }(VRDeviceOrientationFreeCamera));
  70754. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  70755. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  70756. __extends(VRDeviceOrientationArcRotateCamera, _super);
  70757. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  70758. if (compensateDistortion === void 0) { compensateDistortion = true; }
  70759. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  70760. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  70761. vrCameraMetrics.compensateDistortion = compensateDistortion;
  70762. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  70763. _this.inputs.addVRDeviceOrientation();
  70764. return _this;
  70765. }
  70766. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  70767. return "VRDeviceOrientationArcRotateCamera";
  70768. };
  70769. return VRDeviceOrientationArcRotateCamera;
  70770. }(BABYLON.ArcRotateCamera));
  70771. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  70772. })(BABYLON || (BABYLON = {}));
  70773. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  70774. var BABYLON;
  70775. (function (BABYLON) {
  70776. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  70777. __extends(AnaglyphFreeCamera, _super);
  70778. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  70779. var _this = _super.call(this, name, position, scene) || this;
  70780. _this.interaxialDistance = interaxialDistance;
  70781. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70782. return _this;
  70783. }
  70784. AnaglyphFreeCamera.prototype.getClassName = function () {
  70785. return "AnaglyphFreeCamera";
  70786. };
  70787. return AnaglyphFreeCamera;
  70788. }(BABYLON.FreeCamera));
  70789. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  70790. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  70791. __extends(AnaglyphArcRotateCamera, _super);
  70792. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  70793. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  70794. _this.interaxialDistance = interaxialDistance;
  70795. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70796. return _this;
  70797. }
  70798. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  70799. return "AnaglyphArcRotateCamera";
  70800. };
  70801. return AnaglyphArcRotateCamera;
  70802. }(BABYLON.ArcRotateCamera));
  70803. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  70804. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  70805. __extends(AnaglyphGamepadCamera, _super);
  70806. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  70807. var _this = _super.call(this, name, position, scene) || this;
  70808. _this.interaxialDistance = interaxialDistance;
  70809. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70810. return _this;
  70811. }
  70812. AnaglyphGamepadCamera.prototype.getClassName = function () {
  70813. return "AnaglyphGamepadCamera";
  70814. };
  70815. return AnaglyphGamepadCamera;
  70816. }(BABYLON.GamepadCamera));
  70817. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  70818. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  70819. __extends(AnaglyphUniversalCamera, _super);
  70820. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  70821. var _this = _super.call(this, name, position, scene) || this;
  70822. _this.interaxialDistance = interaxialDistance;
  70823. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70824. return _this;
  70825. }
  70826. AnaglyphUniversalCamera.prototype.getClassName = function () {
  70827. return "AnaglyphUniversalCamera";
  70828. };
  70829. return AnaglyphUniversalCamera;
  70830. }(BABYLON.UniversalCamera));
  70831. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  70832. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  70833. __extends(StereoscopicFreeCamera, _super);
  70834. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  70835. var _this = _super.call(this, name, position, scene) || this;
  70836. _this.interaxialDistance = interaxialDistance;
  70837. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70838. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70839. return _this;
  70840. }
  70841. StereoscopicFreeCamera.prototype.getClassName = function () {
  70842. return "StereoscopicFreeCamera";
  70843. };
  70844. return StereoscopicFreeCamera;
  70845. }(BABYLON.FreeCamera));
  70846. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  70847. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  70848. __extends(StereoscopicArcRotateCamera, _super);
  70849. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  70850. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  70851. _this.interaxialDistance = interaxialDistance;
  70852. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70853. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70854. return _this;
  70855. }
  70856. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  70857. return "StereoscopicArcRotateCamera";
  70858. };
  70859. return StereoscopicArcRotateCamera;
  70860. }(BABYLON.ArcRotateCamera));
  70861. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  70862. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  70863. __extends(StereoscopicGamepadCamera, _super);
  70864. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  70865. var _this = _super.call(this, name, position, scene) || this;
  70866. _this.interaxialDistance = interaxialDistance;
  70867. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70868. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70869. return _this;
  70870. }
  70871. StereoscopicGamepadCamera.prototype.getClassName = function () {
  70872. return "StereoscopicGamepadCamera";
  70873. };
  70874. return StereoscopicGamepadCamera;
  70875. }(BABYLON.GamepadCamera));
  70876. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  70877. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  70878. __extends(StereoscopicUniversalCamera, _super);
  70879. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  70880. var _this = _super.call(this, name, position, scene) || this;
  70881. _this.interaxialDistance = interaxialDistance;
  70882. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70883. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70884. return _this;
  70885. }
  70886. StereoscopicUniversalCamera.prototype.getClassName = function () {
  70887. return "StereoscopicUniversalCamera";
  70888. };
  70889. return StereoscopicUniversalCamera;
  70890. }(BABYLON.UniversalCamera));
  70891. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  70892. })(BABYLON || (BABYLON = {}));
  70893. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  70894. var BABYLON;
  70895. (function (BABYLON) {
  70896. var VRExperienceHelper = /** @class */ (function () {
  70897. function VRExperienceHelper(scene, webVROptions) {
  70898. if (webVROptions === void 0) { webVROptions = {}; }
  70899. var _this = this;
  70900. this.webVROptions = webVROptions;
  70901. // Can the system support WebVR, even if a headset isn't plugged in?
  70902. this._webVRsupported = false;
  70903. // If WebVR is supported, is a headset plugged in and are we ready to present?
  70904. this._webVRready = false;
  70905. // Are we waiting for the requestPresent callback to complete?
  70906. this._webVRrequesting = false;
  70907. // Are we presenting to the headset right now?
  70908. this._webVRpresenting = false;
  70909. // Are we presenting in the fullscreen fallback?
  70910. this._fullscreenVRpresenting = false;
  70911. this._useCustomVRButton = false;
  70912. this._teleportationRequested = false;
  70913. this._teleportationEnabledOnLeftController = false;
  70914. this._teleportationEnabledOnRightController = false;
  70915. this._leftControllerReady = false;
  70916. this._rightControllerReady = false;
  70917. this._teleportationAllowed = false;
  70918. this._rotationAllowed = true;
  70919. this._teleportationRequestInitiated = false;
  70920. //private _classicGamepadTeleportationRequestInitiated = false;
  70921. this._rotationRightAsked = false;
  70922. this._rotationLeftAsked = false;
  70923. this._teleportationFillColor = "#444444";
  70924. this._teleportationBorderColor = "#FFFFFF";
  70925. this._rotationAngle = 0;
  70926. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  70927. this._scene = scene;
  70928. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  70929. this._position = new BABYLON.Vector3(0, 2, 0);
  70930. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  70931. }
  70932. else {
  70933. this._position = this._scene.activeCamera.position.clone();
  70934. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position, scene);
  70935. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  70936. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  70937. }
  70938. this._scene.activeCamera = this._deviceOrientationCamera;
  70939. this._canvas = scene.getEngine().getRenderingCanvas();
  70940. if (this._canvas) {
  70941. this._scene.activeCamera.attachControl(this._canvas);
  70942. }
  70943. if (webVROptions) {
  70944. if (webVROptions.useCustomVRButton) {
  70945. this._useCustomVRButton = true;
  70946. if (webVROptions.customVRButton) {
  70947. this._btnVR = webVROptions.customVRButton;
  70948. }
  70949. }
  70950. }
  70951. if (!this._useCustomVRButton) {
  70952. this._btnVR = document.createElement("BUTTON");
  70953. this._btnVR.className = "babylonVRicon";
  70954. this._btnVR.id = "babylonVRiconbtn";
  70955. this._btnVR.title = "Click to switch to VR";
  70956. 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) }";
  70957. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  70958. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  70959. // css += ".babylonVRicon.vrdisplaysupported { }";
  70960. // css += ".babylonVRicon.vrdisplayready { }";
  70961. // css += ".babylonVRicon.vrdisplayrequesting { }";
  70962. var style = document.createElement('style');
  70963. style.appendChild(document.createTextNode(css));
  70964. document.getElementsByTagName('head')[0].appendChild(style);
  70965. }
  70966. if (this._canvas) {
  70967. if (!this._useCustomVRButton) {
  70968. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  70969. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  70970. }
  70971. if (this._btnVR) {
  70972. this._btnVR.addEventListener("click", function () {
  70973. _this.enterVR();
  70974. });
  70975. }
  70976. window.addEventListener("resize", function () {
  70977. if (_this._canvas && !_this._useCustomVRButton) {
  70978. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  70979. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  70980. }
  70981. if (_this._fullscreenVRpresenting && _this._webVRready) {
  70982. _this.exitVR();
  70983. }
  70984. });
  70985. }
  70986. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70987. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70988. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70989. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70990. if (!this._useCustomVRButton) {
  70991. document.body.appendChild(this._btnVR);
  70992. }
  70993. // Exiting VR mode using 'ESC' key on desktop
  70994. this._onKeyDown = function (event) {
  70995. if (event.keyCode === 27 && _this.isInVRMode()) {
  70996. _this.exitVR();
  70997. }
  70998. };
  70999. document.addEventListener("keydown", this._onKeyDown);
  71000. // Exiting VR mode double tapping the touch screen
  71001. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  71002. if (_this.isInVRMode()) {
  71003. _this.exitVR();
  71004. if (_this._fullscreenVRpresenting) {
  71005. _this._scene.getEngine().switchFullscreen(true);
  71006. }
  71007. }
  71008. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  71009. // Listen for WebVR display changes
  71010. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  71011. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  71012. this._onVRRequestPresentStart = function () {
  71013. _this._webVRrequesting = true;
  71014. _this.updateButtonVisibility();
  71015. };
  71016. this._onVRRequestPresentComplete = function (success) {
  71017. _this._webVRrequesting = false;
  71018. _this.updateButtonVisibility();
  71019. };
  71020. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  71021. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  71022. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  71023. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  71024. // Create the cameras
  71025. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  71026. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  71027. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  71028. this.updateButtonVisibility();
  71029. }
  71030. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  71031. get: function () {
  71032. return this._deviceOrientationCamera;
  71033. },
  71034. enumerable: true,
  71035. configurable: true
  71036. });
  71037. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  71038. // Based on the current WebVR support, returns the current VR camera used
  71039. get: function () {
  71040. if (this._webVRready) {
  71041. return this._webVRCamera;
  71042. }
  71043. else {
  71044. return this._vrDeviceOrientationCamera;
  71045. }
  71046. },
  71047. enumerable: true,
  71048. configurable: true
  71049. });
  71050. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  71051. get: function () {
  71052. return this._webVRCamera;
  71053. },
  71054. enumerable: true,
  71055. configurable: true
  71056. });
  71057. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  71058. get: function () {
  71059. return this._vrDeviceOrientationCamera;
  71060. },
  71061. enumerable: true,
  71062. configurable: true
  71063. });
  71064. // Raised when one of the controller has loaded successfully its associated default mesh
  71065. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  71066. if (webVRController.hand === "left") {
  71067. this._leftControllerReady = true;
  71068. if (this._teleportationRequested && !this._teleportationEnabledOnLeftController) {
  71069. this._enableTeleportationOnController(webVRController);
  71070. }
  71071. }
  71072. if (webVRController.hand === "right") {
  71073. this._rightControllerReady = true;
  71074. if (this._teleportationRequested && !this._teleportationEnabledOnRightController) {
  71075. this._enableTeleportationOnController(webVRController);
  71076. }
  71077. }
  71078. if (this.onControllerMeshLoaded) {
  71079. this.onControllerMeshLoaded(webVRController);
  71080. }
  71081. };
  71082. VRExperienceHelper.prototype._onFullscreenChange = function () {
  71083. if (document.fullscreen !== undefined) {
  71084. this._fullscreenVRpresenting = document.fullscreen;
  71085. }
  71086. else if (document.mozFullScreen !== undefined) {
  71087. this._fullscreenVRpresenting = document.mozFullScreen;
  71088. }
  71089. else if (document.webkitIsFullScreen !== undefined) {
  71090. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  71091. }
  71092. else if (document.msIsFullScreen !== undefined) {
  71093. this._fullscreenVRpresenting = document.msIsFullScreen;
  71094. }
  71095. if (!this._fullscreenVRpresenting && this._canvas) {
  71096. this.exitVR();
  71097. if (!this._useCustomVRButton) {
  71098. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  71099. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  71100. }
  71101. }
  71102. };
  71103. VRExperienceHelper.prototype.isInVRMode = function () {
  71104. return this._webVRpresenting || this._fullscreenVRpresenting;
  71105. };
  71106. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  71107. var vrDisplay = this._scene.getEngine().getVRDevice();
  71108. if (vrDisplay) {
  71109. var wasPresenting = this._webVRpresenting;
  71110. // A VR display is connected
  71111. this._webVRpresenting = vrDisplay.isPresenting;
  71112. if (wasPresenting && !this._webVRpresenting)
  71113. this.exitVR();
  71114. }
  71115. else {
  71116. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  71117. }
  71118. this.updateButtonVisibility();
  71119. };
  71120. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  71121. this._webVRsupported = eventArgs.vrSupported;
  71122. this._webVRready = !!eventArgs.vrDisplay;
  71123. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  71124. this.updateButtonVisibility();
  71125. };
  71126. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  71127. if (!this._btnVR) {
  71128. return;
  71129. }
  71130. this._btnVR.className = "babylonVRicon";
  71131. if (this.isInVRMode()) {
  71132. this._btnVR.className += " vrdisplaypresenting";
  71133. }
  71134. else {
  71135. if (this._webVRready)
  71136. this._btnVR.className += " vrdisplayready";
  71137. if (this._webVRsupported)
  71138. this._btnVR.className += " vrdisplaysupported";
  71139. if (this._webVRrequesting)
  71140. this._btnVR.className += " vrdisplayrequesting";
  71141. }
  71142. };
  71143. /**
  71144. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  71145. * Otherwise, will use the fullscreen API.
  71146. */
  71147. VRExperienceHelper.prototype.enterVR = function () {
  71148. if (this._scene.activeCamera) {
  71149. this._position = this._scene.activeCamera.position.clone();
  71150. }
  71151. if (this.onEnteringVR) {
  71152. this.onEnteringVR();
  71153. }
  71154. if (this._webVRrequesting)
  71155. return;
  71156. // If WebVR is supported and a headset is connected
  71157. if (this._webVRready) {
  71158. if (!this._webVRpresenting) {
  71159. this._webVRCamera.position = this._position;
  71160. this._scene.activeCamera = this._webVRCamera;
  71161. this._scene.imageProcessingConfiguration.isEnabled = true;
  71162. }
  71163. }
  71164. else {
  71165. this._vrDeviceOrientationCamera.position = this._position;
  71166. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  71167. this._scene.getEngine().switchFullscreen(true);
  71168. this.updateButtonVisibility();
  71169. }
  71170. if (this._scene.activeCamera && this._canvas) {
  71171. this._scene.activeCamera.attachControl(this._canvas);
  71172. }
  71173. };
  71174. /**
  71175. * Attempt to exit VR, or fullscreen.
  71176. */
  71177. VRExperienceHelper.prototype.exitVR = function () {
  71178. if (this.onExitingVR) {
  71179. this.onExitingVR();
  71180. }
  71181. if (this._webVRpresenting) {
  71182. this._scene.getEngine().disableVR();
  71183. }
  71184. if (this._scene.activeCamera) {
  71185. this._position = this._scene.activeCamera.position.clone();
  71186. }
  71187. this._deviceOrientationCamera.position = this._position;
  71188. this._scene.activeCamera = this._deviceOrientationCamera;
  71189. this._scene.imageProcessingConfiguration.isEnabled = false;
  71190. if (this._canvas) {
  71191. this._scene.activeCamera.attachControl(this._canvas);
  71192. }
  71193. this.updateButtonVisibility();
  71194. };
  71195. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  71196. get: function () {
  71197. return this._position;
  71198. },
  71199. set: function (value) {
  71200. this._position = value;
  71201. if (this._scene.activeCamera) {
  71202. this._scene.activeCamera.position = value;
  71203. }
  71204. },
  71205. enumerable: true,
  71206. configurable: true
  71207. });
  71208. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  71209. var _this = this;
  71210. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  71211. this._teleportationRequested = true;
  71212. if (vrTeleportationOptions) {
  71213. if (vrTeleportationOptions.floorMeshName) {
  71214. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  71215. }
  71216. }
  71217. if (this._leftControllerReady && this._webVRCamera.leftController) {
  71218. this._enableTeleportationOnController(this._webVRCamera.leftController);
  71219. }
  71220. if (this._rightControllerReady && this._webVRCamera.rightController) {
  71221. this._enableTeleportationOnController(this._webVRCamera.rightController);
  71222. }
  71223. this._scene.gamepadManager.onGamepadConnectedObservable.add(function (pad) { return _this._onNewGamepadConnected(pad); });
  71224. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera);
  71225. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  71226. this._scene.imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  71227. this._scene.imageProcessingConfiguration.vignetteEnabled = true;
  71228. this._scene.imageProcessingConfiguration.isEnabled = false;
  71229. this._createGazeTracker();
  71230. this._createTeleportationCircles();
  71231. this.meshSelectionPredicate = function (mesh) {
  71232. if (mesh.isVisible && mesh.name.indexOf("gazeTracker") === -1
  71233. && mesh.name.indexOf("teleportationCircle") === -1
  71234. && mesh.name.indexOf("torusTeleportation") === -1) {
  71235. return true;
  71236. }
  71237. return false;
  71238. };
  71239. this._scene.registerBeforeRender(function () {
  71240. _this._castRayAndSelectObject();
  71241. });
  71242. };
  71243. VRExperienceHelper.prototype._onNewGamepadConnected = function (gamepad) {
  71244. var _this = this;
  71245. if (gamepad.leftStick) {
  71246. gamepad.onleftstickchanged(function (stickValues) {
  71247. if (!_this._teleportationRequestInitiated) {
  71248. if (stickValues.y < -0.6) {
  71249. _this._teleportationRequestInitiated = true;
  71250. }
  71251. }
  71252. else {
  71253. if (stickValues.y > -0.4) {
  71254. if (_this._teleportationAllowed) {
  71255. _this._teleportCamera();
  71256. }
  71257. _this._teleportationRequestInitiated = false;
  71258. }
  71259. }
  71260. });
  71261. }
  71262. if (gamepad.rightStick) {
  71263. gamepad.onrightstickchanged(function (stickValues) {
  71264. if (!_this._rotationLeftAsked) {
  71265. if (stickValues.x < -0.6) {
  71266. _this._rotationLeftAsked = true;
  71267. if (_this._rotationAllowed) {
  71268. _this._rotateCamera(false);
  71269. }
  71270. }
  71271. }
  71272. else {
  71273. if (stickValues.x > -0.4) {
  71274. _this._rotationLeftAsked = false;
  71275. }
  71276. }
  71277. if (!_this._rotationRightAsked) {
  71278. if (stickValues.x > 0.6) {
  71279. _this._rotationRightAsked = true;
  71280. if (_this._rotationAllowed) {
  71281. _this._rotateCamera(true);
  71282. }
  71283. }
  71284. }
  71285. else {
  71286. if (stickValues.x < 0.4) {
  71287. _this._rotationRightAsked = false;
  71288. }
  71289. }
  71290. });
  71291. }
  71292. };
  71293. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  71294. var _this = this;
  71295. var controllerMesh = webVRController.mesh;
  71296. if (controllerMesh) {
  71297. var childMeshes = controllerMesh.getChildMeshes();
  71298. for (var i = 0; i < childMeshes.length; i++) {
  71299. if (childMeshes[i].name === "POINTING_POSE") {
  71300. controllerMesh = childMeshes[i];
  71301. break;
  71302. }
  71303. }
  71304. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 3, 0.004, 0.0001, 20, 1, this._scene, false);
  71305. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  71306. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  71307. laserPointerMaterial.alpha = 0.6;
  71308. laserPointer.material = laserPointerMaterial;
  71309. laserPointer.rotation.x = Math.PI / 2;
  71310. laserPointer.parent = controllerMesh;
  71311. laserPointer.position.z = -1.5;
  71312. laserPointer.position.y = 0;
  71313. laserPointer.isVisible = false;
  71314. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  71315. // Enabling / disabling laserPointer
  71316. if (stateObject.value === 1) {
  71317. laserPointer.isVisible = !laserPointer.isVisible;
  71318. }
  71319. });
  71320. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  71321. // on pressed
  71322. if (!_this._teleportationRequestInitiated) {
  71323. if (stateObject.y < -0.6) {
  71324. laserPointer.isVisible = true;
  71325. _this._teleportationRequestInitiated = true;
  71326. }
  71327. }
  71328. else {
  71329. if (stateObject.y > -0.4) {
  71330. if (_this._teleportationAllowed) {
  71331. _this._teleportCamera();
  71332. }
  71333. _this._teleportationRequestInitiated = false;
  71334. laserPointer.isVisible = false;
  71335. }
  71336. }
  71337. if (!_this._rotationLeftAsked) {
  71338. if (stateObject.x < -0.6) {
  71339. _this._rotationLeftAsked = true;
  71340. if (_this._rotationAllowed) {
  71341. _this._rotateCamera(false);
  71342. }
  71343. }
  71344. }
  71345. else {
  71346. if (stateObject.x > -0.4) {
  71347. _this._rotationLeftAsked = false;
  71348. }
  71349. }
  71350. if (!_this._rotationRightAsked) {
  71351. if (stateObject.x > 0.6) {
  71352. _this._rotationRightAsked = true;
  71353. if (_this._rotationAllowed) {
  71354. _this._rotateCamera(true);
  71355. }
  71356. }
  71357. }
  71358. else {
  71359. if (stateObject.x < 0.4) {
  71360. _this._rotationRightAsked = false;
  71361. }
  71362. }
  71363. });
  71364. }
  71365. };
  71366. // Little white circle attached to the camera
  71367. // That will act as the target to look on the floor where to teleport
  71368. VRExperienceHelper.prototype._createGazeTracker = function () {
  71369. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0050, 0.0020, 25, this._scene, false);
  71370. this._gazeTracker.bakeCurrentTransformIntoVertices();
  71371. this._gazeTracker.isPickable = false;
  71372. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  71373. targetMat.specularColor = BABYLON.Color3.Black();
  71374. targetMat.emissiveColor = BABYLON.Color3.White();
  71375. targetMat.backFaceCulling = false;
  71376. this._gazeTracker.material = targetMat;
  71377. };
  71378. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  71379. this._teleportationCircle = BABYLON.Mesh.CreateGround("teleportationCircle", 2, 2, 2, this._scene);
  71380. var length = 512;
  71381. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  71382. dynamicTexture.hasAlpha = true;
  71383. var context = dynamicTexture.getContext();
  71384. var centerX = length / 2;
  71385. var centerY = length / 2;
  71386. var radius = 200;
  71387. context.beginPath();
  71388. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  71389. context.fillStyle = this._teleportationFillColor;
  71390. context.fill();
  71391. context.lineWidth = 10;
  71392. context.strokeStyle = this._teleportationBorderColor;
  71393. context.stroke();
  71394. context.closePath();
  71395. dynamicTexture.update();
  71396. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  71397. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  71398. this._teleportationCircle.material = teleportationCircleMaterial;
  71399. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  71400. torus.parent = this._teleportationCircle;
  71401. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  71402. var keys = [];
  71403. keys.push({
  71404. frame: 0,
  71405. value: 0
  71406. });
  71407. keys.push({
  71408. frame: 30,
  71409. value: 0.4
  71410. });
  71411. keys.push({
  71412. frame: 60,
  71413. value: 0
  71414. });
  71415. animationInnerCircle.setKeys(keys);
  71416. var easingFunction = new BABYLON.SineEase();
  71417. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  71418. animationInnerCircle.setEasingFunction(easingFunction);
  71419. torus.animations = [];
  71420. torus.animations.push(animationInnerCircle);
  71421. this._scene.beginAnimation(torus, 0, 60, true);
  71422. this._hideTeleportationCircle();
  71423. };
  71424. VRExperienceHelper.prototype._displayTeleportationCircle = function () {
  71425. this._teleportationCircle.isVisible = true;
  71426. this._teleportationCircle.getChildren()[0].isVisible = true;
  71427. };
  71428. VRExperienceHelper.prototype._hideTeleportationCircle = function () {
  71429. this._teleportationCircle.isVisible = false;
  71430. this._teleportationCircle.getChildren()[0].isVisible = false;
  71431. };
  71432. VRExperienceHelper.prototype._rotateCamera = function (right) {
  71433. var _this = this;
  71434. if (right) {
  71435. this._rotationAngle++;
  71436. }
  71437. else {
  71438. this._rotationAngle--;
  71439. }
  71440. this.currentVRCamera.animations = [];
  71441. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  71442. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71443. var animationRotationKeys = [];
  71444. animationRotationKeys.push({
  71445. frame: 0,
  71446. value: this.currentVRCamera.rotationQuaternion
  71447. });
  71448. animationRotationKeys.push({
  71449. frame: 6,
  71450. value: target
  71451. });
  71452. animationRotation.setKeys(animationRotationKeys);
  71453. var easingFunction = new BABYLON.CircleEase();
  71454. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  71455. animationRotation.setEasingFunction(easingFunction);
  71456. this.currentVRCamera.animations.push(animationRotation);
  71457. this._postProcessMove.animations = [];
  71458. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71459. var vignetteWeightKeys = [];
  71460. vignetteWeightKeys.push({
  71461. frame: 0,
  71462. value: 0
  71463. });
  71464. vignetteWeightKeys.push({
  71465. frame: 3,
  71466. value: 4
  71467. });
  71468. vignetteWeightKeys.push({
  71469. frame: 6,
  71470. value: 0
  71471. });
  71472. animationPP.setKeys(vignetteWeightKeys);
  71473. animationPP.setEasingFunction(easingFunction);
  71474. this._postProcessMove.animations.push(animationPP);
  71475. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71476. var vignetteStretchKeys = [];
  71477. vignetteStretchKeys.push({
  71478. frame: 0,
  71479. value: 0
  71480. });
  71481. vignetteStretchKeys.push({
  71482. frame: 3,
  71483. value: 10
  71484. });
  71485. vignetteStretchKeys.push({
  71486. frame: 6,
  71487. value: 0
  71488. });
  71489. animationPP2.setKeys(vignetteStretchKeys);
  71490. animationPP2.setEasingFunction(easingFunction);
  71491. this._postProcessMove.animations.push(animationPP2);
  71492. this._scene.imageProcessingConfiguration.vignetteWeight = 0;
  71493. this._scene.imageProcessingConfiguration.vignetteStretch = 0;
  71494. this._scene.imageProcessingConfiguration.vignetteEnabled = true;
  71495. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  71496. _this._scene.imageProcessingConfiguration.vignetteEnabled = false;
  71497. });
  71498. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  71499. };
  71500. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (coordinates) {
  71501. this._teleportationAllowed = true;
  71502. if (this._teleportationRequestInitiated) {
  71503. this._displayTeleportationCircle();
  71504. }
  71505. else {
  71506. this._hideTeleportationCircle();
  71507. }
  71508. this._haloCenter.copyFrom(coordinates);
  71509. this._teleportationCircle.position = coordinates;
  71510. this._teleportationCircle.position.y += 0.001;
  71511. };
  71512. VRExperienceHelper.prototype._teleportCamera = function () {
  71513. var _this = this;
  71514. this.currentVRCamera.animations = [];
  71515. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position.x", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71516. var animationCameraTeleportationKeys = [];
  71517. animationCameraTeleportationKeys.push({
  71518. frame: 0,
  71519. value: this.currentVRCamera.position.x
  71520. });
  71521. animationCameraTeleportationKeys.push({
  71522. frame: 11,
  71523. value: this._haloCenter.x
  71524. });
  71525. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  71526. var easingFunction = new BABYLON.CircleEase();
  71527. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  71528. animationCameraTeleportation.setEasingFunction(easingFunction);
  71529. this.currentVRCamera.animations.push(animationCameraTeleportation);
  71530. var animationZoomIn2 = new BABYLON.Animation("animationZoomIn", "position.z", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71531. var keys2 = [];
  71532. keys2.push({
  71533. frame: 0,
  71534. value: this.currentVRCamera.position.z
  71535. });
  71536. keys2.push({
  71537. frame: 11,
  71538. value: this._haloCenter.z
  71539. });
  71540. animationZoomIn2.setKeys(keys2);
  71541. animationZoomIn2.setEasingFunction(easingFunction);
  71542. this.currentVRCamera.animations.push(animationZoomIn2);
  71543. this._postProcessMove.animations = [];
  71544. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71545. var vignetteWeightKeys = [];
  71546. vignetteWeightKeys.push({
  71547. frame: 0,
  71548. value: 0
  71549. });
  71550. vignetteWeightKeys.push({
  71551. frame: 5,
  71552. value: 8
  71553. });
  71554. vignetteWeightKeys.push({
  71555. frame: 11,
  71556. value: 0
  71557. });
  71558. animationPP.setKeys(vignetteWeightKeys);
  71559. this._postProcessMove.animations.push(animationPP);
  71560. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71561. var vignetteStretchKeys = [];
  71562. vignetteStretchKeys.push({
  71563. frame: 0,
  71564. value: 0
  71565. });
  71566. vignetteStretchKeys.push({
  71567. frame: 5,
  71568. value: 10
  71569. });
  71570. vignetteStretchKeys.push({
  71571. frame: 11,
  71572. value: 0
  71573. });
  71574. animationPP2.setKeys(vignetteStretchKeys);
  71575. this._postProcessMove.animations.push(animationPP2);
  71576. this._scene.imageProcessingConfiguration.vignetteWeight = 8;
  71577. this._scene.imageProcessingConfiguration.vignetteStretch = 10;
  71578. this._scene.imageProcessingConfiguration.vignetteEnabled = true;
  71579. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  71580. _this._scene.imageProcessingConfiguration.vignetteEnabled = false;
  71581. });
  71582. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1);
  71583. };
  71584. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  71585. var ray;
  71586. if (!this.currentVRCamera.rightController) {
  71587. ray = this.currentVRCamera.getForwardRay();
  71588. }
  71589. else {
  71590. ray = this.currentVRCamera.rightController.getForwardRay();
  71591. }
  71592. var hit = this._scene.pickWithRay(ray, this.meshSelectionPredicate);
  71593. if (hit && hit.pickedPoint) {
  71594. this._gazeTracker.scaling.x = hit.distance;
  71595. this._gazeTracker.scaling.y = hit.distance;
  71596. this._gazeTracker.scaling.z = hit.distance;
  71597. var pickNormal = hit.getNormal();
  71598. var deltaFighting = 0.002;
  71599. if (pickNormal) {
  71600. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  71601. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  71602. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  71603. }
  71604. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  71605. if (this._gazeTracker.position.x < 0) {
  71606. this._gazeTracker.position.x += deltaFighting;
  71607. }
  71608. else {
  71609. this._gazeTracker.position.x -= deltaFighting;
  71610. }
  71611. if (this._gazeTracker.position.y < 0) {
  71612. this._gazeTracker.position.y += deltaFighting;
  71613. }
  71614. else {
  71615. this._gazeTracker.position.y -= deltaFighting;
  71616. }
  71617. if (this._gazeTracker.position.z < 0) {
  71618. this._gazeTracker.position.z += deltaFighting;
  71619. }
  71620. else {
  71621. this._gazeTracker.position.z -= deltaFighting;
  71622. }
  71623. }
  71624. if (this._rayHelper) {
  71625. this._rayHelper.dispose();
  71626. }
  71627. if (this.currentVRCamera.rightController) {
  71628. this._rayHelper = BABYLON.RayHelper.CreateAndShow(ray, this._scene, new BABYLON.Color3(0.7, 0.7, 0.7));
  71629. }
  71630. if (hit && hit.pickedMesh) {
  71631. // The object selected is the floor, we're in a teleportation scenario
  71632. if (hit.pickedMesh.name.indexOf(this._floorMeshName) !== -1 && hit.pickedPoint) {
  71633. this._moveTeleportationSelectorTo(hit.pickedPoint);
  71634. return;
  71635. }
  71636. // If not, we're in a selection scenario
  71637. this._hideTeleportationCircle();
  71638. this._teleportationAllowed = false;
  71639. //currentMeshSelected = hit.pickedMesh;
  71640. }
  71641. else {
  71642. this._teleportationAllowed = false;
  71643. this._hideTeleportationCircle();
  71644. }
  71645. };
  71646. VRExperienceHelper.prototype.dispose = function () {
  71647. if (this.isInVRMode()) {
  71648. this.exitVR();
  71649. }
  71650. this._deviceOrientationCamera.dispose();
  71651. if (this._passProcessMove) {
  71652. this._passProcessMove.dispose();
  71653. }
  71654. if (this._postProcessMove) {
  71655. this._postProcessMove.dispose();
  71656. }
  71657. if (this._webVRCamera) {
  71658. this._webVRCamera.dispose();
  71659. }
  71660. if (this._vrDeviceOrientationCamera) {
  71661. this._vrDeviceOrientationCamera.dispose();
  71662. }
  71663. if (!this._useCustomVRButton) {
  71664. document.body.removeChild(this._btnVR);
  71665. }
  71666. document.removeEventListener("keydown", this._onKeyDown);
  71667. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  71668. };
  71669. VRExperienceHelper.prototype.getClassName = function () {
  71670. return "VRExperienceHelper";
  71671. };
  71672. return VRExperienceHelper;
  71673. }());
  71674. BABYLON.VRExperienceHelper = VRExperienceHelper;
  71675. })(BABYLON || (BABYLON = {}));
  71676. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  71677. // Mainly based on these 2 articles :
  71678. // 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
  71679. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  71680. var BABYLON;
  71681. (function (BABYLON) {
  71682. var JoystickAxis;
  71683. (function (JoystickAxis) {
  71684. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  71685. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  71686. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  71687. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  71688. var VirtualJoystick = /** @class */ (function () {
  71689. function VirtualJoystick(leftJoystick) {
  71690. var _this = this;
  71691. if (leftJoystick) {
  71692. this._leftJoystick = true;
  71693. }
  71694. else {
  71695. this._leftJoystick = false;
  71696. }
  71697. VirtualJoystick._globalJoystickIndex++;
  71698. // By default left & right arrow keys are moving the X
  71699. // and up & down keys are moving the Y
  71700. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  71701. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  71702. this.reverseLeftRight = false;
  71703. this.reverseUpDown = false;
  71704. // collections of pointers
  71705. this._touches = new BABYLON.StringDictionary();
  71706. this.deltaPosition = BABYLON.Vector3.Zero();
  71707. this._joystickSensibility = 25;
  71708. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  71709. this._onResize = function (evt) {
  71710. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  71711. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  71712. if (VirtualJoystick.vjCanvas) {
  71713. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  71714. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  71715. }
  71716. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  71717. };
  71718. // injecting a canvas element on top of the canvas 3D game
  71719. if (!VirtualJoystick.vjCanvas) {
  71720. window.addEventListener("resize", this._onResize, false);
  71721. VirtualJoystick.vjCanvas = document.createElement("canvas");
  71722. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  71723. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  71724. VirtualJoystick.vjCanvas.width = window.innerWidth;
  71725. VirtualJoystick.vjCanvas.height = window.innerHeight;
  71726. VirtualJoystick.vjCanvas.style.width = "100%";
  71727. VirtualJoystick.vjCanvas.style.height = "100%";
  71728. VirtualJoystick.vjCanvas.style.position = "absolute";
  71729. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  71730. VirtualJoystick.vjCanvas.style.top = "0px";
  71731. VirtualJoystick.vjCanvas.style.left = "0px";
  71732. VirtualJoystick.vjCanvas.style.zIndex = "5";
  71733. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  71734. // Support for jQuery PEP polyfill
  71735. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  71736. var context = VirtualJoystick.vjCanvas.getContext('2d');
  71737. if (!context) {
  71738. throw new Error("Unable to create canvas for virtual joystick");
  71739. }
  71740. VirtualJoystick.vjCanvasContext = context;
  71741. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  71742. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  71743. document.body.appendChild(VirtualJoystick.vjCanvas);
  71744. }
  71745. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  71746. this.pressed = false;
  71747. // default joystick color
  71748. this._joystickColor = "cyan";
  71749. this._joystickPointerID = -1;
  71750. // current joystick position
  71751. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  71752. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  71753. // origin joystick position
  71754. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  71755. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  71756. this._onPointerDownHandlerRef = function (evt) {
  71757. _this._onPointerDown(evt);
  71758. };
  71759. this._onPointerMoveHandlerRef = function (evt) {
  71760. _this._onPointerMove(evt);
  71761. };
  71762. this._onPointerUpHandlerRef = function (evt) {
  71763. _this._onPointerUp(evt);
  71764. };
  71765. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  71766. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  71767. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  71768. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  71769. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  71770. evt.preventDefault(); // Disables system menu
  71771. }, false);
  71772. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  71773. }
  71774. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  71775. this._joystickSensibility = newJoystickSensibility;
  71776. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  71777. };
  71778. VirtualJoystick.prototype._onPointerDown = function (e) {
  71779. var positionOnScreenCondition;
  71780. e.preventDefault();
  71781. if (this._leftJoystick === true) {
  71782. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  71783. }
  71784. else {
  71785. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  71786. }
  71787. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  71788. // First contact will be dedicated to the virtual joystick
  71789. this._joystickPointerID = e.pointerId;
  71790. this._joystickPointerStartPos.x = e.clientX;
  71791. this._joystickPointerStartPos.y = e.clientY;
  71792. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  71793. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  71794. this._deltaJoystickVector.x = 0;
  71795. this._deltaJoystickVector.y = 0;
  71796. this.pressed = true;
  71797. this._touches.add(e.pointerId.toString(), e);
  71798. }
  71799. else {
  71800. // You can only trigger the action buttons with a joystick declared
  71801. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  71802. this._action();
  71803. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  71804. }
  71805. }
  71806. };
  71807. VirtualJoystick.prototype._onPointerMove = function (e) {
  71808. // If the current pointer is the one associated to the joystick (first touch contact)
  71809. if (this._joystickPointerID == e.pointerId) {
  71810. this._joystickPointerPos.x = e.clientX;
  71811. this._joystickPointerPos.y = e.clientY;
  71812. this._deltaJoystickVector = this._joystickPointerPos.clone();
  71813. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  71814. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  71815. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  71816. switch (this._axisTargetedByLeftAndRight) {
  71817. case JoystickAxis.X:
  71818. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  71819. break;
  71820. case JoystickAxis.Y:
  71821. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  71822. break;
  71823. case JoystickAxis.Z:
  71824. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  71825. break;
  71826. }
  71827. var directionUpDown = this.reverseUpDown ? 1 : -1;
  71828. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  71829. switch (this._axisTargetedByUpAndDown) {
  71830. case JoystickAxis.X:
  71831. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  71832. break;
  71833. case JoystickAxis.Y:
  71834. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  71835. break;
  71836. case JoystickAxis.Z:
  71837. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  71838. break;
  71839. }
  71840. }
  71841. else {
  71842. var data = this._touches.get(e.pointerId.toString());
  71843. if (data) {
  71844. data.x = e.clientX;
  71845. data.y = e.clientY;
  71846. }
  71847. }
  71848. };
  71849. VirtualJoystick.prototype._onPointerUp = function (e) {
  71850. if (this._joystickPointerID == e.pointerId) {
  71851. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  71852. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  71853. this._joystickPointerID = -1;
  71854. this.pressed = false;
  71855. }
  71856. else {
  71857. var touch = this._touches.get(e.pointerId.toString());
  71858. if (touch) {
  71859. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  71860. }
  71861. }
  71862. this._deltaJoystickVector.x = 0;
  71863. this._deltaJoystickVector.y = 0;
  71864. this._touches.remove(e.pointerId.toString());
  71865. };
  71866. /**
  71867. * Change the color of the virtual joystick
  71868. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  71869. */
  71870. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  71871. this._joystickColor = newColor;
  71872. };
  71873. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  71874. this._action = action;
  71875. };
  71876. // Define which axis you'd like to control for left & right
  71877. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  71878. switch (axis) {
  71879. case JoystickAxis.X:
  71880. case JoystickAxis.Y:
  71881. case JoystickAxis.Z:
  71882. this._axisTargetedByLeftAndRight = axis;
  71883. break;
  71884. default:
  71885. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  71886. break;
  71887. }
  71888. };
  71889. // Define which axis you'd like to control for up & down
  71890. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  71891. switch (axis) {
  71892. case JoystickAxis.X:
  71893. case JoystickAxis.Y:
  71894. case JoystickAxis.Z:
  71895. this._axisTargetedByUpAndDown = axis;
  71896. break;
  71897. default:
  71898. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  71899. break;
  71900. }
  71901. };
  71902. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  71903. var _this = this;
  71904. if (this.pressed) {
  71905. this._touches.forEach(function (key, touch) {
  71906. if (touch.pointerId === _this._joystickPointerID) {
  71907. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  71908. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  71909. VirtualJoystick.vjCanvasContext.beginPath();
  71910. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  71911. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  71912. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  71913. VirtualJoystick.vjCanvasContext.stroke();
  71914. VirtualJoystick.vjCanvasContext.closePath();
  71915. VirtualJoystick.vjCanvasContext.beginPath();
  71916. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  71917. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  71918. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  71919. VirtualJoystick.vjCanvasContext.stroke();
  71920. VirtualJoystick.vjCanvasContext.closePath();
  71921. VirtualJoystick.vjCanvasContext.beginPath();
  71922. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  71923. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  71924. VirtualJoystick.vjCanvasContext.stroke();
  71925. VirtualJoystick.vjCanvasContext.closePath();
  71926. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  71927. }
  71928. else {
  71929. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  71930. VirtualJoystick.vjCanvasContext.beginPath();
  71931. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  71932. VirtualJoystick.vjCanvasContext.beginPath();
  71933. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  71934. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  71935. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  71936. VirtualJoystick.vjCanvasContext.stroke();
  71937. VirtualJoystick.vjCanvasContext.closePath();
  71938. touch.prevX = touch.x;
  71939. touch.prevY = touch.y;
  71940. }
  71941. ;
  71942. });
  71943. }
  71944. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  71945. };
  71946. VirtualJoystick.prototype.releaseCanvas = function () {
  71947. if (VirtualJoystick.vjCanvas) {
  71948. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  71949. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  71950. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  71951. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  71952. window.removeEventListener("resize", this._onResize);
  71953. document.body.removeChild(VirtualJoystick.vjCanvas);
  71954. VirtualJoystick.vjCanvas = null;
  71955. }
  71956. };
  71957. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  71958. VirtualJoystick._globalJoystickIndex = 0;
  71959. return VirtualJoystick;
  71960. }());
  71961. BABYLON.VirtualJoystick = VirtualJoystick;
  71962. })(BABYLON || (BABYLON = {}));
  71963. //# sourceMappingURL=babylon.virtualJoystick.js.map
  71964. var BABYLON;
  71965. (function (BABYLON) {
  71966. // We're mainly based on the logic defined into the FreeCamera code
  71967. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  71968. __extends(VirtualJoysticksCamera, _super);
  71969. function VirtualJoysticksCamera(name, position, scene) {
  71970. var _this = _super.call(this, name, position, scene) || this;
  71971. _this.inputs.addVirtualJoystick();
  71972. return _this;
  71973. }
  71974. VirtualJoysticksCamera.prototype.getClassName = function () {
  71975. return "VirtualJoysticksCamera";
  71976. };
  71977. return VirtualJoysticksCamera;
  71978. }(BABYLON.FreeCamera));
  71979. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  71980. })(BABYLON || (BABYLON = {}));
  71981. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  71982. var BABYLON;
  71983. (function (BABYLON) {
  71984. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  71985. function FreeCameraVirtualJoystickInput() {
  71986. }
  71987. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  71988. return this._leftjoystick;
  71989. };
  71990. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  71991. return this._rightjoystick;
  71992. };
  71993. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  71994. if (this._leftjoystick) {
  71995. var camera = this.camera;
  71996. var speed = camera._computeLocalCameraSpeed() * 50;
  71997. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  71998. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  71999. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  72000. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  72001. if (!this._leftjoystick.pressed) {
  72002. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  72003. }
  72004. if (!this._rightjoystick.pressed) {
  72005. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  72006. }
  72007. }
  72008. };
  72009. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  72010. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  72011. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  72012. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  72013. this._leftjoystick.setJoystickSensibility(0.15);
  72014. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  72015. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  72016. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  72017. this._rightjoystick.reverseUpDown = true;
  72018. this._rightjoystick.setJoystickSensibility(0.05);
  72019. this._rightjoystick.setJoystickColor("yellow");
  72020. };
  72021. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  72022. this._leftjoystick.releaseCanvas();
  72023. this._rightjoystick.releaseCanvas();
  72024. };
  72025. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  72026. return "FreeCameraVirtualJoystickInput";
  72027. };
  72028. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  72029. return "virtualJoystick";
  72030. };
  72031. return FreeCameraVirtualJoystickInput;
  72032. }());
  72033. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  72034. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  72035. })(BABYLON || (BABYLON = {}));
  72036. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  72037. var BABYLON;
  72038. (function (BABYLON) {
  72039. var SimplificationSettings = /** @class */ (function () {
  72040. function SimplificationSettings(quality, distance, optimizeMesh) {
  72041. this.quality = quality;
  72042. this.distance = distance;
  72043. this.optimizeMesh = optimizeMesh;
  72044. }
  72045. return SimplificationSettings;
  72046. }());
  72047. BABYLON.SimplificationSettings = SimplificationSettings;
  72048. var SimplificationQueue = /** @class */ (function () {
  72049. function SimplificationQueue() {
  72050. this.running = false;
  72051. this._simplificationArray = [];
  72052. }
  72053. SimplificationQueue.prototype.addTask = function (task) {
  72054. this._simplificationArray.push(task);
  72055. };
  72056. SimplificationQueue.prototype.executeNext = function () {
  72057. var task = this._simplificationArray.pop();
  72058. if (task) {
  72059. this.running = true;
  72060. this.runSimplification(task);
  72061. }
  72062. else {
  72063. this.running = false;
  72064. }
  72065. };
  72066. SimplificationQueue.prototype.runSimplification = function (task) {
  72067. var _this = this;
  72068. if (task.parallelProcessing) {
  72069. //parallel simplifier
  72070. task.settings.forEach(function (setting) {
  72071. var simplifier = _this.getSimplifier(task);
  72072. simplifier.simplify(setting, function (newMesh) {
  72073. task.mesh.addLODLevel(setting.distance, newMesh);
  72074. newMesh.isVisible = true;
  72075. //check if it is the last
  72076. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  72077. //all done, run the success callback.
  72078. task.successCallback();
  72079. }
  72080. _this.executeNext();
  72081. });
  72082. });
  72083. }
  72084. else {
  72085. //single simplifier.
  72086. var simplifier = this.getSimplifier(task);
  72087. var runDecimation = function (setting, callback) {
  72088. simplifier.simplify(setting, function (newMesh) {
  72089. task.mesh.addLODLevel(setting.distance, newMesh);
  72090. newMesh.isVisible = true;
  72091. //run the next quality level
  72092. callback();
  72093. });
  72094. };
  72095. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  72096. runDecimation(task.settings[loop.index], function () {
  72097. loop.executeNext();
  72098. });
  72099. }, function () {
  72100. //execution ended, run the success callback.
  72101. if (task.successCallback) {
  72102. task.successCallback();
  72103. }
  72104. _this.executeNext();
  72105. });
  72106. }
  72107. };
  72108. SimplificationQueue.prototype.getSimplifier = function (task) {
  72109. switch (task.simplificationType) {
  72110. case SimplificationType.QUADRATIC:
  72111. default:
  72112. return new QuadraticErrorSimplification(task.mesh);
  72113. }
  72114. };
  72115. return SimplificationQueue;
  72116. }());
  72117. BABYLON.SimplificationQueue = SimplificationQueue;
  72118. /**
  72119. * The implemented types of simplification.
  72120. * At the moment only Quadratic Error Decimation is implemented.
  72121. */
  72122. var SimplificationType;
  72123. (function (SimplificationType) {
  72124. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  72125. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  72126. var DecimationTriangle = /** @class */ (function () {
  72127. function DecimationTriangle(vertices) {
  72128. this.vertices = vertices;
  72129. this.error = new Array(4);
  72130. this.deleted = false;
  72131. this.isDirty = false;
  72132. this.deletePending = false;
  72133. this.borderFactor = 0;
  72134. }
  72135. return DecimationTriangle;
  72136. }());
  72137. BABYLON.DecimationTriangle = DecimationTriangle;
  72138. var DecimationVertex = /** @class */ (function () {
  72139. function DecimationVertex(position, id) {
  72140. this.position = position;
  72141. this.id = id;
  72142. this.isBorder = true;
  72143. this.q = new QuadraticMatrix();
  72144. this.triangleCount = 0;
  72145. this.triangleStart = 0;
  72146. this.originalOffsets = [];
  72147. }
  72148. DecimationVertex.prototype.updatePosition = function (newPosition) {
  72149. this.position.copyFrom(newPosition);
  72150. };
  72151. return DecimationVertex;
  72152. }());
  72153. BABYLON.DecimationVertex = DecimationVertex;
  72154. var QuadraticMatrix = /** @class */ (function () {
  72155. function QuadraticMatrix(data) {
  72156. this.data = new Array(10);
  72157. for (var i = 0; i < 10; ++i) {
  72158. if (data && data[i]) {
  72159. this.data[i] = data[i];
  72160. }
  72161. else {
  72162. this.data[i] = 0;
  72163. }
  72164. }
  72165. }
  72166. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  72167. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  72168. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  72169. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  72170. return det;
  72171. };
  72172. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  72173. for (var i = 0; i < 10; ++i) {
  72174. this.data[i] += matrix.data[i];
  72175. }
  72176. };
  72177. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  72178. for (var i = 0; i < 10; ++i) {
  72179. this.data[i] += data[i];
  72180. }
  72181. };
  72182. QuadraticMatrix.prototype.add = function (matrix) {
  72183. var m = new QuadraticMatrix();
  72184. for (var i = 0; i < 10; ++i) {
  72185. m.data[i] = this.data[i] + matrix.data[i];
  72186. }
  72187. return m;
  72188. };
  72189. QuadraticMatrix.FromData = function (a, b, c, d) {
  72190. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  72191. };
  72192. //returning an array to avoid garbage collection
  72193. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  72194. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  72195. };
  72196. return QuadraticMatrix;
  72197. }());
  72198. BABYLON.QuadraticMatrix = QuadraticMatrix;
  72199. var Reference = /** @class */ (function () {
  72200. function Reference(vertexId, triangleId) {
  72201. this.vertexId = vertexId;
  72202. this.triangleId = triangleId;
  72203. }
  72204. return Reference;
  72205. }());
  72206. BABYLON.Reference = Reference;
  72207. /**
  72208. * An implementation of the Quadratic Error simplification algorithm.
  72209. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  72210. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  72211. * @author RaananW
  72212. */
  72213. var QuadraticErrorSimplification = /** @class */ (function () {
  72214. function QuadraticErrorSimplification(_mesh) {
  72215. this._mesh = _mesh;
  72216. this.syncIterations = 5000;
  72217. this.aggressiveness = 7;
  72218. this.decimationIterations = 100;
  72219. this.boundingBoxEpsilon = BABYLON.Epsilon;
  72220. }
  72221. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  72222. var _this = this;
  72223. this.initDecimatedMesh();
  72224. //iterating through the submeshes array, one after the other.
  72225. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  72226. _this.initWithMesh(loop.index, function () {
  72227. _this.runDecimation(settings, loop.index, function () {
  72228. loop.executeNext();
  72229. });
  72230. }, settings.optimizeMesh);
  72231. }, function () {
  72232. setTimeout(function () {
  72233. successCallback(_this._reconstructedMesh);
  72234. }, 0);
  72235. });
  72236. };
  72237. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  72238. var _this = this;
  72239. var targetCount = ~~(this.triangles.length * settings.quality);
  72240. var deletedTriangles = 0;
  72241. var triangleCount = this.triangles.length;
  72242. var iterationFunction = function (iteration, callback) {
  72243. setTimeout(function () {
  72244. if (iteration % 5 === 0) {
  72245. _this.updateMesh(iteration === 0);
  72246. }
  72247. for (var i = 0; i < _this.triangles.length; ++i) {
  72248. _this.triangles[i].isDirty = false;
  72249. }
  72250. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  72251. var trianglesIterator = function (i) {
  72252. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  72253. var t = _this.triangles[tIdx];
  72254. if (!t)
  72255. return;
  72256. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  72257. return;
  72258. }
  72259. for (var j = 0; j < 3; ++j) {
  72260. if (t.error[j] < threshold) {
  72261. var deleted0 = [];
  72262. var deleted1 = [];
  72263. var v0 = t.vertices[j];
  72264. var v1 = t.vertices[(j + 1) % 3];
  72265. if (v0.isBorder || v1.isBorder)
  72266. continue;
  72267. var p = BABYLON.Vector3.Zero();
  72268. var n = BABYLON.Vector3.Zero();
  72269. var uv = BABYLON.Vector2.Zero();
  72270. var color = new BABYLON.Color4(0, 0, 0, 1);
  72271. _this.calculateError(v0, v1, p, n, uv, color);
  72272. var delTr = new Array();
  72273. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  72274. continue;
  72275. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  72276. continue;
  72277. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  72278. continue;
  72279. var uniqueArray = new Array();
  72280. delTr.forEach(function (deletedT) {
  72281. if (uniqueArray.indexOf(deletedT) === -1) {
  72282. deletedT.deletePending = true;
  72283. uniqueArray.push(deletedT);
  72284. }
  72285. });
  72286. if (uniqueArray.length % 2 !== 0) {
  72287. continue;
  72288. }
  72289. v0.q = v1.q.add(v0.q);
  72290. v0.updatePosition(p);
  72291. var tStart = _this.references.length;
  72292. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  72293. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  72294. var tCount = _this.references.length - tStart;
  72295. if (tCount <= v0.triangleCount) {
  72296. if (tCount) {
  72297. for (var c = 0; c < tCount; c++) {
  72298. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  72299. }
  72300. }
  72301. }
  72302. else {
  72303. v0.triangleStart = tStart;
  72304. }
  72305. v0.triangleCount = tCount;
  72306. break;
  72307. }
  72308. }
  72309. };
  72310. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  72311. }, 0);
  72312. };
  72313. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  72314. if (triangleCount - deletedTriangles <= targetCount)
  72315. loop.breakLoop();
  72316. else {
  72317. iterationFunction(loop.index, function () {
  72318. loop.executeNext();
  72319. });
  72320. }
  72321. }, function () {
  72322. setTimeout(function () {
  72323. //reconstruct this part of the mesh
  72324. _this.reconstructMesh(submeshIndex);
  72325. successCallback();
  72326. }, 0);
  72327. });
  72328. };
  72329. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  72330. var _this = this;
  72331. this.vertices = [];
  72332. this.triangles = [];
  72333. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  72334. var indices = this._mesh.getIndices();
  72335. var submesh = this._mesh.subMeshes[submeshIndex];
  72336. var findInVertices = function (positionToSearch) {
  72337. if (optimizeMesh) {
  72338. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  72339. if (_this.vertices[ii].position.equals(positionToSearch)) {
  72340. return _this.vertices[ii];
  72341. }
  72342. }
  72343. }
  72344. return null;
  72345. };
  72346. var vertexReferences = [];
  72347. var vertexInit = function (i) {
  72348. if (!positionData) {
  72349. return;
  72350. }
  72351. var offset = i + submesh.verticesStart;
  72352. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  72353. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  72354. vertex.originalOffsets.push(offset);
  72355. if (vertex.id === _this.vertices.length) {
  72356. _this.vertices.push(vertex);
  72357. }
  72358. vertexReferences.push(vertex.id);
  72359. };
  72360. //var totalVertices = mesh.getTotalVertices();
  72361. var totalVertices = submesh.verticesCount;
  72362. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  72363. var indicesInit = function (i) {
  72364. if (!indices) {
  72365. return;
  72366. }
  72367. var offset = (submesh.indexStart / 3) + i;
  72368. var pos = (offset * 3);
  72369. var i0 = indices[pos + 0];
  72370. var i1 = indices[pos + 1];
  72371. var i2 = indices[pos + 2];
  72372. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  72373. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  72374. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  72375. var triangle = new DecimationTriangle([v0, v1, v2]);
  72376. triangle.originalOffset = pos;
  72377. _this.triangles.push(triangle);
  72378. };
  72379. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  72380. _this.init(callback);
  72381. });
  72382. });
  72383. };
  72384. QuadraticErrorSimplification.prototype.init = function (callback) {
  72385. var _this = this;
  72386. var triangleInit1 = function (i) {
  72387. var t = _this.triangles[i];
  72388. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  72389. for (var j = 0; j < 3; j++) {
  72390. 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))));
  72391. }
  72392. };
  72393. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  72394. var triangleInit2 = function (i) {
  72395. var t = _this.triangles[i];
  72396. for (var j = 0; j < 3; ++j) {
  72397. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  72398. }
  72399. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  72400. };
  72401. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  72402. callback();
  72403. });
  72404. });
  72405. };
  72406. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  72407. var newTriangles = [];
  72408. var i;
  72409. for (i = 0; i < this.vertices.length; ++i) {
  72410. this.vertices[i].triangleCount = 0;
  72411. }
  72412. var t;
  72413. var j;
  72414. for (i = 0; i < this.triangles.length; ++i) {
  72415. if (!this.triangles[i].deleted) {
  72416. t = this.triangles[i];
  72417. for (j = 0; j < 3; ++j) {
  72418. t.vertices[j].triangleCount = 1;
  72419. }
  72420. newTriangles.push(t);
  72421. }
  72422. }
  72423. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  72424. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  72425. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  72426. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  72427. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  72428. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  72429. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  72430. var vertexCount = 0;
  72431. for (i = 0; i < this.vertices.length; ++i) {
  72432. var vertex = this.vertices[i];
  72433. vertex.id = vertexCount;
  72434. if (vertex.triangleCount) {
  72435. vertex.originalOffsets.forEach(function (originalOffset) {
  72436. if (!normalData) {
  72437. return;
  72438. }
  72439. newPositionData.push(vertex.position.x);
  72440. newPositionData.push(vertex.position.y);
  72441. newPositionData.push(vertex.position.z);
  72442. newNormalData.push(normalData[originalOffset * 3]);
  72443. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  72444. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  72445. if (uvs && uvs.length) {
  72446. newUVsData.push(uvs[(originalOffset * 2)]);
  72447. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  72448. }
  72449. else if (colorsData && colorsData.length) {
  72450. newColorsData.push(colorsData[(originalOffset * 4)]);
  72451. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  72452. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  72453. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  72454. }
  72455. ++vertexCount;
  72456. });
  72457. }
  72458. }
  72459. var startingIndex = this._reconstructedMesh.getTotalIndices();
  72460. var startingVertex = this._reconstructedMesh.getTotalVertices();
  72461. var submeshesArray = this._reconstructedMesh.subMeshes;
  72462. this._reconstructedMesh.subMeshes = [];
  72463. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  72464. var originalIndices = this._mesh.getIndices();
  72465. for (i = 0; i < newTriangles.length; ++i) {
  72466. t = newTriangles[i]; //now get the new referencing point for each vertex
  72467. [0, 1, 2].forEach(function (idx) {
  72468. var id = originalIndices[t.originalOffset + idx];
  72469. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  72470. if (offset < 0)
  72471. offset = 0;
  72472. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  72473. });
  72474. }
  72475. //overwriting the old vertex buffers and indices.
  72476. this._reconstructedMesh.setIndices(newIndicesArray);
  72477. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  72478. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  72479. if (newUVsData.length > 0)
  72480. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  72481. if (newColorsData.length > 0)
  72482. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  72483. //create submesh
  72484. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  72485. if (submeshIndex > 0) {
  72486. this._reconstructedMesh.subMeshes = [];
  72487. submeshesArray.forEach(function (submesh) {
  72488. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  72489. });
  72490. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  72491. }
  72492. };
  72493. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  72494. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  72495. this._reconstructedMesh.material = this._mesh.material;
  72496. this._reconstructedMesh.parent = this._mesh.parent;
  72497. this._reconstructedMesh.isVisible = false;
  72498. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  72499. };
  72500. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  72501. for (var i = 0; i < vertex1.triangleCount; ++i) {
  72502. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  72503. if (t.deleted)
  72504. continue;
  72505. var s = this.references[vertex1.triangleStart + i].vertexId;
  72506. var v1 = t.vertices[(s + 1) % 3];
  72507. var v2 = t.vertices[(s + 2) % 3];
  72508. if ((v1 === vertex2 || v2 === vertex2)) {
  72509. deletedArray[i] = true;
  72510. delTr.push(t);
  72511. continue;
  72512. }
  72513. var d1 = v1.position.subtract(point);
  72514. d1 = d1.normalize();
  72515. var d2 = v2.position.subtract(point);
  72516. d2 = d2.normalize();
  72517. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  72518. return true;
  72519. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  72520. deletedArray[i] = false;
  72521. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  72522. return true;
  72523. }
  72524. return false;
  72525. };
  72526. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  72527. var newDeleted = deletedTriangles;
  72528. for (var i = 0; i < vertex.triangleCount; ++i) {
  72529. var ref = this.references[vertex.triangleStart + i];
  72530. var t = this.triangles[ref.triangleId];
  72531. if (t.deleted)
  72532. continue;
  72533. if (deletedArray[i] && t.deletePending) {
  72534. t.deleted = true;
  72535. newDeleted++;
  72536. continue;
  72537. }
  72538. t.vertices[ref.vertexId] = origVertex;
  72539. t.isDirty = true;
  72540. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  72541. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  72542. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  72543. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  72544. this.references.push(ref);
  72545. }
  72546. return newDeleted;
  72547. };
  72548. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  72549. for (var i = 0; i < this.vertices.length; ++i) {
  72550. var vCount = [];
  72551. var vId = [];
  72552. var v = this.vertices[i];
  72553. var j;
  72554. for (j = 0; j < v.triangleCount; ++j) {
  72555. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  72556. for (var ii = 0; ii < 3; ii++) {
  72557. var ofs = 0;
  72558. var vv = triangle.vertices[ii];
  72559. while (ofs < vCount.length) {
  72560. if (vId[ofs] === vv.id)
  72561. break;
  72562. ++ofs;
  72563. }
  72564. if (ofs === vCount.length) {
  72565. vCount.push(1);
  72566. vId.push(vv.id);
  72567. }
  72568. else {
  72569. vCount[ofs]++;
  72570. }
  72571. }
  72572. }
  72573. for (j = 0; j < vCount.length; ++j) {
  72574. if (vCount[j] === 1) {
  72575. this.vertices[vId[j]].isBorder = true;
  72576. }
  72577. else {
  72578. this.vertices[vId[j]].isBorder = false;
  72579. }
  72580. }
  72581. }
  72582. };
  72583. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  72584. if (identifyBorders === void 0) { identifyBorders = false; }
  72585. var i;
  72586. if (!identifyBorders) {
  72587. var newTrianglesVector = [];
  72588. for (i = 0; i < this.triangles.length; ++i) {
  72589. if (!this.triangles[i].deleted) {
  72590. newTrianglesVector.push(this.triangles[i]);
  72591. }
  72592. }
  72593. this.triangles = newTrianglesVector;
  72594. }
  72595. for (i = 0; i < this.vertices.length; ++i) {
  72596. this.vertices[i].triangleCount = 0;
  72597. this.vertices[i].triangleStart = 0;
  72598. }
  72599. var t;
  72600. var j;
  72601. var v;
  72602. for (i = 0; i < this.triangles.length; ++i) {
  72603. t = this.triangles[i];
  72604. for (j = 0; j < 3; ++j) {
  72605. v = t.vertices[j];
  72606. v.triangleCount++;
  72607. }
  72608. }
  72609. var tStart = 0;
  72610. for (i = 0; i < this.vertices.length; ++i) {
  72611. this.vertices[i].triangleStart = tStart;
  72612. tStart += this.vertices[i].triangleCount;
  72613. this.vertices[i].triangleCount = 0;
  72614. }
  72615. var newReferences = new Array(this.triangles.length * 3);
  72616. for (i = 0; i < this.triangles.length; ++i) {
  72617. t = this.triangles[i];
  72618. for (j = 0; j < 3; ++j) {
  72619. v = t.vertices[j];
  72620. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  72621. v.triangleCount++;
  72622. }
  72623. }
  72624. this.references = newReferences;
  72625. if (identifyBorders) {
  72626. this.identifyBorder();
  72627. }
  72628. };
  72629. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  72630. var x = point.x;
  72631. var y = point.y;
  72632. var z = point.z;
  72633. 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
  72634. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  72635. };
  72636. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  72637. var q = vertex1.q.add(vertex2.q);
  72638. var border = vertex1.isBorder && vertex2.isBorder;
  72639. var error = 0;
  72640. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  72641. if (qDet !== 0 && !border) {
  72642. if (!pointResult) {
  72643. pointResult = BABYLON.Vector3.Zero();
  72644. }
  72645. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  72646. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  72647. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  72648. error = this.vertexError(q, pointResult);
  72649. }
  72650. else {
  72651. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  72652. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  72653. var error1 = this.vertexError(q, vertex1.position);
  72654. var error2 = this.vertexError(q, vertex2.position);
  72655. var error3 = this.vertexError(q, p3);
  72656. error = Math.min(error1, error2, error3);
  72657. if (error === error1) {
  72658. if (pointResult) {
  72659. pointResult.copyFrom(vertex1.position);
  72660. }
  72661. }
  72662. else if (error === error2) {
  72663. if (pointResult) {
  72664. pointResult.copyFrom(vertex2.position);
  72665. }
  72666. }
  72667. else {
  72668. if (pointResult) {
  72669. pointResult.copyFrom(p3);
  72670. }
  72671. }
  72672. }
  72673. return error;
  72674. };
  72675. return QuadraticErrorSimplification;
  72676. }());
  72677. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  72678. })(BABYLON || (BABYLON = {}));
  72679. //# sourceMappingURL=babylon.meshSimplification.js.map
  72680. var BABYLON;
  72681. (function (BABYLON) {
  72682. var Internals;
  72683. (function (Internals) {
  72684. var MeshLODLevel = /** @class */ (function () {
  72685. function MeshLODLevel(distance, mesh) {
  72686. this.distance = distance;
  72687. this.mesh = mesh;
  72688. }
  72689. return MeshLODLevel;
  72690. }());
  72691. Internals.MeshLODLevel = MeshLODLevel;
  72692. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  72693. })(BABYLON || (BABYLON = {}));
  72694. //# sourceMappingURL=babylon.meshLODLevel.js.map
  72695. var BABYLON;
  72696. (function (BABYLON) {
  72697. // Standard optimizations
  72698. var SceneOptimization = /** @class */ (function () {
  72699. function SceneOptimization(priority) {
  72700. if (priority === void 0) { priority = 0; }
  72701. this.priority = priority;
  72702. this.apply = function (scene) {
  72703. return true; // Return true if everything that can be done was applied
  72704. };
  72705. }
  72706. return SceneOptimization;
  72707. }());
  72708. BABYLON.SceneOptimization = SceneOptimization;
  72709. var TextureOptimization = /** @class */ (function (_super) {
  72710. __extends(TextureOptimization, _super);
  72711. function TextureOptimization(priority, maximumSize) {
  72712. if (priority === void 0) { priority = 0; }
  72713. if (maximumSize === void 0) { maximumSize = 1024; }
  72714. var _this = _super.call(this, priority) || this;
  72715. _this.priority = priority;
  72716. _this.maximumSize = maximumSize;
  72717. _this.apply = function (scene) {
  72718. var allDone = true;
  72719. for (var index = 0; index < scene.textures.length; index++) {
  72720. var texture = scene.textures[index];
  72721. if (!texture.canRescale || texture.getContext) {
  72722. continue;
  72723. }
  72724. var currentSize = texture.getSize();
  72725. var maxDimension = Math.max(currentSize.width, currentSize.height);
  72726. if (maxDimension > _this.maximumSize) {
  72727. texture.scale(0.5);
  72728. allDone = false;
  72729. }
  72730. }
  72731. return allDone;
  72732. };
  72733. return _this;
  72734. }
  72735. return TextureOptimization;
  72736. }(SceneOptimization));
  72737. BABYLON.TextureOptimization = TextureOptimization;
  72738. var HardwareScalingOptimization = /** @class */ (function (_super) {
  72739. __extends(HardwareScalingOptimization, _super);
  72740. function HardwareScalingOptimization(priority, maximumScale) {
  72741. if (priority === void 0) { priority = 0; }
  72742. if (maximumScale === void 0) { maximumScale = 2; }
  72743. var _this = _super.call(this, priority) || this;
  72744. _this.priority = priority;
  72745. _this.maximumScale = maximumScale;
  72746. _this._currentScale = 1;
  72747. _this.apply = function (scene) {
  72748. _this._currentScale++;
  72749. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  72750. return _this._currentScale >= _this.maximumScale;
  72751. };
  72752. return _this;
  72753. }
  72754. return HardwareScalingOptimization;
  72755. }(SceneOptimization));
  72756. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  72757. var ShadowsOptimization = /** @class */ (function (_super) {
  72758. __extends(ShadowsOptimization, _super);
  72759. function ShadowsOptimization() {
  72760. var _this = _super !== null && _super.apply(this, arguments) || this;
  72761. _this.apply = function (scene) {
  72762. scene.shadowsEnabled = false;
  72763. return true;
  72764. };
  72765. return _this;
  72766. }
  72767. return ShadowsOptimization;
  72768. }(SceneOptimization));
  72769. BABYLON.ShadowsOptimization = ShadowsOptimization;
  72770. var PostProcessesOptimization = /** @class */ (function (_super) {
  72771. __extends(PostProcessesOptimization, _super);
  72772. function PostProcessesOptimization() {
  72773. var _this = _super !== null && _super.apply(this, arguments) || this;
  72774. _this.apply = function (scene) {
  72775. scene.postProcessesEnabled = false;
  72776. return true;
  72777. };
  72778. return _this;
  72779. }
  72780. return PostProcessesOptimization;
  72781. }(SceneOptimization));
  72782. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  72783. var LensFlaresOptimization = /** @class */ (function (_super) {
  72784. __extends(LensFlaresOptimization, _super);
  72785. function LensFlaresOptimization() {
  72786. var _this = _super !== null && _super.apply(this, arguments) || this;
  72787. _this.apply = function (scene) {
  72788. scene.lensFlaresEnabled = false;
  72789. return true;
  72790. };
  72791. return _this;
  72792. }
  72793. return LensFlaresOptimization;
  72794. }(SceneOptimization));
  72795. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  72796. var ParticlesOptimization = /** @class */ (function (_super) {
  72797. __extends(ParticlesOptimization, _super);
  72798. function ParticlesOptimization() {
  72799. var _this = _super !== null && _super.apply(this, arguments) || this;
  72800. _this.apply = function (scene) {
  72801. scene.particlesEnabled = false;
  72802. return true;
  72803. };
  72804. return _this;
  72805. }
  72806. return ParticlesOptimization;
  72807. }(SceneOptimization));
  72808. BABYLON.ParticlesOptimization = ParticlesOptimization;
  72809. var RenderTargetsOptimization = /** @class */ (function (_super) {
  72810. __extends(RenderTargetsOptimization, _super);
  72811. function RenderTargetsOptimization() {
  72812. var _this = _super !== null && _super.apply(this, arguments) || this;
  72813. _this.apply = function (scene) {
  72814. scene.renderTargetsEnabled = false;
  72815. return true;
  72816. };
  72817. return _this;
  72818. }
  72819. return RenderTargetsOptimization;
  72820. }(SceneOptimization));
  72821. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  72822. var MergeMeshesOptimization = /** @class */ (function (_super) {
  72823. __extends(MergeMeshesOptimization, _super);
  72824. function MergeMeshesOptimization() {
  72825. var _this = _super !== null && _super.apply(this, arguments) || this;
  72826. _this._canBeMerged = function (abstractMesh) {
  72827. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  72828. return false;
  72829. }
  72830. var mesh = abstractMesh;
  72831. if (!mesh.isVisible || !mesh.isEnabled()) {
  72832. return false;
  72833. }
  72834. if (mesh.instances.length > 0) {
  72835. return false;
  72836. }
  72837. if (mesh.skeleton || mesh.hasLODLevels) {
  72838. return false;
  72839. }
  72840. if (mesh.parent) {
  72841. return false;
  72842. }
  72843. return true;
  72844. };
  72845. _this.apply = function (scene, updateSelectionTree) {
  72846. var globalPool = scene.meshes.slice(0);
  72847. var globalLength = globalPool.length;
  72848. for (var index = 0; index < globalLength; index++) {
  72849. var currentPool = new Array();
  72850. var current = globalPool[index];
  72851. // Checks
  72852. if (!_this._canBeMerged(current)) {
  72853. continue;
  72854. }
  72855. currentPool.push(current);
  72856. // Find compatible meshes
  72857. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  72858. var otherMesh = globalPool[subIndex];
  72859. if (!_this._canBeMerged(otherMesh)) {
  72860. continue;
  72861. }
  72862. if (otherMesh.material !== current.material) {
  72863. continue;
  72864. }
  72865. if (otherMesh.checkCollisions !== current.checkCollisions) {
  72866. continue;
  72867. }
  72868. currentPool.push(otherMesh);
  72869. globalLength--;
  72870. globalPool.splice(subIndex, 1);
  72871. subIndex--;
  72872. }
  72873. if (currentPool.length < 2) {
  72874. continue;
  72875. }
  72876. // Merge meshes
  72877. BABYLON.Mesh.MergeMeshes(currentPool);
  72878. }
  72879. if (updateSelectionTree != undefined) {
  72880. if (updateSelectionTree) {
  72881. scene.createOrUpdateSelectionOctree();
  72882. }
  72883. }
  72884. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  72885. scene.createOrUpdateSelectionOctree();
  72886. }
  72887. return true;
  72888. };
  72889. return _this;
  72890. }
  72891. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  72892. get: function () {
  72893. return MergeMeshesOptimization._UpdateSelectionTree;
  72894. },
  72895. set: function (value) {
  72896. MergeMeshesOptimization._UpdateSelectionTree = value;
  72897. },
  72898. enumerable: true,
  72899. configurable: true
  72900. });
  72901. MergeMeshesOptimization._UpdateSelectionTree = false;
  72902. return MergeMeshesOptimization;
  72903. }(SceneOptimization));
  72904. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  72905. // Options
  72906. var SceneOptimizerOptions = /** @class */ (function () {
  72907. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  72908. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  72909. if (trackerDuration === void 0) { trackerDuration = 2000; }
  72910. this.targetFrameRate = targetFrameRate;
  72911. this.trackerDuration = trackerDuration;
  72912. this.optimizations = new Array();
  72913. }
  72914. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  72915. var result = new SceneOptimizerOptions(targetFrameRate);
  72916. var priority = 0;
  72917. result.optimizations.push(new MergeMeshesOptimization(priority));
  72918. result.optimizations.push(new ShadowsOptimization(priority));
  72919. result.optimizations.push(new LensFlaresOptimization(priority));
  72920. // Next priority
  72921. priority++;
  72922. result.optimizations.push(new PostProcessesOptimization(priority));
  72923. result.optimizations.push(new ParticlesOptimization(priority));
  72924. // Next priority
  72925. priority++;
  72926. result.optimizations.push(new TextureOptimization(priority, 1024));
  72927. return result;
  72928. };
  72929. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  72930. var result = new SceneOptimizerOptions(targetFrameRate);
  72931. var priority = 0;
  72932. result.optimizations.push(new MergeMeshesOptimization(priority));
  72933. result.optimizations.push(new ShadowsOptimization(priority));
  72934. result.optimizations.push(new LensFlaresOptimization(priority));
  72935. // Next priority
  72936. priority++;
  72937. result.optimizations.push(new PostProcessesOptimization(priority));
  72938. result.optimizations.push(new ParticlesOptimization(priority));
  72939. // Next priority
  72940. priority++;
  72941. result.optimizations.push(new TextureOptimization(priority, 512));
  72942. // Next priority
  72943. priority++;
  72944. result.optimizations.push(new RenderTargetsOptimization(priority));
  72945. // Next priority
  72946. priority++;
  72947. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  72948. return result;
  72949. };
  72950. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  72951. var result = new SceneOptimizerOptions(targetFrameRate);
  72952. var priority = 0;
  72953. result.optimizations.push(new MergeMeshesOptimization(priority));
  72954. result.optimizations.push(new ShadowsOptimization(priority));
  72955. result.optimizations.push(new LensFlaresOptimization(priority));
  72956. // Next priority
  72957. priority++;
  72958. result.optimizations.push(new PostProcessesOptimization(priority));
  72959. result.optimizations.push(new ParticlesOptimization(priority));
  72960. // Next priority
  72961. priority++;
  72962. result.optimizations.push(new TextureOptimization(priority, 256));
  72963. // Next priority
  72964. priority++;
  72965. result.optimizations.push(new RenderTargetsOptimization(priority));
  72966. // Next priority
  72967. priority++;
  72968. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  72969. return result;
  72970. };
  72971. return SceneOptimizerOptions;
  72972. }());
  72973. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  72974. // Scene optimizer tool
  72975. var SceneOptimizer = /** @class */ (function () {
  72976. function SceneOptimizer() {
  72977. }
  72978. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  72979. // TODO: add an epsilon
  72980. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  72981. if (onSuccess) {
  72982. onSuccess();
  72983. }
  72984. return;
  72985. }
  72986. // Apply current level of optimizations
  72987. var allDone = true;
  72988. var noOptimizationApplied = true;
  72989. for (var index = 0; index < options.optimizations.length; index++) {
  72990. var optimization = options.optimizations[index];
  72991. if (optimization.priority === currentPriorityLevel) {
  72992. noOptimizationApplied = false;
  72993. allDone = allDone && optimization.apply(scene);
  72994. }
  72995. }
  72996. // If no optimization was applied, this is a failure :(
  72997. if (noOptimizationApplied) {
  72998. if (onFailure) {
  72999. onFailure();
  73000. }
  73001. return;
  73002. }
  73003. // If all optimizations were done, move to next level
  73004. if (allDone) {
  73005. currentPriorityLevel++;
  73006. }
  73007. // Let's the system running for a specific amount of time before checking FPS
  73008. scene.executeWhenReady(function () {
  73009. setTimeout(function () {
  73010. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  73011. }, options.trackerDuration);
  73012. });
  73013. };
  73014. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  73015. if (!options) {
  73016. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  73017. }
  73018. // Let's the system running for a specific amount of time before checking FPS
  73019. scene.executeWhenReady(function () {
  73020. setTimeout(function () {
  73021. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  73022. }, options.trackerDuration);
  73023. });
  73024. };
  73025. return SceneOptimizer;
  73026. }());
  73027. BABYLON.SceneOptimizer = SceneOptimizer;
  73028. })(BABYLON || (BABYLON = {}));
  73029. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  73030. var BABYLON;
  73031. (function (BABYLON) {
  73032. var OutlineRenderer = /** @class */ (function () {
  73033. function OutlineRenderer(scene) {
  73034. this.zOffset = 1;
  73035. this._scene = scene;
  73036. }
  73037. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  73038. var _this = this;
  73039. if (useOverlay === void 0) { useOverlay = false; }
  73040. var scene = this._scene;
  73041. var engine = this._scene.getEngine();
  73042. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  73043. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  73044. return;
  73045. }
  73046. var mesh = subMesh.getRenderingMesh();
  73047. var material = subMesh.getMaterial();
  73048. if (!material || !scene.activeCamera) {
  73049. return;
  73050. }
  73051. engine.enableEffect(this._effect);
  73052. // Logarithmic depth
  73053. if (material.useLogarithmicDepth) {
  73054. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  73055. }
  73056. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  73057. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  73058. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73059. // Bones
  73060. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73061. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73062. }
  73063. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  73064. // Alpha test
  73065. if (material && material.needAlphaTesting()) {
  73066. var alphaTexture = material.getAlphaTestTexture();
  73067. if (alphaTexture) {
  73068. this._effect.setTexture("diffuseSampler", alphaTexture);
  73069. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73070. }
  73071. }
  73072. engine.setZOffset(-this.zOffset);
  73073. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  73074. engine.setZOffset(0);
  73075. };
  73076. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  73077. var defines = [];
  73078. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  73079. var mesh = subMesh.getMesh();
  73080. var material = subMesh.getMaterial();
  73081. if (material) {
  73082. // Alpha test
  73083. if (material.needAlphaTesting()) {
  73084. defines.push("#define ALPHATEST");
  73085. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73086. attribs.push(BABYLON.VertexBuffer.UVKind);
  73087. defines.push("#define UV1");
  73088. }
  73089. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73090. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73091. defines.push("#define UV2");
  73092. }
  73093. }
  73094. //Logarithmic depth
  73095. if (material.useLogarithmicDepth) {
  73096. defines.push("#define LOGARITHMICDEPTH");
  73097. }
  73098. }
  73099. // Bones
  73100. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73101. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73102. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73103. if (mesh.numBoneInfluencers > 4) {
  73104. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73105. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73106. }
  73107. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73108. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73109. }
  73110. else {
  73111. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73112. }
  73113. // Instances
  73114. if (useInstances) {
  73115. defines.push("#define INSTANCES");
  73116. attribs.push("world0");
  73117. attribs.push("world1");
  73118. attribs.push("world2");
  73119. attribs.push("world3");
  73120. }
  73121. // Get correct effect
  73122. var join = defines.join("\n");
  73123. if (this._cachedDefines !== join) {
  73124. this._cachedDefines = join;
  73125. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  73126. }
  73127. return this._effect.isReady();
  73128. };
  73129. return OutlineRenderer;
  73130. }());
  73131. BABYLON.OutlineRenderer = OutlineRenderer;
  73132. })(BABYLON || (BABYLON = {}));
  73133. //# sourceMappingURL=babylon.outlineRenderer.js.map
  73134. var BABYLON;
  73135. (function (BABYLON) {
  73136. var FaceAdjacencies = /** @class */ (function () {
  73137. function FaceAdjacencies() {
  73138. this.edges = new Array();
  73139. this.edgesConnectedCount = 0;
  73140. }
  73141. return FaceAdjacencies;
  73142. }());
  73143. var EdgesRenderer = /** @class */ (function () {
  73144. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  73145. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  73146. if (epsilon === void 0) { epsilon = 0.95; }
  73147. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  73148. this.edgesWidthScalerForOrthographic = 1000.0;
  73149. this.edgesWidthScalerForPerspective = 50.0;
  73150. this._linesPositions = new Array();
  73151. this._linesNormals = new Array();
  73152. this._linesIndices = new Array();
  73153. this._buffers = {};
  73154. this._checkVerticesInsteadOfIndices = false;
  73155. this._source = source;
  73156. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  73157. this._epsilon = epsilon;
  73158. this._prepareRessources();
  73159. this._generateEdgesLines();
  73160. }
  73161. EdgesRenderer.prototype._prepareRessources = function () {
  73162. if (this._lineShader) {
  73163. return;
  73164. }
  73165. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  73166. attributes: ["position", "normal"],
  73167. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  73168. });
  73169. this._lineShader.disableDepthWrite = true;
  73170. this._lineShader.backFaceCulling = false;
  73171. };
  73172. EdgesRenderer.prototype._rebuild = function () {
  73173. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  73174. if (buffer) {
  73175. buffer._rebuild();
  73176. }
  73177. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  73178. if (buffer) {
  73179. buffer._rebuild();
  73180. }
  73181. var scene = this._source.getScene();
  73182. var engine = scene.getEngine();
  73183. this._ib = engine.createIndexBuffer(this._linesIndices);
  73184. };
  73185. EdgesRenderer.prototype.dispose = function () {
  73186. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  73187. if (buffer) {
  73188. buffer.dispose();
  73189. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  73190. }
  73191. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  73192. if (buffer) {
  73193. buffer.dispose();
  73194. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  73195. }
  73196. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  73197. this._lineShader.dispose();
  73198. };
  73199. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  73200. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  73201. return 0;
  73202. }
  73203. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  73204. return 1;
  73205. }
  73206. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  73207. return 2;
  73208. }
  73209. return -1;
  73210. };
  73211. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  73212. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  73213. return 0;
  73214. }
  73215. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  73216. return 1;
  73217. }
  73218. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  73219. return 2;
  73220. }
  73221. return -1;
  73222. };
  73223. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  73224. var needToCreateLine;
  73225. if (edge === undefined) {
  73226. needToCreateLine = true;
  73227. }
  73228. else {
  73229. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  73230. needToCreateLine = dotProduct < this._epsilon;
  73231. }
  73232. if (needToCreateLine) {
  73233. var offset = this._linesPositions.length / 3;
  73234. var normal = p0.subtract(p1);
  73235. normal.normalize();
  73236. // Positions
  73237. this._linesPositions.push(p0.x);
  73238. this._linesPositions.push(p0.y);
  73239. this._linesPositions.push(p0.z);
  73240. this._linesPositions.push(p0.x);
  73241. this._linesPositions.push(p0.y);
  73242. this._linesPositions.push(p0.z);
  73243. this._linesPositions.push(p1.x);
  73244. this._linesPositions.push(p1.y);
  73245. this._linesPositions.push(p1.z);
  73246. this._linesPositions.push(p1.x);
  73247. this._linesPositions.push(p1.y);
  73248. this._linesPositions.push(p1.z);
  73249. // Normals
  73250. this._linesNormals.push(p1.x);
  73251. this._linesNormals.push(p1.y);
  73252. this._linesNormals.push(p1.z);
  73253. this._linesNormals.push(-1);
  73254. this._linesNormals.push(p1.x);
  73255. this._linesNormals.push(p1.y);
  73256. this._linesNormals.push(p1.z);
  73257. this._linesNormals.push(1);
  73258. this._linesNormals.push(p0.x);
  73259. this._linesNormals.push(p0.y);
  73260. this._linesNormals.push(p0.z);
  73261. this._linesNormals.push(-1);
  73262. this._linesNormals.push(p0.x);
  73263. this._linesNormals.push(p0.y);
  73264. this._linesNormals.push(p0.z);
  73265. this._linesNormals.push(1);
  73266. // Indices
  73267. this._linesIndices.push(offset);
  73268. this._linesIndices.push(offset + 1);
  73269. this._linesIndices.push(offset + 2);
  73270. this._linesIndices.push(offset);
  73271. this._linesIndices.push(offset + 2);
  73272. this._linesIndices.push(offset + 3);
  73273. }
  73274. };
  73275. EdgesRenderer.prototype._generateEdgesLines = function () {
  73276. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  73277. var indices = this._source.getIndices();
  73278. if (!indices || !positions) {
  73279. return;
  73280. }
  73281. // First let's find adjacencies
  73282. var adjacencies = new Array();
  73283. var faceNormals = new Array();
  73284. var index;
  73285. var faceAdjacencies;
  73286. // Prepare faces
  73287. for (index = 0; index < indices.length; index += 3) {
  73288. faceAdjacencies = new FaceAdjacencies();
  73289. var p0Index = indices[index];
  73290. var p1Index = indices[index + 1];
  73291. var p2Index = indices[index + 2];
  73292. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  73293. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  73294. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  73295. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  73296. faceNormal.normalize();
  73297. faceNormals.push(faceNormal);
  73298. adjacencies.push(faceAdjacencies);
  73299. }
  73300. // Scan
  73301. for (index = 0; index < adjacencies.length; index++) {
  73302. faceAdjacencies = adjacencies[index];
  73303. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  73304. var otherFaceAdjacencies = adjacencies[otherIndex];
  73305. if (faceAdjacencies.edgesConnectedCount === 3) {
  73306. break;
  73307. }
  73308. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  73309. continue;
  73310. }
  73311. var otherP0 = indices[otherIndex * 3];
  73312. var otherP1 = indices[otherIndex * 3 + 1];
  73313. var otherP2 = indices[otherIndex * 3 + 2];
  73314. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  73315. var otherEdgeIndex = 0;
  73316. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  73317. continue;
  73318. }
  73319. switch (edgeIndex) {
  73320. case 0:
  73321. if (this._checkVerticesInsteadOfIndices) {
  73322. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  73323. }
  73324. else {
  73325. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  73326. }
  73327. break;
  73328. case 1:
  73329. if (this._checkVerticesInsteadOfIndices) {
  73330. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  73331. }
  73332. else {
  73333. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  73334. }
  73335. break;
  73336. case 2:
  73337. if (this._checkVerticesInsteadOfIndices) {
  73338. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  73339. }
  73340. else {
  73341. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  73342. }
  73343. break;
  73344. }
  73345. if (otherEdgeIndex === -1) {
  73346. continue;
  73347. }
  73348. faceAdjacencies.edges[edgeIndex] = otherIndex;
  73349. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  73350. faceAdjacencies.edgesConnectedCount++;
  73351. otherFaceAdjacencies.edgesConnectedCount++;
  73352. if (faceAdjacencies.edgesConnectedCount === 3) {
  73353. break;
  73354. }
  73355. }
  73356. }
  73357. }
  73358. // Create lines
  73359. for (index = 0; index < adjacencies.length; index++) {
  73360. // 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
  73361. var current = adjacencies[index];
  73362. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  73363. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  73364. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  73365. }
  73366. // Merge into a single mesh
  73367. var engine = this._source.getScene().getEngine();
  73368. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  73369. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  73370. this._ib = engine.createIndexBuffer(this._linesIndices);
  73371. this._indicesCount = this._linesIndices.length;
  73372. };
  73373. EdgesRenderer.prototype.render = function () {
  73374. var scene = this._source.getScene();
  73375. if (!this._lineShader.isReady() || !scene.activeCamera) {
  73376. return;
  73377. }
  73378. var engine = scene.getEngine();
  73379. this._lineShader._preBind();
  73380. // VBOs
  73381. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  73382. scene.resetCachedMaterial();
  73383. this._lineShader.setColor4("color", this._source.edgesColor);
  73384. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  73385. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  73386. }
  73387. else {
  73388. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  73389. }
  73390. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  73391. this._lineShader.bind(this._source.getWorldMatrix());
  73392. // Draw order
  73393. engine.draw(true, 0, this._indicesCount);
  73394. this._lineShader.unbind();
  73395. engine.setDepthWrite(true);
  73396. };
  73397. return EdgesRenderer;
  73398. }());
  73399. BABYLON.EdgesRenderer = EdgesRenderer;
  73400. })(BABYLON || (BABYLON = {}));
  73401. //# sourceMappingURL=babylon.edgesRenderer.js.map
  73402. var BABYLON;
  73403. (function (BABYLON) {
  73404. /**
  73405. * Special Glow Blur post process only blurring the alpha channel
  73406. * It enforces keeping the most luminous color in the color channel.
  73407. */
  73408. var GlowBlurPostProcess = /** @class */ (function (_super) {
  73409. __extends(GlowBlurPostProcess, _super);
  73410. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  73411. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73412. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  73413. _this.direction = direction;
  73414. _this.kernel = kernel;
  73415. _this.onApplyObservable.add(function (effect) {
  73416. effect.setFloat2("screenSize", _this.width, _this.height);
  73417. effect.setVector2("direction", _this.direction);
  73418. effect.setFloat("blurWidth", _this.kernel);
  73419. });
  73420. return _this;
  73421. }
  73422. return GlowBlurPostProcess;
  73423. }(BABYLON.PostProcess));
  73424. /**
  73425. * The highlight layer Helps adding a glow effect around a mesh.
  73426. *
  73427. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  73428. * glowy meshes to your scene.
  73429. *
  73430. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  73431. */
  73432. var HighlightLayer = /** @class */ (function () {
  73433. /**
  73434. * Instantiates a new highlight Layer and references it to the scene..
  73435. * @param name The name of the layer
  73436. * @param scene The scene to use the layer in
  73437. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  73438. */
  73439. function HighlightLayer(name, scene, options) {
  73440. this.name = name;
  73441. this._vertexBuffers = {};
  73442. this._mainTextureDesiredSize = { width: 0, height: 0 };
  73443. this._meshes = {};
  73444. this._maxSize = 0;
  73445. this._shouldRender = false;
  73446. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  73447. this._excludedMeshes = {};
  73448. /**
  73449. * Specifies whether or not the inner glow is ACTIVE in the layer.
  73450. */
  73451. this.innerGlow = true;
  73452. /**
  73453. * Specifies whether or not the outer glow is ACTIVE in the layer.
  73454. */
  73455. this.outerGlow = true;
  73456. /**
  73457. * Specifies wether the highlight layer is enabled or not.
  73458. */
  73459. this.isEnabled = true;
  73460. /**
  73461. * An event triggered when the highlight layer has been disposed.
  73462. * @type {BABYLON.Observable}
  73463. */
  73464. this.onDisposeObservable = new BABYLON.Observable();
  73465. /**
  73466. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  73467. * @type {BABYLON.Observable}
  73468. */
  73469. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  73470. /**
  73471. * An event triggered when the highlight layer is being blurred.
  73472. * @type {BABYLON.Observable}
  73473. */
  73474. this.onBeforeBlurObservable = new BABYLON.Observable();
  73475. /**
  73476. * An event triggered when the highlight layer has been blurred.
  73477. * @type {BABYLON.Observable}
  73478. */
  73479. this.onAfterBlurObservable = new BABYLON.Observable();
  73480. /**
  73481. * An event triggered when the glowing blurred texture is being merged in the scene.
  73482. * @type {BABYLON.Observable}
  73483. */
  73484. this.onBeforeComposeObservable = new BABYLON.Observable();
  73485. /**
  73486. * An event triggered when the glowing blurred texture has been merged in the scene.
  73487. * @type {BABYLON.Observable}
  73488. */
  73489. this.onAfterComposeObservable = new BABYLON.Observable();
  73490. /**
  73491. * An event triggered when the highlight layer changes its size.
  73492. * @type {BABYLON.Observable}
  73493. */
  73494. this.onSizeChangedObservable = new BABYLON.Observable();
  73495. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73496. var engine = scene.getEngine();
  73497. this._engine = engine;
  73498. this._maxSize = this._engine.getCaps().maxTextureSize;
  73499. this._scene.highlightLayers.push(this);
  73500. // Warn on stencil.
  73501. if (!this._engine.isStencilEnable) {
  73502. 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 }");
  73503. }
  73504. // Adapt options
  73505. this._options = options || {
  73506. mainTextureRatio: 0.5,
  73507. blurTextureSizeRatio: 0.5,
  73508. blurHorizontalSize: 1.0,
  73509. blurVerticalSize: 1.0,
  73510. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  73511. camera: null
  73512. };
  73513. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  73514. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  73515. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  73516. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  73517. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  73518. // VBO
  73519. var vertices = [];
  73520. vertices.push(1, 1);
  73521. vertices.push(-1, 1);
  73522. vertices.push(-1, -1);
  73523. vertices.push(1, -1);
  73524. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73525. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  73526. this._createIndexBuffer();
  73527. // Effect
  73528. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  73529. // Render target
  73530. this.setMainTextureSize();
  73531. // Create Textures and post processes
  73532. this.createTextureAndPostProcesses();
  73533. }
  73534. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  73535. /**
  73536. * Gets the horizontal size of the blur.
  73537. */
  73538. get: function () {
  73539. return this._horizontalBlurPostprocess.kernel;
  73540. },
  73541. /**
  73542. * Specifies the horizontal size of the blur.
  73543. */
  73544. set: function (value) {
  73545. this._horizontalBlurPostprocess.kernel = value;
  73546. },
  73547. enumerable: true,
  73548. configurable: true
  73549. });
  73550. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  73551. /**
  73552. * Gets the vertical size of the blur.
  73553. */
  73554. get: function () {
  73555. return this._verticalBlurPostprocess.kernel;
  73556. },
  73557. /**
  73558. * Specifies the vertical size of the blur.
  73559. */
  73560. set: function (value) {
  73561. this._verticalBlurPostprocess.kernel = value;
  73562. },
  73563. enumerable: true,
  73564. configurable: true
  73565. });
  73566. Object.defineProperty(HighlightLayer.prototype, "camera", {
  73567. /**
  73568. * Gets the camera attached to the layer.
  73569. */
  73570. get: function () {
  73571. return this._options.camera;
  73572. },
  73573. enumerable: true,
  73574. configurable: true
  73575. });
  73576. HighlightLayer.prototype._createIndexBuffer = function () {
  73577. var engine = this._scene.getEngine();
  73578. // Indices
  73579. var indices = [];
  73580. indices.push(0);
  73581. indices.push(1);
  73582. indices.push(2);
  73583. indices.push(0);
  73584. indices.push(2);
  73585. indices.push(3);
  73586. this._indexBuffer = engine.createIndexBuffer(indices);
  73587. };
  73588. HighlightLayer.prototype._rebuild = function () {
  73589. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73590. if (vb) {
  73591. vb._rebuild();
  73592. }
  73593. this._createIndexBuffer();
  73594. };
  73595. /**
  73596. * Creates the render target textures and post processes used in the highlight layer.
  73597. */
  73598. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  73599. var _this = this;
  73600. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  73601. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  73602. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  73603. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  73604. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  73605. width: this._mainTextureDesiredSize.width,
  73606. height: this._mainTextureDesiredSize.height
  73607. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73608. this._mainTexture.activeCamera = this._options.camera;
  73609. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73610. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73611. this._mainTexture.anisotropicFilteringLevel = 1;
  73612. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73613. this._mainTexture.renderParticles = false;
  73614. this._mainTexture.renderList = null;
  73615. this._mainTexture.ignoreCameraViewport = true;
  73616. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  73617. width: blurTextureWidth,
  73618. height: blurTextureHeight
  73619. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73620. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73621. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73622. this._blurTexture.anisotropicFilteringLevel = 16;
  73623. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73624. this._blurTexture.renderParticles = false;
  73625. this._blurTexture.ignoreCameraViewport = true;
  73626. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  73627. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  73628. effect.setTexture("textureSampler", _this._mainTexture);
  73629. });
  73630. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  73631. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  73632. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  73633. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  73634. });
  73635. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  73636. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  73637. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  73638. });
  73639. }
  73640. else {
  73641. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  73642. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  73643. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  73644. });
  73645. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  73646. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  73647. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  73648. });
  73649. }
  73650. this._mainTexture.onAfterUnbindObservable.add(function () {
  73651. _this.onBeforeBlurObservable.notifyObservers(_this);
  73652. var internalTexture = _this._blurTexture.getInternalTexture();
  73653. if (internalTexture) {
  73654. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  73655. }
  73656. _this.onAfterBlurObservable.notifyObservers(_this);
  73657. });
  73658. // Custom render function
  73659. var renderSubMesh = function (subMesh) {
  73660. if (!_this._meshes) {
  73661. return;
  73662. }
  73663. var material = subMesh.getMaterial();
  73664. var mesh = subMesh.getRenderingMesh();
  73665. var scene = _this._scene;
  73666. var engine = scene.getEngine();
  73667. if (!material) {
  73668. return;
  73669. }
  73670. // Culling
  73671. engine.setState(material.backFaceCulling);
  73672. // Managing instances
  73673. var batch = mesh._getInstancesRenderList(subMesh._id);
  73674. if (batch.mustReturn) {
  73675. return;
  73676. }
  73677. // Excluded Mesh
  73678. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  73679. return;
  73680. }
  73681. ;
  73682. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  73683. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  73684. var emissiveTexture = null;
  73685. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  73686. emissiveTexture = material.emissiveTexture;
  73687. }
  73688. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  73689. engine.enableEffect(_this._glowMapGenerationEffect);
  73690. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  73691. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  73692. if (highlightLayerMesh) {
  73693. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  73694. }
  73695. else {
  73696. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  73697. }
  73698. // Alpha test
  73699. if (material && material.needAlphaTesting()) {
  73700. var alphaTexture = material.getAlphaTestTexture();
  73701. if (alphaTexture) {
  73702. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  73703. var textureMatrix = alphaTexture.getTextureMatrix();
  73704. if (textureMatrix) {
  73705. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  73706. }
  73707. }
  73708. }
  73709. // Glow emissive only
  73710. if (emissiveTexture) {
  73711. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  73712. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  73713. }
  73714. // Bones
  73715. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73716. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73717. }
  73718. // Draw
  73719. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  73720. }
  73721. else {
  73722. // Need to reset refresh rate of the shadowMap
  73723. _this._mainTexture.resetRefreshCounter();
  73724. }
  73725. };
  73726. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73727. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  73728. var index;
  73729. var engine = _this._scene.getEngine();
  73730. if (depthOnlySubMeshes.length) {
  73731. engine.setColorWrite(false);
  73732. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73733. renderSubMesh(depthOnlySubMeshes.data[index]);
  73734. }
  73735. engine.setColorWrite(true);
  73736. }
  73737. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73738. renderSubMesh(opaqueSubMeshes.data[index]);
  73739. }
  73740. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73741. renderSubMesh(alphaTestSubMeshes.data[index]);
  73742. }
  73743. for (index = 0; index < transparentSubMeshes.length; index++) {
  73744. renderSubMesh(transparentSubMeshes.data[index]);
  73745. }
  73746. };
  73747. this._mainTexture.onClearObservable.add(function (engine) {
  73748. engine.clear(HighlightLayer.neutralColor, true, true, true);
  73749. });
  73750. };
  73751. /**
  73752. * Checks for the readiness of the element composing the layer.
  73753. * @param subMesh the mesh to check for
  73754. * @param useInstances specify wether or not to use instances to render the mesh
  73755. * @param emissiveTexture the associated emissive texture used to generate the glow
  73756. * @return true if ready otherwise, false
  73757. */
  73758. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  73759. var material = subMesh.getMaterial();
  73760. if (!material) {
  73761. return false;
  73762. }
  73763. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  73764. return false;
  73765. }
  73766. var defines = [];
  73767. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73768. var mesh = subMesh.getMesh();
  73769. var uv1 = false;
  73770. var uv2 = false;
  73771. // Alpha test
  73772. if (material && material.needAlphaTesting()) {
  73773. var alphaTexture = material.getAlphaTestTexture();
  73774. if (alphaTexture) {
  73775. defines.push("#define ALPHATEST");
  73776. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  73777. alphaTexture.coordinatesIndex === 1) {
  73778. defines.push("#define DIFFUSEUV2");
  73779. uv2 = true;
  73780. }
  73781. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73782. defines.push("#define DIFFUSEUV1");
  73783. uv1 = true;
  73784. }
  73785. }
  73786. }
  73787. // Emissive
  73788. if (emissiveTexture) {
  73789. defines.push("#define EMISSIVE");
  73790. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  73791. emissiveTexture.coordinatesIndex === 1) {
  73792. defines.push("#define EMISSIVEUV2");
  73793. uv2 = true;
  73794. }
  73795. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73796. defines.push("#define EMISSIVEUV1");
  73797. uv1 = true;
  73798. }
  73799. }
  73800. if (uv1) {
  73801. attribs.push(BABYLON.VertexBuffer.UVKind);
  73802. defines.push("#define UV1");
  73803. }
  73804. if (uv2) {
  73805. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73806. defines.push("#define UV2");
  73807. }
  73808. // Bones
  73809. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73810. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73811. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73812. if (mesh.numBoneInfluencers > 4) {
  73813. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73814. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73815. }
  73816. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73817. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  73818. }
  73819. else {
  73820. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73821. }
  73822. // Instances
  73823. if (useInstances) {
  73824. defines.push("#define INSTANCES");
  73825. attribs.push("world0");
  73826. attribs.push("world1");
  73827. attribs.push("world2");
  73828. attribs.push("world3");
  73829. }
  73830. // Get correct effect
  73831. var join = defines.join("\n");
  73832. if (this._cachedDefines !== join) {
  73833. this._cachedDefines = join;
  73834. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  73835. }
  73836. return this._glowMapGenerationEffect.isReady();
  73837. };
  73838. /**
  73839. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  73840. */
  73841. HighlightLayer.prototype.render = function () {
  73842. var currentEffect = this._glowMapMergeEffect;
  73843. // Check
  73844. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  73845. return;
  73846. var engine = this._scene.getEngine();
  73847. this.onBeforeComposeObservable.notifyObservers(this);
  73848. // Render
  73849. engine.enableEffect(currentEffect);
  73850. engine.setState(false);
  73851. // Cache
  73852. var previousStencilBuffer = engine.getStencilBuffer();
  73853. var previousStencilFunction = engine.getStencilFunction();
  73854. var previousStencilMask = engine.getStencilMask();
  73855. var previousStencilOperationPass = engine.getStencilOperationPass();
  73856. var previousStencilOperationFail = engine.getStencilOperationFail();
  73857. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  73858. var previousAlphaMode = engine.getAlphaMode();
  73859. // Texture
  73860. currentEffect.setTexture("textureSampler", this._blurTexture);
  73861. // VBOs
  73862. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  73863. // Stencil operations
  73864. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  73865. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  73866. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  73867. // Draw order
  73868. engine.setAlphaMode(this._options.alphaBlendingMode);
  73869. engine.setStencilMask(0x00);
  73870. engine.setStencilBuffer(true);
  73871. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  73872. if (this.outerGlow) {
  73873. currentEffect.setFloat("offset", 0);
  73874. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  73875. engine.draw(true, 0, 6);
  73876. }
  73877. if (this.innerGlow) {
  73878. currentEffect.setFloat("offset", 1);
  73879. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  73880. engine.draw(true, 0, 6);
  73881. }
  73882. // Restore Cache
  73883. engine.setStencilFunction(previousStencilFunction);
  73884. engine.setStencilMask(previousStencilMask);
  73885. engine.setAlphaMode(previousAlphaMode);
  73886. engine.setStencilBuffer(previousStencilBuffer);
  73887. engine.setStencilOperationPass(previousStencilOperationPass);
  73888. engine.setStencilOperationFail(previousStencilOperationFail);
  73889. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  73890. engine._stencilState.reset();
  73891. this.onAfterComposeObservable.notifyObservers(this);
  73892. // Handle size changes.
  73893. var size = this._mainTexture.getSize();
  73894. this.setMainTextureSize();
  73895. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  73896. // Recreate RTT and post processes on size change.
  73897. this.onSizeChangedObservable.notifyObservers(this);
  73898. this.disposeTextureAndPostProcesses();
  73899. this.createTextureAndPostProcesses();
  73900. }
  73901. };
  73902. /**
  73903. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  73904. * @param mesh The mesh to exclude from the highlight layer
  73905. */
  73906. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  73907. if (!this._excludedMeshes) {
  73908. return;
  73909. }
  73910. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  73911. if (!meshExcluded) {
  73912. this._excludedMeshes[mesh.uniqueId] = {
  73913. mesh: mesh,
  73914. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  73915. mesh.getEngine().setStencilBuffer(false);
  73916. }),
  73917. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  73918. mesh.getEngine().setStencilBuffer(true);
  73919. }),
  73920. };
  73921. }
  73922. };
  73923. /**
  73924. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  73925. * @param mesh The mesh to highlight
  73926. */
  73927. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  73928. if (!this._excludedMeshes) {
  73929. return;
  73930. }
  73931. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  73932. if (meshExcluded) {
  73933. if (meshExcluded.beforeRender) {
  73934. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  73935. }
  73936. if (meshExcluded.afterRender) {
  73937. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  73938. }
  73939. }
  73940. this._excludedMeshes[mesh.uniqueId] = null;
  73941. };
  73942. /**
  73943. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  73944. * @param mesh The mesh to highlight
  73945. * @param color The color of the highlight
  73946. * @param glowEmissiveOnly Extract the glow from the emissive texture
  73947. */
  73948. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  73949. var _this = this;
  73950. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  73951. if (!this._meshes) {
  73952. return;
  73953. }
  73954. var meshHighlight = this._meshes[mesh.uniqueId];
  73955. if (meshHighlight) {
  73956. meshHighlight.color = color;
  73957. }
  73958. else {
  73959. this._meshes[mesh.uniqueId] = {
  73960. mesh: mesh,
  73961. color: color,
  73962. // Lambda required for capture due to Observable this context
  73963. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  73964. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  73965. _this.defaultStencilReference(mesh);
  73966. }
  73967. else {
  73968. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  73969. }
  73970. }),
  73971. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  73972. glowEmissiveOnly: glowEmissiveOnly
  73973. };
  73974. }
  73975. this._shouldRender = true;
  73976. };
  73977. /**
  73978. * Remove a mesh from the highlight layer in order to make it stop glowing.
  73979. * @param mesh The mesh to highlight
  73980. */
  73981. HighlightLayer.prototype.removeMesh = function (mesh) {
  73982. if (!this._meshes) {
  73983. return;
  73984. }
  73985. var meshHighlight = this._meshes[mesh.uniqueId];
  73986. if (meshHighlight) {
  73987. if (meshHighlight.observerHighlight) {
  73988. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  73989. }
  73990. if (meshHighlight.observerDefault) {
  73991. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  73992. }
  73993. }
  73994. this._meshes[mesh.uniqueId] = null;
  73995. this._shouldRender = false;
  73996. for (var meshHighlightToCheck in this._meshes) {
  73997. if (meshHighlightToCheck) {
  73998. this._shouldRender = true;
  73999. break;
  74000. }
  74001. }
  74002. };
  74003. /**
  74004. * Returns true if the layer contains information to display, otherwise false.
  74005. */
  74006. HighlightLayer.prototype.shouldRender = function () {
  74007. return this.isEnabled && this._shouldRender;
  74008. };
  74009. /**
  74010. * Sets the main texture desired size which is the closest power of two
  74011. * of the engine canvas size.
  74012. */
  74013. HighlightLayer.prototype.setMainTextureSize = function () {
  74014. if (this._options.mainTextureFixedSize) {
  74015. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  74016. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  74017. }
  74018. else {
  74019. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  74020. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  74021. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  74022. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  74023. }
  74024. };
  74025. /**
  74026. * Force the stencil to the normal expected value for none glowing parts
  74027. */
  74028. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  74029. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  74030. };
  74031. /**
  74032. * Dispose only the render target textures and post process.
  74033. */
  74034. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  74035. this._blurTexture.dispose();
  74036. this._mainTexture.dispose();
  74037. this._downSamplePostprocess.dispose();
  74038. this._horizontalBlurPostprocess.dispose();
  74039. this._verticalBlurPostprocess.dispose();
  74040. };
  74041. /**
  74042. * Dispose the highlight layer and free resources.
  74043. */
  74044. HighlightLayer.prototype.dispose = function () {
  74045. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74046. if (vertexBuffer) {
  74047. vertexBuffer.dispose();
  74048. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74049. }
  74050. if (this._indexBuffer) {
  74051. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74052. this._indexBuffer = null;
  74053. }
  74054. // Clean textures and post processes
  74055. this.disposeTextureAndPostProcesses();
  74056. if (this._meshes) {
  74057. // Clean mesh references
  74058. for (var id in this._meshes) {
  74059. var meshHighlight = this._meshes[id];
  74060. if (meshHighlight && meshHighlight.mesh) {
  74061. if (meshHighlight.observerHighlight) {
  74062. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  74063. }
  74064. if (meshHighlight.observerDefault) {
  74065. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  74066. }
  74067. }
  74068. }
  74069. this._meshes = null;
  74070. }
  74071. if (this._excludedMeshes) {
  74072. for (var id in this._excludedMeshes) {
  74073. var meshHighlight = this._excludedMeshes[id];
  74074. if (meshHighlight) {
  74075. if (meshHighlight.beforeRender) {
  74076. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  74077. }
  74078. if (meshHighlight.afterRender) {
  74079. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  74080. }
  74081. }
  74082. }
  74083. this._excludedMeshes = null;
  74084. }
  74085. // Remove from scene
  74086. var index = this._scene.highlightLayers.indexOf(this, 0);
  74087. if (index > -1) {
  74088. this._scene.highlightLayers.splice(index, 1);
  74089. }
  74090. // Callback
  74091. this.onDisposeObservable.notifyObservers(this);
  74092. this.onDisposeObservable.clear();
  74093. this.onBeforeRenderMainTextureObservable.clear();
  74094. this.onBeforeBlurObservable.clear();
  74095. this.onBeforeComposeObservable.clear();
  74096. this.onAfterComposeObservable.clear();
  74097. this.onSizeChangedObservable.clear();
  74098. };
  74099. /**
  74100. * The neutral color used during the preparation of the glow effect.
  74101. * This is black by default as the blend operation is a blend operation.
  74102. */
  74103. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  74104. /**
  74105. * Stencil value used for glowing meshes.
  74106. */
  74107. HighlightLayer.glowingMeshStencilReference = 0x02;
  74108. /**
  74109. * Stencil value used for the other meshes in the scene.
  74110. */
  74111. HighlightLayer.normalMeshStencilReference = 0x01;
  74112. return HighlightLayer;
  74113. }());
  74114. BABYLON.HighlightLayer = HighlightLayer;
  74115. })(BABYLON || (BABYLON = {}));
  74116. //# sourceMappingURL=babylon.highlightlayer.js.map
  74117. var BABYLON;
  74118. (function (BABYLON) {
  74119. var AssetTaskState;
  74120. (function (AssetTaskState) {
  74121. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  74122. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  74123. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  74124. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  74125. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  74126. var AbstractAssetTask = /** @class */ (function () {
  74127. function AbstractAssetTask(name) {
  74128. this.name = name;
  74129. this.isCompleted = false;
  74130. this.taskState = AssetTaskState.INIT;
  74131. }
  74132. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  74133. var _this = this;
  74134. this.taskState = AssetTaskState.RUNNING;
  74135. this.runTask(scene, function () {
  74136. _this.onDoneCallback(onSuccess, onError);
  74137. }, function (msg, exception) {
  74138. _this.onErrorCallback(onError, msg, exception);
  74139. });
  74140. };
  74141. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74142. throw new Error("runTask is not implemented");
  74143. };
  74144. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  74145. this.taskState = AssetTaskState.ERROR;
  74146. this.errorObject = {
  74147. message: message,
  74148. exception: exception
  74149. };
  74150. if (this.onError) {
  74151. this.onError(this, message, exception);
  74152. }
  74153. onError();
  74154. };
  74155. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  74156. try {
  74157. this.taskState = AssetTaskState.DONE;
  74158. this.isCompleted = true;
  74159. if (this.onSuccess) {
  74160. this.onSuccess(this);
  74161. }
  74162. onSuccess();
  74163. }
  74164. catch (e) {
  74165. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  74166. }
  74167. };
  74168. return AbstractAssetTask;
  74169. }());
  74170. BABYLON.AbstractAssetTask = AbstractAssetTask;
  74171. var AssetsProgressEvent = /** @class */ (function () {
  74172. function AssetsProgressEvent(remainingCount, totalCount, task) {
  74173. this.remainingCount = remainingCount;
  74174. this.totalCount = totalCount;
  74175. this.task = task;
  74176. }
  74177. return AssetsProgressEvent;
  74178. }());
  74179. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  74180. var MeshAssetTask = /** @class */ (function (_super) {
  74181. __extends(MeshAssetTask, _super);
  74182. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  74183. var _this = _super.call(this, name) || this;
  74184. _this.name = name;
  74185. _this.meshesNames = meshesNames;
  74186. _this.rootUrl = rootUrl;
  74187. _this.sceneFilename = sceneFilename;
  74188. return _this;
  74189. }
  74190. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74191. var _this = this;
  74192. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  74193. _this.loadedMeshes = meshes;
  74194. _this.loadedParticleSystems = particleSystems;
  74195. _this.loadedSkeletons = skeletons;
  74196. onSuccess();
  74197. }, null, function (scene, message, exception) {
  74198. onError(message, exception);
  74199. });
  74200. };
  74201. return MeshAssetTask;
  74202. }(AbstractAssetTask));
  74203. BABYLON.MeshAssetTask = MeshAssetTask;
  74204. var TextFileAssetTask = /** @class */ (function (_super) {
  74205. __extends(TextFileAssetTask, _super);
  74206. function TextFileAssetTask(name, url) {
  74207. var _this = _super.call(this, name) || this;
  74208. _this.name = name;
  74209. _this.url = url;
  74210. return _this;
  74211. }
  74212. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74213. var _this = this;
  74214. BABYLON.Tools.LoadFile(this.url, function (data) {
  74215. _this.text = data;
  74216. onSuccess();
  74217. }, undefined, scene.database, false, function (request, exception) {
  74218. if (request) {
  74219. onError(request.status + " " + request.statusText, exception);
  74220. }
  74221. });
  74222. };
  74223. return TextFileAssetTask;
  74224. }(AbstractAssetTask));
  74225. BABYLON.TextFileAssetTask = TextFileAssetTask;
  74226. var BinaryFileAssetTask = /** @class */ (function (_super) {
  74227. __extends(BinaryFileAssetTask, _super);
  74228. function BinaryFileAssetTask(name, url) {
  74229. var _this = _super.call(this, name) || this;
  74230. _this.name = name;
  74231. _this.url = url;
  74232. return _this;
  74233. }
  74234. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74235. var _this = this;
  74236. BABYLON.Tools.LoadFile(this.url, function (data) {
  74237. _this.data = data;
  74238. onSuccess();
  74239. }, undefined, scene.database, true, function (request, exception) {
  74240. if (request) {
  74241. onError(request.status + " " + request.statusText, exception);
  74242. }
  74243. });
  74244. };
  74245. return BinaryFileAssetTask;
  74246. }(AbstractAssetTask));
  74247. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  74248. var ImageAssetTask = /** @class */ (function (_super) {
  74249. __extends(ImageAssetTask, _super);
  74250. function ImageAssetTask(name, url) {
  74251. var _this = _super.call(this, name) || this;
  74252. _this.name = name;
  74253. _this.url = url;
  74254. return _this;
  74255. }
  74256. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74257. var _this = this;
  74258. var img = new Image();
  74259. BABYLON.Tools.SetCorsBehavior(this.url, img);
  74260. img.onload = function () {
  74261. _this.image = img;
  74262. onSuccess();
  74263. };
  74264. img.onerror = function (err) {
  74265. onError("Error loading image", err);
  74266. };
  74267. img.src = this.url;
  74268. };
  74269. return ImageAssetTask;
  74270. }(AbstractAssetTask));
  74271. BABYLON.ImageAssetTask = ImageAssetTask;
  74272. var TextureAssetTask = /** @class */ (function (_super) {
  74273. __extends(TextureAssetTask, _super);
  74274. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  74275. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74276. var _this = _super.call(this, name) || this;
  74277. _this.name = name;
  74278. _this.url = url;
  74279. _this.noMipmap = noMipmap;
  74280. _this.invertY = invertY;
  74281. _this.samplingMode = samplingMode;
  74282. return _this;
  74283. }
  74284. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74285. var onload = function () {
  74286. onSuccess();
  74287. };
  74288. var onerror = function (message, exception) {
  74289. onError(message, exception);
  74290. };
  74291. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  74292. };
  74293. return TextureAssetTask;
  74294. }(AbstractAssetTask));
  74295. BABYLON.TextureAssetTask = TextureAssetTask;
  74296. var CubeTextureAssetTask = /** @class */ (function (_super) {
  74297. __extends(CubeTextureAssetTask, _super);
  74298. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  74299. var _this = _super.call(this, name) || this;
  74300. _this.name = name;
  74301. _this.url = url;
  74302. _this.extensions = extensions;
  74303. _this.noMipmap = noMipmap;
  74304. _this.files = files;
  74305. return _this;
  74306. }
  74307. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74308. var onload = function () {
  74309. onSuccess();
  74310. };
  74311. var onerror = function (message, exception) {
  74312. onError(message, exception);
  74313. };
  74314. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  74315. };
  74316. return CubeTextureAssetTask;
  74317. }(AbstractAssetTask));
  74318. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  74319. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  74320. __extends(HDRCubeTextureAssetTask, _super);
  74321. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  74322. if (noMipmap === void 0) { noMipmap = false; }
  74323. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74324. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74325. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74326. var _this = _super.call(this, name) || this;
  74327. _this.name = name;
  74328. _this.url = url;
  74329. _this.size = size;
  74330. _this.noMipmap = noMipmap;
  74331. _this.generateHarmonics = generateHarmonics;
  74332. _this.useInGammaSpace = useInGammaSpace;
  74333. _this.usePMREMGenerator = usePMREMGenerator;
  74334. return _this;
  74335. }
  74336. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  74337. var onload = function () {
  74338. onSuccess();
  74339. };
  74340. var onerror = function (message, exception) {
  74341. onError(message, exception);
  74342. };
  74343. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  74344. };
  74345. return HDRCubeTextureAssetTask;
  74346. }(AbstractAssetTask));
  74347. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  74348. var AssetsManager = /** @class */ (function () {
  74349. function AssetsManager(scene) {
  74350. this.tasks = new Array();
  74351. this.waitingTasksCount = 0;
  74352. //Observables
  74353. this.onTaskSuccessObservable = new BABYLON.Observable();
  74354. this.onTaskErrorObservable = new BABYLON.Observable();
  74355. this.onTasksDoneObservable = new BABYLON.Observable();
  74356. this.onProgressObservable = new BABYLON.Observable();
  74357. this.useDefaultLoadingScreen = true;
  74358. this._scene = scene;
  74359. }
  74360. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  74361. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  74362. this.tasks.push(task);
  74363. return task;
  74364. };
  74365. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  74366. var task = new TextFileAssetTask(taskName, url);
  74367. this.tasks.push(task);
  74368. return task;
  74369. };
  74370. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  74371. var task = new BinaryFileAssetTask(taskName, url);
  74372. this.tasks.push(task);
  74373. return task;
  74374. };
  74375. AssetsManager.prototype.addImageTask = function (taskName, url) {
  74376. var task = new ImageAssetTask(taskName, url);
  74377. this.tasks.push(task);
  74378. return task;
  74379. };
  74380. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  74381. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74382. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  74383. this.tasks.push(task);
  74384. return task;
  74385. };
  74386. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  74387. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  74388. this.tasks.push(task);
  74389. return task;
  74390. };
  74391. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  74392. if (noMipmap === void 0) { noMipmap = false; }
  74393. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74394. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74395. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74396. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  74397. this.tasks.push(task);
  74398. return task;
  74399. };
  74400. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  74401. this.waitingTasksCount--;
  74402. try {
  74403. if (this.onProgress) {
  74404. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  74405. }
  74406. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  74407. }
  74408. catch (e) {
  74409. BABYLON.Tools.Error("Error running progress callbacks.");
  74410. console.log(e);
  74411. }
  74412. if (this.waitingTasksCount === 0) {
  74413. try {
  74414. if (this.onFinish) {
  74415. this.onFinish(this.tasks);
  74416. }
  74417. this.onTasksDoneObservable.notifyObservers(this.tasks);
  74418. }
  74419. catch (e) {
  74420. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  74421. console.log(e);
  74422. }
  74423. this._scene.getEngine().hideLoadingUI();
  74424. }
  74425. };
  74426. AssetsManager.prototype._runTask = function (task) {
  74427. var _this = this;
  74428. var done = function () {
  74429. try {
  74430. if (_this.onTaskSuccess) {
  74431. _this.onTaskSuccess(task);
  74432. }
  74433. _this.onTaskSuccessObservable.notifyObservers(task);
  74434. _this._decreaseWaitingTasksCount(task);
  74435. }
  74436. catch (e) {
  74437. error("Error executing task success callbacks", e);
  74438. }
  74439. };
  74440. var error = function (message, exception) {
  74441. task.errorObject = task.errorObject || {
  74442. message: message,
  74443. exception: exception
  74444. };
  74445. if (_this.onTaskError) {
  74446. _this.onTaskError(task);
  74447. }
  74448. _this.onTaskErrorObservable.notifyObservers(task);
  74449. _this._decreaseWaitingTasksCount(task);
  74450. };
  74451. task.run(this._scene, done, error);
  74452. };
  74453. AssetsManager.prototype.reset = function () {
  74454. this.tasks = new Array();
  74455. return this;
  74456. };
  74457. AssetsManager.prototype.load = function () {
  74458. this.waitingTasksCount = this.tasks.length;
  74459. if (this.waitingTasksCount === 0) {
  74460. if (this.onFinish) {
  74461. this.onFinish(this.tasks);
  74462. }
  74463. this.onTasksDoneObservable.notifyObservers(this.tasks);
  74464. return this;
  74465. }
  74466. if (this.useDefaultLoadingScreen) {
  74467. this._scene.getEngine().displayLoadingUI();
  74468. }
  74469. for (var index = 0; index < this.tasks.length; index++) {
  74470. var task = this.tasks[index];
  74471. this._runTask(task);
  74472. }
  74473. return this;
  74474. };
  74475. return AssetsManager;
  74476. }());
  74477. BABYLON.AssetsManager = AssetsManager;
  74478. })(BABYLON || (BABYLON = {}));
  74479. //# sourceMappingURL=babylon.assetsManager.js.map
  74480. var BABYLON;
  74481. (function (BABYLON) {
  74482. var serializedGeometries = [];
  74483. var serializeGeometry = function (geometry, serializationGeometries) {
  74484. if (serializedGeometries[geometry.id]) {
  74485. return;
  74486. }
  74487. if (geometry.doNotSerialize) {
  74488. return;
  74489. }
  74490. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  74491. serializationGeometries.boxes.push(geometry.serialize());
  74492. }
  74493. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  74494. serializationGeometries.spheres.push(geometry.serialize());
  74495. }
  74496. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  74497. serializationGeometries.cylinders.push(geometry.serialize());
  74498. }
  74499. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  74500. serializationGeometries.toruses.push(geometry.serialize());
  74501. }
  74502. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  74503. serializationGeometries.grounds.push(geometry.serialize());
  74504. }
  74505. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  74506. serializationGeometries.planes.push(geometry.serialize());
  74507. }
  74508. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  74509. serializationGeometries.torusKnots.push(geometry.serialize());
  74510. }
  74511. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  74512. throw new Error("Unknown primitive type");
  74513. }
  74514. else {
  74515. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  74516. }
  74517. serializedGeometries[geometry.id] = true;
  74518. };
  74519. var serializeMesh = function (mesh, serializationScene) {
  74520. var serializationObject = {};
  74521. // Geometry
  74522. var geometry = mesh._geometry;
  74523. if (geometry) {
  74524. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  74525. // 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
  74526. serializeGeometry(geometry, serializationScene.geometries);
  74527. }
  74528. }
  74529. // Custom
  74530. if (mesh.serialize) {
  74531. mesh.serialize(serializationObject);
  74532. }
  74533. return serializationObject;
  74534. };
  74535. var finalizeSingleMesh = function (mesh, serializationObject) {
  74536. //only works if the mesh is already loaded
  74537. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  74538. //serialize material
  74539. if (mesh.material) {
  74540. if (mesh.material instanceof BABYLON.StandardMaterial) {
  74541. serializationObject.materials = serializationObject.materials || [];
  74542. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  74543. serializationObject.materials.push(mesh.material.serialize());
  74544. }
  74545. }
  74546. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  74547. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  74548. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  74549. serializationObject.multiMaterials.push(mesh.material.serialize());
  74550. }
  74551. }
  74552. }
  74553. //serialize geometry
  74554. var geometry = mesh._geometry;
  74555. if (geometry) {
  74556. if (!serializationObject.geometries) {
  74557. serializationObject.geometries = {};
  74558. serializationObject.geometries.boxes = [];
  74559. serializationObject.geometries.spheres = [];
  74560. serializationObject.geometries.cylinders = [];
  74561. serializationObject.geometries.toruses = [];
  74562. serializationObject.geometries.grounds = [];
  74563. serializationObject.geometries.planes = [];
  74564. serializationObject.geometries.torusKnots = [];
  74565. serializationObject.geometries.vertexData = [];
  74566. }
  74567. serializeGeometry(geometry, serializationObject.geometries);
  74568. }
  74569. // Skeletons
  74570. if (mesh.skeleton) {
  74571. serializationObject.skeletons = serializationObject.skeletons || [];
  74572. serializationObject.skeletons.push(mesh.skeleton.serialize());
  74573. }
  74574. //serialize the actual mesh
  74575. serializationObject.meshes = serializationObject.meshes || [];
  74576. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  74577. }
  74578. };
  74579. var SceneSerializer = /** @class */ (function () {
  74580. function SceneSerializer() {
  74581. }
  74582. SceneSerializer.ClearCache = function () {
  74583. serializedGeometries = [];
  74584. };
  74585. SceneSerializer.Serialize = function (scene) {
  74586. var serializationObject = {};
  74587. SceneSerializer.ClearCache();
  74588. // Scene
  74589. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  74590. serializationObject.autoClear = scene.autoClear;
  74591. serializationObject.clearColor = scene.clearColor.asArray();
  74592. serializationObject.ambientColor = scene.ambientColor.asArray();
  74593. serializationObject.gravity = scene.gravity.asArray();
  74594. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  74595. serializationObject.workerCollisions = scene.workerCollisions;
  74596. // Fog
  74597. if (scene.fogMode && scene.fogMode !== 0) {
  74598. serializationObject.fogMode = scene.fogMode;
  74599. serializationObject.fogColor = scene.fogColor.asArray();
  74600. serializationObject.fogStart = scene.fogStart;
  74601. serializationObject.fogEnd = scene.fogEnd;
  74602. serializationObject.fogDensity = scene.fogDensity;
  74603. }
  74604. //Physics
  74605. if (scene.isPhysicsEnabled()) {
  74606. var physicEngine = scene.getPhysicsEngine();
  74607. if (physicEngine) {
  74608. serializationObject.physicsEnabled = true;
  74609. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  74610. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  74611. }
  74612. }
  74613. // Metadata
  74614. if (scene.metadata) {
  74615. serializationObject.metadata = scene.metadata;
  74616. }
  74617. // Morph targets
  74618. serializationObject.morphTargetManagers = [];
  74619. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  74620. var abstractMesh = _a[_i];
  74621. var manager = abstractMesh.morphTargetManager;
  74622. if (manager) {
  74623. serializationObject.morphTargetManagers.push(manager.serialize());
  74624. }
  74625. }
  74626. // Lights
  74627. serializationObject.lights = [];
  74628. var index;
  74629. var light;
  74630. for (index = 0; index < scene.lights.length; index++) {
  74631. light = scene.lights[index];
  74632. if (!light.doNotSerialize) {
  74633. serializationObject.lights.push(light.serialize());
  74634. }
  74635. }
  74636. // Cameras
  74637. serializationObject.cameras = [];
  74638. for (index = 0; index < scene.cameras.length; index++) {
  74639. var camera = scene.cameras[index];
  74640. if (!camera.doNotSerialize) {
  74641. serializationObject.cameras.push(camera.serialize());
  74642. }
  74643. }
  74644. if (scene.activeCamera) {
  74645. serializationObject.activeCameraID = scene.activeCamera.id;
  74646. }
  74647. // Animations
  74648. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  74649. // Materials
  74650. serializationObject.materials = [];
  74651. serializationObject.multiMaterials = [];
  74652. var material;
  74653. for (index = 0; index < scene.materials.length; index++) {
  74654. material = scene.materials[index];
  74655. if (!material.doNotSerialize) {
  74656. serializationObject.materials.push(material.serialize());
  74657. }
  74658. }
  74659. // MultiMaterials
  74660. serializationObject.multiMaterials = [];
  74661. for (index = 0; index < scene.multiMaterials.length; index++) {
  74662. var multiMaterial = scene.multiMaterials[index];
  74663. serializationObject.multiMaterials.push(multiMaterial.serialize());
  74664. }
  74665. // Skeletons
  74666. serializationObject.skeletons = [];
  74667. for (index = 0; index < scene.skeletons.length; index++) {
  74668. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  74669. }
  74670. // Transform nodes
  74671. serializationObject.transformNodes = [];
  74672. for (index = 0; index < scene.transformNodes.length; index++) {
  74673. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  74674. }
  74675. // Geometries
  74676. serializationObject.geometries = {};
  74677. serializationObject.geometries.boxes = [];
  74678. serializationObject.geometries.spheres = [];
  74679. serializationObject.geometries.cylinders = [];
  74680. serializationObject.geometries.toruses = [];
  74681. serializationObject.geometries.grounds = [];
  74682. serializationObject.geometries.planes = [];
  74683. serializationObject.geometries.torusKnots = [];
  74684. serializationObject.geometries.vertexData = [];
  74685. serializedGeometries = [];
  74686. var geometries = scene.getGeometries();
  74687. for (index = 0; index < geometries.length; index++) {
  74688. var geometry = geometries[index];
  74689. if (geometry.isReady()) {
  74690. serializeGeometry(geometry, serializationObject.geometries);
  74691. }
  74692. }
  74693. // Meshes
  74694. serializationObject.meshes = [];
  74695. for (index = 0; index < scene.meshes.length; index++) {
  74696. var abstractMesh = scene.meshes[index];
  74697. if (abstractMesh instanceof BABYLON.Mesh) {
  74698. var mesh = abstractMesh;
  74699. if (!mesh.doNotSerialize) {
  74700. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  74701. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  74702. }
  74703. }
  74704. }
  74705. }
  74706. // Particles Systems
  74707. serializationObject.particleSystems = [];
  74708. for (index = 0; index < scene.particleSystems.length; index++) {
  74709. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  74710. }
  74711. // Lens flares
  74712. serializationObject.lensFlareSystems = [];
  74713. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  74714. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  74715. }
  74716. // Shadows
  74717. serializationObject.shadowGenerators = [];
  74718. for (index = 0; index < scene.lights.length; index++) {
  74719. light = scene.lights[index];
  74720. var shadowGenerator = light.getShadowGenerator();
  74721. if (shadowGenerator) {
  74722. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  74723. }
  74724. }
  74725. // Action Manager
  74726. if (scene.actionManager) {
  74727. serializationObject.actions = scene.actionManager.serialize("scene");
  74728. }
  74729. // Audio
  74730. serializationObject.sounds = [];
  74731. for (index = 0; index < scene.soundTracks.length; index++) {
  74732. var soundtrack = scene.soundTracks[index];
  74733. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  74734. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  74735. }
  74736. }
  74737. return serializationObject;
  74738. };
  74739. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  74740. if (withParents === void 0) { withParents = false; }
  74741. if (withChildren === void 0) { withChildren = false; }
  74742. var serializationObject = {};
  74743. SceneSerializer.ClearCache();
  74744. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  74745. if (withParents || withChildren) {
  74746. //deliberate for loop! not for each, appended should be processed as well.
  74747. for (var i = 0; i < toSerialize.length; ++i) {
  74748. if (withChildren) {
  74749. toSerialize[i].getDescendants().forEach(function (node) {
  74750. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  74751. toSerialize.push(node);
  74752. }
  74753. });
  74754. }
  74755. //make sure the array doesn't contain the object already
  74756. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  74757. toSerialize.push(toSerialize[i].parent);
  74758. }
  74759. }
  74760. }
  74761. toSerialize.forEach(function (mesh) {
  74762. finalizeSingleMesh(mesh, serializationObject);
  74763. });
  74764. return serializationObject;
  74765. };
  74766. return SceneSerializer;
  74767. }());
  74768. BABYLON.SceneSerializer = SceneSerializer;
  74769. })(BABYLON || (BABYLON = {}));
  74770. //# sourceMappingURL=babylon.sceneSerializer.js.map
  74771. var BABYLON;
  74772. (function (BABYLON) {
  74773. var ReflectionProbe = /** @class */ (function () {
  74774. function ReflectionProbe(name, size, scene, generateMipMaps) {
  74775. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74776. var _this = this;
  74777. this.name = name;
  74778. this._viewMatrix = BABYLON.Matrix.Identity();
  74779. this._target = BABYLON.Vector3.Zero();
  74780. this._add = BABYLON.Vector3.Zero();
  74781. this.invertYAxis = false;
  74782. this.position = BABYLON.Vector3.Zero();
  74783. this._scene = scene;
  74784. this._scene.reflectionProbes.push(this);
  74785. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  74786. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  74787. switch (faceIndex) {
  74788. case 0:
  74789. _this._add.copyFromFloats(1, 0, 0);
  74790. break;
  74791. case 1:
  74792. _this._add.copyFromFloats(-1, 0, 0);
  74793. break;
  74794. case 2:
  74795. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  74796. break;
  74797. case 3:
  74798. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  74799. break;
  74800. case 4:
  74801. _this._add.copyFromFloats(0, 0, 1);
  74802. break;
  74803. case 5:
  74804. _this._add.copyFromFloats(0, 0, -1);
  74805. break;
  74806. }
  74807. if (_this._attachedMesh) {
  74808. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  74809. }
  74810. _this.position.addToRef(_this._add, _this._target);
  74811. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  74812. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  74813. scene._forcedViewPosition = _this.position;
  74814. });
  74815. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  74816. scene._forcedViewPosition = null;
  74817. scene.updateTransformMatrix(true);
  74818. });
  74819. if (scene.activeCamera) {
  74820. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74821. }
  74822. }
  74823. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  74824. get: function () {
  74825. return this._renderTargetTexture.samples;
  74826. },
  74827. set: function (value) {
  74828. this._renderTargetTexture.samples = value;
  74829. },
  74830. enumerable: true,
  74831. configurable: true
  74832. });
  74833. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  74834. get: function () {
  74835. return this._renderTargetTexture.refreshRate;
  74836. },
  74837. set: function (value) {
  74838. this._renderTargetTexture.refreshRate = value;
  74839. },
  74840. enumerable: true,
  74841. configurable: true
  74842. });
  74843. ReflectionProbe.prototype.getScene = function () {
  74844. return this._scene;
  74845. };
  74846. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  74847. get: function () {
  74848. return this._renderTargetTexture;
  74849. },
  74850. enumerable: true,
  74851. configurable: true
  74852. });
  74853. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  74854. get: function () {
  74855. return this._renderTargetTexture.renderList;
  74856. },
  74857. enumerable: true,
  74858. configurable: true
  74859. });
  74860. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  74861. this._attachedMesh = mesh;
  74862. };
  74863. /**
  74864. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  74865. *
  74866. * @param renderingGroupId The rendering group id corresponding to its index
  74867. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  74868. */
  74869. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  74870. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  74871. };
  74872. ReflectionProbe.prototype.dispose = function () {
  74873. var index = this._scene.reflectionProbes.indexOf(this);
  74874. if (index !== -1) {
  74875. // Remove from the scene if found
  74876. this._scene.reflectionProbes.splice(index, 1);
  74877. }
  74878. if (this._renderTargetTexture) {
  74879. this._renderTargetTexture.dispose();
  74880. this._renderTargetTexture = null;
  74881. }
  74882. };
  74883. return ReflectionProbe;
  74884. }());
  74885. BABYLON.ReflectionProbe = ReflectionProbe;
  74886. })(BABYLON || (BABYLON = {}));
  74887. //# sourceMappingURL=babylon.reflectionProbe.js.map
  74888. var BABYLON;
  74889. (function (BABYLON) {
  74890. var Layer = /** @class */ (function () {
  74891. function Layer(name, imgUrl, scene, isBackground, color) {
  74892. this.name = name;
  74893. this.scale = new BABYLON.Vector2(1, 1);
  74894. this.offset = new BABYLON.Vector2(0, 0);
  74895. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  74896. this.layerMask = 0x0FFFFFFF;
  74897. this._vertexBuffers = {};
  74898. // Events
  74899. /**
  74900. * An event triggered when the layer is disposed.
  74901. * @type {BABYLON.Observable}
  74902. */
  74903. this.onDisposeObservable = new BABYLON.Observable();
  74904. /**
  74905. * An event triggered before rendering the scene
  74906. * @type {BABYLON.Observable}
  74907. */
  74908. this.onBeforeRenderObservable = new BABYLON.Observable();
  74909. /**
  74910. * An event triggered after rendering the scene
  74911. * @type {BABYLON.Observable}
  74912. */
  74913. this.onAfterRenderObservable = new BABYLON.Observable();
  74914. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  74915. this.isBackground = isBackground === undefined ? true : isBackground;
  74916. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  74917. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  74918. this._scene.layers.push(this);
  74919. var engine = this._scene.getEngine();
  74920. // VBO
  74921. var vertices = [];
  74922. vertices.push(1, 1);
  74923. vertices.push(-1, 1);
  74924. vertices.push(-1, -1);
  74925. vertices.push(1, -1);
  74926. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74927. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  74928. this._createIndexBuffer();
  74929. // Effects
  74930. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  74931. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  74932. }
  74933. Object.defineProperty(Layer.prototype, "onDispose", {
  74934. set: function (callback) {
  74935. if (this._onDisposeObserver) {
  74936. this.onDisposeObservable.remove(this._onDisposeObserver);
  74937. }
  74938. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  74939. },
  74940. enumerable: true,
  74941. configurable: true
  74942. });
  74943. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  74944. set: function (callback) {
  74945. if (this._onBeforeRenderObserver) {
  74946. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  74947. }
  74948. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  74949. },
  74950. enumerable: true,
  74951. configurable: true
  74952. });
  74953. Object.defineProperty(Layer.prototype, "onAfterRender", {
  74954. set: function (callback) {
  74955. if (this._onAfterRenderObserver) {
  74956. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  74957. }
  74958. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  74959. },
  74960. enumerable: true,
  74961. configurable: true
  74962. });
  74963. Layer.prototype._createIndexBuffer = function () {
  74964. var engine = this._scene.getEngine();
  74965. // Indices
  74966. var indices = [];
  74967. indices.push(0);
  74968. indices.push(1);
  74969. indices.push(2);
  74970. indices.push(0);
  74971. indices.push(2);
  74972. indices.push(3);
  74973. this._indexBuffer = engine.createIndexBuffer(indices);
  74974. };
  74975. Layer.prototype._rebuild = function () {
  74976. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74977. if (vb) {
  74978. vb._rebuild();
  74979. }
  74980. this._createIndexBuffer();
  74981. };
  74982. Layer.prototype.render = function () {
  74983. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  74984. // Check
  74985. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  74986. return;
  74987. var engine = this._scene.getEngine();
  74988. this.onBeforeRenderObservable.notifyObservers(this);
  74989. // Render
  74990. engine.enableEffect(currentEffect);
  74991. engine.setState(false);
  74992. // Texture
  74993. currentEffect.setTexture("textureSampler", this.texture);
  74994. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  74995. // Color
  74996. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  74997. // Scale / offset
  74998. currentEffect.setVector2("offset", this.offset);
  74999. currentEffect.setVector2("scale", this.scale);
  75000. // VBOs
  75001. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  75002. // Draw order
  75003. if (!this.alphaTest) {
  75004. engine.setAlphaMode(this.alphaBlendingMode);
  75005. engine.draw(true, 0, 6);
  75006. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75007. }
  75008. else {
  75009. engine.draw(true, 0, 6);
  75010. }
  75011. this.onAfterRenderObservable.notifyObservers(this);
  75012. };
  75013. Layer.prototype.dispose = function () {
  75014. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75015. if (vertexBuffer) {
  75016. vertexBuffer.dispose();
  75017. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75018. }
  75019. if (this._indexBuffer) {
  75020. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75021. this._indexBuffer = null;
  75022. }
  75023. if (this.texture) {
  75024. this.texture.dispose();
  75025. this.texture = null;
  75026. }
  75027. // Remove from scene
  75028. var index = this._scene.layers.indexOf(this);
  75029. this._scene.layers.splice(index, 1);
  75030. // Callback
  75031. this.onDisposeObservable.notifyObservers(this);
  75032. this.onDisposeObservable.clear();
  75033. this.onAfterRenderObservable.clear();
  75034. this.onBeforeRenderObservable.clear();
  75035. };
  75036. return Layer;
  75037. }());
  75038. BABYLON.Layer = Layer;
  75039. })(BABYLON || (BABYLON = {}));
  75040. //# sourceMappingURL=babylon.layer.js.map
  75041. var BABYLON;
  75042. (function (BABYLON) {
  75043. var TextureTools = /** @class */ (function () {
  75044. function TextureTools() {
  75045. }
  75046. /**
  75047. * Uses the GPU to create a copy texture rescaled at a given size
  75048. * @param texture Texture to copy from
  75049. * @param width Desired width
  75050. * @param height Desired height
  75051. * @return Generated texture
  75052. */
  75053. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  75054. if (useBilinearMode === void 0) { useBilinearMode = true; }
  75055. var scene = texture.getScene();
  75056. var engine = scene.getEngine();
  75057. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  75058. rtt.wrapU = texture.wrapU;
  75059. rtt.wrapV = texture.wrapV;
  75060. rtt.uOffset = texture.uOffset;
  75061. rtt.vOffset = texture.vOffset;
  75062. rtt.uScale = texture.uScale;
  75063. rtt.vScale = texture.vScale;
  75064. rtt.uAng = texture.uAng;
  75065. rtt.vAng = texture.vAng;
  75066. rtt.wAng = texture.wAng;
  75067. rtt.coordinatesIndex = texture.coordinatesIndex;
  75068. rtt.level = texture.level;
  75069. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  75070. rtt._texture.isReady = false;
  75071. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75072. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75073. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75074. passPostProcess.getEffect().executeWhenCompiled(function () {
  75075. passPostProcess.onApply = function (effect) {
  75076. effect.setTexture("textureSampler", texture);
  75077. };
  75078. var internalTexture = rtt.getInternalTexture();
  75079. if (internalTexture) {
  75080. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  75081. engine.unBindFramebuffer(internalTexture);
  75082. rtt.disposeFramebufferObjects();
  75083. passPostProcess.dispose();
  75084. internalTexture.isReady = true;
  75085. }
  75086. });
  75087. return rtt;
  75088. };
  75089. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  75090. if (!scene._environmentBRDFTexture) {
  75091. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75092. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75093. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75094. scene._environmentBRDFTexture = texture;
  75095. }
  75096. return scene._environmentBRDFTexture;
  75097. };
  75098. 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=";
  75099. return TextureTools;
  75100. }());
  75101. BABYLON.TextureTools = TextureTools;
  75102. })(BABYLON || (BABYLON = {}));
  75103. //# sourceMappingURL=babylon.textureTools.js.map
  75104. var BABYLON;
  75105. (function (BABYLON) {
  75106. var FramingBehavior = /** @class */ (function () {
  75107. function FramingBehavior() {
  75108. this._mode = FramingBehavior.FitFrustumSidesMode;
  75109. this._radiusScale = 1.0;
  75110. this._positionScale = 0.5;
  75111. this._defaultElevation = 0.3;
  75112. this._elevationReturnTime = 1500;
  75113. this._elevationReturnWaitTime = 1000;
  75114. this._zoomStopsAnimation = false;
  75115. this._framingTime = 1500;
  75116. this._isPointerDown = false;
  75117. this._lastInteractionTime = -Infinity;
  75118. // Framing control
  75119. this._animatables = new Array();
  75120. this._betaIsAnimating = false;
  75121. }
  75122. Object.defineProperty(FramingBehavior.prototype, "name", {
  75123. get: function () {
  75124. return "Framing";
  75125. },
  75126. enumerable: true,
  75127. configurable: true
  75128. });
  75129. Object.defineProperty(FramingBehavior.prototype, "mode", {
  75130. /**
  75131. * Gets current mode used by the behavior.
  75132. */
  75133. get: function () {
  75134. return this._mode;
  75135. },
  75136. /**
  75137. * Sets the current mode used by the behavior
  75138. */
  75139. set: function (mode) {
  75140. this._mode = mode;
  75141. },
  75142. enumerable: true,
  75143. configurable: true
  75144. });
  75145. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  75146. /**
  75147. * Gets the scale applied to the radius
  75148. */
  75149. get: function () {
  75150. return this._radiusScale;
  75151. },
  75152. /**
  75153. * Sets the scale applied to the radius (1 by default)
  75154. */
  75155. set: function (radius) {
  75156. this._radiusScale = radius;
  75157. },
  75158. enumerable: true,
  75159. configurable: true
  75160. });
  75161. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  75162. /**
  75163. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  75164. */
  75165. get: function () {
  75166. return this._positionScale;
  75167. },
  75168. /**
  75169. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  75170. */
  75171. set: function (scale) {
  75172. this._positionScale = scale;
  75173. },
  75174. enumerable: true,
  75175. configurable: true
  75176. });
  75177. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  75178. /**
  75179. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  75180. * behaviour is triggered, in radians.
  75181. */
  75182. get: function () {
  75183. return this._defaultElevation;
  75184. },
  75185. /**
  75186. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  75187. * behaviour is triggered, in radians.
  75188. */
  75189. set: function (elevation) {
  75190. this._defaultElevation = elevation;
  75191. },
  75192. enumerable: true,
  75193. configurable: true
  75194. });
  75195. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  75196. /**
  75197. * Gets the time (in milliseconds) taken to return to the default beta position.
  75198. * Negative value indicates camera should not return to default.
  75199. */
  75200. get: function () {
  75201. return this._elevationReturnTime;
  75202. },
  75203. /**
  75204. * Sets the time (in milliseconds) taken to return to the default beta position.
  75205. * Negative value indicates camera should not return to default.
  75206. */
  75207. set: function (speed) {
  75208. this._elevationReturnTime = speed;
  75209. },
  75210. enumerable: true,
  75211. configurable: true
  75212. });
  75213. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  75214. /**
  75215. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  75216. */
  75217. get: function () {
  75218. return this._elevationReturnWaitTime;
  75219. },
  75220. /**
  75221. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  75222. */
  75223. set: function (time) {
  75224. this._elevationReturnWaitTime = time;
  75225. },
  75226. enumerable: true,
  75227. configurable: true
  75228. });
  75229. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  75230. /**
  75231. * Gets the flag that indicates if user zooming should stop animation.
  75232. */
  75233. get: function () {
  75234. return this._zoomStopsAnimation;
  75235. },
  75236. /**
  75237. * Sets the flag that indicates if user zooming should stop animation.
  75238. */
  75239. set: function (flag) {
  75240. this._zoomStopsAnimation = flag;
  75241. },
  75242. enumerable: true,
  75243. configurable: true
  75244. });
  75245. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  75246. /**
  75247. * Gets the transition time when framing the mesh, in milliseconds
  75248. */
  75249. get: function () {
  75250. return this._framingTime;
  75251. },
  75252. /**
  75253. * Sets the transition time when framing the mesh, in milliseconds
  75254. */
  75255. set: function (time) {
  75256. this._framingTime = time;
  75257. },
  75258. enumerable: true,
  75259. configurable: true
  75260. });
  75261. FramingBehavior.prototype.init = function () {
  75262. // Do notihng
  75263. };
  75264. FramingBehavior.prototype.attach = function (camera) {
  75265. var _this = this;
  75266. this._attachedCamera = camera;
  75267. var scene = this._attachedCamera.getScene();
  75268. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  75269. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  75270. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  75271. _this._isPointerDown = true;
  75272. return;
  75273. }
  75274. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  75275. _this._isPointerDown = false;
  75276. }
  75277. });
  75278. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  75279. if (mesh) {
  75280. _this.zoomOnMesh(mesh);
  75281. }
  75282. });
  75283. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  75284. // Stop the animation if there is user interaction and the animation should stop for this interaction
  75285. _this._applyUserInteraction();
  75286. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  75287. // back to the default position after a given timeout
  75288. _this._maintainCameraAboveGround();
  75289. });
  75290. };
  75291. FramingBehavior.prototype.detach = function () {
  75292. if (!this._attachedCamera) {
  75293. return;
  75294. }
  75295. var scene = this._attachedCamera.getScene();
  75296. if (this._onPrePointerObservableObserver) {
  75297. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  75298. }
  75299. if (this._onAfterCheckInputsObserver) {
  75300. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  75301. }
  75302. if (this._onMeshTargetChangedObserver) {
  75303. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  75304. }
  75305. this._attachedCamera = null;
  75306. };
  75307. /**
  75308. * Targets the given mesh and updates zoom level accordingly.
  75309. * @param mesh The mesh to target.
  75310. * @param radius Optional. If a cached radius position already exists, overrides default.
  75311. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  75312. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  75313. * @param onAnimationEnd Callback triggered at the end of the framing animation
  75314. */
  75315. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  75316. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  75317. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  75318. mesh.computeWorldMatrix(true);
  75319. var boundingBox = mesh.getBoundingInfo().boundingBox;
  75320. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  75321. };
  75322. /**
  75323. * Targets the given mesh with its children and updates zoom level accordingly.
  75324. * @param mesh The mesh to target.
  75325. * @param radius Optional. If a cached radius position already exists, overrides default.
  75326. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  75327. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  75328. * @param onAnimationEnd Callback triggered at the end of the framing animation
  75329. */
  75330. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  75331. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  75332. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  75333. mesh.computeWorldMatrix(true);
  75334. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  75335. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  75336. };
  75337. /**
  75338. * Targets the given meshes with their children and updates zoom level accordingly.
  75339. * @param meshes The mesh to target.
  75340. * @param radius Optional. If a cached radius position already exists, overrides default.
  75341. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  75342. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  75343. * @param onAnimationEnd Callback triggered at the end of the framing animation
  75344. */
  75345. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  75346. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  75347. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  75348. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  75349. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  75350. for (var i = 0; i < meshes.length; i++) {
  75351. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  75352. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  75353. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  75354. }
  75355. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  75356. };
  75357. /**
  75358. * Targets the given mesh and updates zoom level accordingly.
  75359. * @param mesh The mesh to target.
  75360. * @param radius Optional. If a cached radius position already exists, overrides default.
  75361. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  75362. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  75363. * @param onAnimationEnd Callback triggered at the end of the framing animation
  75364. */
  75365. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  75366. var _this = this;
  75367. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  75368. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  75369. var zoomTarget;
  75370. if (!this._attachedCamera) {
  75371. return;
  75372. }
  75373. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  75374. var bottom = minimumWorld.y;
  75375. var top = maximumWorld.y;
  75376. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  75377. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  75378. if (focusOnOriginXZ) {
  75379. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  75380. }
  75381. else {
  75382. var centerWorld = minimumWorld.add(radiusWorld);
  75383. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  75384. }
  75385. if (!this._vectorTransition) {
  75386. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  75387. }
  75388. this._betaIsAnimating = true;
  75389. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  75390. if (animatable) {
  75391. this._animatables.push(animatable);
  75392. }
  75393. // sets the radius and lower radius bounds
  75394. // Small delta ensures camera is not always at lower zoom limit.
  75395. var radius = 0;
  75396. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  75397. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  75398. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  75399. radius = position;
  75400. }
  75401. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  75402. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  75403. if (this._attachedCamera.lowerRadiusLimit === null) {
  75404. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  75405. }
  75406. }
  75407. // Set sensibilities
  75408. var extend = maximumWorld.subtract(minimumWorld).length();
  75409. this._attachedCamera.panningSensibility = 5000 / extend;
  75410. this._attachedCamera.wheelPrecision = 100 / radius;
  75411. // transition to new radius
  75412. if (!this._radiusTransition) {
  75413. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  75414. }
  75415. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  75416. if (onAnimationEnd) {
  75417. onAnimationEnd();
  75418. }
  75419. if (_this._attachedCamera) {
  75420. _this._attachedCamera.storeState();
  75421. }
  75422. });
  75423. if (animatable) {
  75424. this._animatables.push(animatable);
  75425. }
  75426. };
  75427. /**
  75428. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  75429. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  75430. * frustum width.
  75431. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  75432. * to fully enclose the mesh in the viewing frustum.
  75433. */
  75434. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  75435. var size = maximumWorld.subtract(minimumWorld);
  75436. var boxVectorGlobalDiagonal = size.length();
  75437. var frustumSlope = this._getFrustumSlope();
  75438. // Formula for setting distance
  75439. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  75440. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  75441. // Horizon distance
  75442. var radius = radiusWithoutFraming * this._radiusScale;
  75443. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  75444. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  75445. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  75446. var camera = this._attachedCamera;
  75447. if (!camera) {
  75448. return 0;
  75449. }
  75450. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  75451. // Don't exceed the requested limit
  75452. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  75453. }
  75454. // Don't exceed the upper radius limit
  75455. if (camera.upperRadiusLimit) {
  75456. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  75457. }
  75458. return distance;
  75459. };
  75460. /**
  75461. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  75462. * is automatically returned to its default position (expected to be above ground plane).
  75463. */
  75464. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  75465. var _this = this;
  75466. if (this._elevationReturnTime < 0) {
  75467. return;
  75468. }
  75469. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  75470. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  75471. var limitBeta = Math.PI * 0.5;
  75472. // Bring the camera back up if below the ground plane
  75473. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  75474. this._betaIsAnimating = true;
  75475. //Transition to new position
  75476. this.stopAllAnimations();
  75477. if (!this._betaTransition) {
  75478. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  75479. }
  75480. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  75481. _this._clearAnimationLocks();
  75482. _this.stopAllAnimations();
  75483. });
  75484. if (animatabe) {
  75485. this._animatables.push(animatabe);
  75486. }
  75487. }
  75488. };
  75489. /**
  75490. * Returns the frustum slope based on the canvas ratio and camera FOV
  75491. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  75492. */
  75493. FramingBehavior.prototype._getFrustumSlope = function () {
  75494. // Calculate the viewport ratio
  75495. // Aspect Ratio is Height/Width.
  75496. var camera = this._attachedCamera;
  75497. if (!camera) {
  75498. return BABYLON.Vector2.Zero();
  75499. }
  75500. var engine = camera.getScene().getEngine();
  75501. var aspectRatio = engine.getAspectRatio(camera);
  75502. // Camera FOV is the vertical field of view (top-bottom) in radians.
  75503. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  75504. var frustumSlopeY = Math.tan(camera.fov / 2);
  75505. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  75506. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  75507. // along the forward vector.
  75508. var frustumSlopeX = frustumSlopeY * aspectRatio;
  75509. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  75510. };
  75511. /**
  75512. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  75513. */
  75514. FramingBehavior.prototype._clearAnimationLocks = function () {
  75515. this._betaIsAnimating = false;
  75516. };
  75517. /**
  75518. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  75519. */
  75520. FramingBehavior.prototype._applyUserInteraction = function () {
  75521. if (this.isUserIsMoving) {
  75522. this._lastInteractionTime = BABYLON.Tools.Now;
  75523. this.stopAllAnimations();
  75524. this._clearAnimationLocks();
  75525. }
  75526. };
  75527. /**
  75528. * Stops and removes all animations that have been applied to the camera
  75529. */
  75530. FramingBehavior.prototype.stopAllAnimations = function () {
  75531. if (this._attachedCamera) {
  75532. this._attachedCamera.animations = [];
  75533. }
  75534. while (this._animatables.length) {
  75535. if (this._animatables[0]) {
  75536. this._animatables[0].onAnimationEnd = null;
  75537. this._animatables[0].stop();
  75538. }
  75539. this._animatables.shift();
  75540. }
  75541. };
  75542. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  75543. /**
  75544. * Gets a value indicating if the user is moving the camera
  75545. */
  75546. get: function () {
  75547. if (!this._attachedCamera) {
  75548. return false;
  75549. }
  75550. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  75551. this._attachedCamera.inertialBetaOffset !== 0 ||
  75552. this._attachedCamera.inertialRadiusOffset !== 0 ||
  75553. this._attachedCamera.inertialPanningX !== 0 ||
  75554. this._attachedCamera.inertialPanningY !== 0 ||
  75555. this._isPointerDown;
  75556. },
  75557. enumerable: true,
  75558. configurable: true
  75559. });
  75560. /**
  75561. * The easing function used by animations
  75562. */
  75563. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  75564. /**
  75565. * The easing mode used by animations
  75566. */
  75567. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  75568. // Statics
  75569. /**
  75570. * The camera can move all the way towards the mesh.
  75571. */
  75572. FramingBehavior.IgnoreBoundsSizeMode = 0;
  75573. /**
  75574. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  75575. */
  75576. FramingBehavior.FitFrustumSidesMode = 1;
  75577. return FramingBehavior;
  75578. }());
  75579. BABYLON.FramingBehavior = FramingBehavior;
  75580. })(BABYLON || (BABYLON = {}));
  75581. //# sourceMappingURL=babylon.framingBehavior.js.map
  75582. var BABYLON;
  75583. (function (BABYLON) {
  75584. /**
  75585. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  75586. */
  75587. var BouncingBehavior = /** @class */ (function () {
  75588. function BouncingBehavior() {
  75589. /**
  75590. * The duration of the animation, in milliseconds
  75591. */
  75592. this.transitionDuration = 450;
  75593. /**
  75594. * Length of the distance animated by the transition when lower radius is reached
  75595. */
  75596. this.lowerRadiusTransitionRange = 2;
  75597. /**
  75598. * Length of the distance animated by the transition when upper radius is reached
  75599. */
  75600. this.upperRadiusTransitionRange = -2;
  75601. this._autoTransitionRange = false;
  75602. // Animations
  75603. this._radiusIsAnimating = false;
  75604. this._radiusBounceTransition = null;
  75605. this._animatables = new Array();
  75606. }
  75607. Object.defineProperty(BouncingBehavior.prototype, "name", {
  75608. get: function () {
  75609. return "Bouncing";
  75610. },
  75611. enumerable: true,
  75612. configurable: true
  75613. });
  75614. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  75615. /**
  75616. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  75617. */
  75618. get: function () {
  75619. return this._autoTransitionRange;
  75620. },
  75621. /**
  75622. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  75623. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  75624. */
  75625. set: function (value) {
  75626. var _this = this;
  75627. if (this._autoTransitionRange === value) {
  75628. return;
  75629. }
  75630. this._autoTransitionRange = value;
  75631. var camera = this._attachedCamera;
  75632. if (!camera) {
  75633. return;
  75634. }
  75635. if (value) {
  75636. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  75637. if (!mesh) {
  75638. return;
  75639. }
  75640. mesh.computeWorldMatrix(true);
  75641. var diagonal = mesh.getBoundingInfo().diagonalLength;
  75642. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  75643. _this.upperRadiusTransitionRange = diagonal * 0.05;
  75644. });
  75645. }
  75646. else if (this._onMeshTargetChangedObserver) {
  75647. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  75648. }
  75649. },
  75650. enumerable: true,
  75651. configurable: true
  75652. });
  75653. BouncingBehavior.prototype.init = function () {
  75654. // Do notihng
  75655. };
  75656. BouncingBehavior.prototype.attach = function (camera) {
  75657. var _this = this;
  75658. this._attachedCamera = camera;
  75659. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  75660. if (!_this._attachedCamera) {
  75661. return;
  75662. }
  75663. // Add the bounce animation to the lower radius limit
  75664. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  75665. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  75666. }
  75667. // Add the bounce animation to the upper radius limit
  75668. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  75669. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  75670. }
  75671. });
  75672. };
  75673. BouncingBehavior.prototype.detach = function () {
  75674. if (!this._attachedCamera) {
  75675. return;
  75676. }
  75677. if (this._onAfterCheckInputsObserver) {
  75678. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  75679. }
  75680. if (this._onMeshTargetChangedObserver) {
  75681. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  75682. }
  75683. this._attachedCamera = null;
  75684. };
  75685. /**
  75686. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  75687. * @param radiusLimit The limit to check against.
  75688. * @return Bool to indicate if at limit.
  75689. */
  75690. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  75691. if (!this._attachedCamera) {
  75692. return false;
  75693. }
  75694. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  75695. return true;
  75696. }
  75697. return false;
  75698. };
  75699. /**
  75700. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  75701. * @param radiusDelta The delta by which to animate to. Can be negative.
  75702. */
  75703. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  75704. var _this = this;
  75705. if (!this._attachedCamera) {
  75706. return;
  75707. }
  75708. if (!this._radiusBounceTransition) {
  75709. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  75710. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  75711. }
  75712. // Prevent zoom until bounce has completed
  75713. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  75714. this._attachedCamera.wheelPrecision = Infinity;
  75715. this._attachedCamera.inertialRadiusOffset = 0;
  75716. // Animate to the radius limit
  75717. this.stopAllAnimations();
  75718. this._radiusIsAnimating = true;
  75719. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  75720. if (animatable) {
  75721. this._animatables.push(animatable);
  75722. }
  75723. };
  75724. /**
  75725. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  75726. */
  75727. BouncingBehavior.prototype._clearAnimationLocks = function () {
  75728. this._radiusIsAnimating = false;
  75729. if (this._attachedCamera) {
  75730. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  75731. }
  75732. };
  75733. /**
  75734. * Stops and removes all animations that have been applied to the camera
  75735. */
  75736. BouncingBehavior.prototype.stopAllAnimations = function () {
  75737. if (this._attachedCamera) {
  75738. this._attachedCamera.animations = [];
  75739. }
  75740. while (this._animatables.length) {
  75741. this._animatables[0].onAnimationEnd = null;
  75742. this._animatables[0].stop();
  75743. this._animatables.shift();
  75744. }
  75745. };
  75746. /**
  75747. * The easing function used by animations
  75748. */
  75749. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  75750. /**
  75751. * The easing mode used by animations
  75752. */
  75753. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  75754. return BouncingBehavior;
  75755. }());
  75756. BABYLON.BouncingBehavior = BouncingBehavior;
  75757. })(BABYLON || (BABYLON = {}));
  75758. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  75759. var BABYLON;
  75760. (function (BABYLON) {
  75761. var AutoRotationBehavior = /** @class */ (function () {
  75762. function AutoRotationBehavior() {
  75763. this._zoomStopsAnimation = false;
  75764. this._idleRotationSpeed = 0.05;
  75765. this._idleRotationWaitTime = 2000;
  75766. this._idleRotationSpinupTime = 2000;
  75767. this._isPointerDown = false;
  75768. this._lastFrameTime = null;
  75769. this._lastInteractionTime = -Infinity;
  75770. this._cameraRotationSpeed = 0;
  75771. this._lastFrameRadius = 0;
  75772. }
  75773. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  75774. get: function () {
  75775. return "AutoRotation";
  75776. },
  75777. enumerable: true,
  75778. configurable: true
  75779. });
  75780. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  75781. /**
  75782. * Gets the flag that indicates if user zooming should stop animation.
  75783. */
  75784. get: function () {
  75785. return this._zoomStopsAnimation;
  75786. },
  75787. /**
  75788. * Sets the flag that indicates if user zooming should stop animation.
  75789. */
  75790. set: function (flag) {
  75791. this._zoomStopsAnimation = flag;
  75792. },
  75793. enumerable: true,
  75794. configurable: true
  75795. });
  75796. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  75797. /**
  75798. * Gets the default speed at which the camera rotates around the model.
  75799. */
  75800. get: function () {
  75801. return this._idleRotationSpeed;
  75802. },
  75803. /**
  75804. * Sets the default speed at which the camera rotates around the model.
  75805. */
  75806. set: function (speed) {
  75807. this._idleRotationSpeed = speed;
  75808. },
  75809. enumerable: true,
  75810. configurable: true
  75811. });
  75812. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  75813. /**
  75814. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  75815. */
  75816. get: function () {
  75817. return this._idleRotationWaitTime;
  75818. },
  75819. /**
  75820. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  75821. */
  75822. set: function (time) {
  75823. this._idleRotationWaitTime = time;
  75824. },
  75825. enumerable: true,
  75826. configurable: true
  75827. });
  75828. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  75829. /**
  75830. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  75831. */
  75832. get: function () {
  75833. return this._idleRotationSpinupTime;
  75834. },
  75835. /**
  75836. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  75837. */
  75838. set: function (time) {
  75839. this._idleRotationSpinupTime = time;
  75840. },
  75841. enumerable: true,
  75842. configurable: true
  75843. });
  75844. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  75845. /**
  75846. * Gets a value indicating if the camera is currently rotating because of this behavior
  75847. */
  75848. get: function () {
  75849. return Math.abs(this._cameraRotationSpeed) > 0;
  75850. },
  75851. enumerable: true,
  75852. configurable: true
  75853. });
  75854. AutoRotationBehavior.prototype.init = function () {
  75855. // Do notihng
  75856. };
  75857. AutoRotationBehavior.prototype.attach = function (camera) {
  75858. var _this = this;
  75859. this._attachedCamera = camera;
  75860. var scene = this._attachedCamera.getScene();
  75861. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  75862. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  75863. _this._isPointerDown = true;
  75864. return;
  75865. }
  75866. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  75867. _this._isPointerDown = false;
  75868. }
  75869. });
  75870. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  75871. var now = BABYLON.Tools.Now;
  75872. var dt = 0;
  75873. if (_this._lastFrameTime != null) {
  75874. dt = now - _this._lastFrameTime;
  75875. }
  75876. _this._lastFrameTime = now;
  75877. // Stop the animation if there is user interaction and the animation should stop for this interaction
  75878. _this._applyUserInteraction();
  75879. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  75880. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  75881. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  75882. // Step camera rotation by rotation speed
  75883. if (_this._attachedCamera) {
  75884. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  75885. }
  75886. });
  75887. };
  75888. AutoRotationBehavior.prototype.detach = function () {
  75889. if (!this._attachedCamera) {
  75890. return;
  75891. }
  75892. var scene = this._attachedCamera.getScene();
  75893. if (this._onPrePointerObservableObserver) {
  75894. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  75895. }
  75896. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  75897. this._attachedCamera = null;
  75898. };
  75899. /**
  75900. * Returns true if user is scrolling.
  75901. * @return true if user is scrolling.
  75902. */
  75903. AutoRotationBehavior.prototype._userIsZooming = function () {
  75904. if (!this._attachedCamera) {
  75905. return false;
  75906. }
  75907. return this._attachedCamera.inertialRadiusOffset !== 0;
  75908. };
  75909. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  75910. if (!this._attachedCamera) {
  75911. return false;
  75912. }
  75913. var zoomHasHitLimit = false;
  75914. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  75915. zoomHasHitLimit = true;
  75916. }
  75917. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  75918. this._lastFrameRadius = this._attachedCamera.radius;
  75919. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  75920. };
  75921. /**
  75922. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  75923. */
  75924. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  75925. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  75926. this._lastInteractionTime = BABYLON.Tools.Now;
  75927. }
  75928. };
  75929. // Tools
  75930. AutoRotationBehavior.prototype._userIsMoving = function () {
  75931. if (!this._attachedCamera) {
  75932. return false;
  75933. }
  75934. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  75935. this._attachedCamera.inertialBetaOffset !== 0 ||
  75936. this._attachedCamera.inertialRadiusOffset !== 0 ||
  75937. this._attachedCamera.inertialPanningX !== 0 ||
  75938. this._attachedCamera.inertialPanningY !== 0 ||
  75939. this._isPointerDown;
  75940. };
  75941. return AutoRotationBehavior;
  75942. }());
  75943. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  75944. })(BABYLON || (BABYLON = {}));
  75945. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  75946. var BABYLON;
  75947. (function (BABYLON) {
  75948. /**
  75949. * This class can be used to get instrumentation data from a Babylon engine
  75950. */
  75951. var EngineInstrumentation = /** @class */ (function () {
  75952. function EngineInstrumentation(engine) {
  75953. this.engine = engine;
  75954. this._captureGPUFrameTime = false;
  75955. this._gpuFrameTime = new BABYLON.PerfCounter();
  75956. this._captureShaderCompilationTime = false;
  75957. this._shaderCompilationTime = new BABYLON.PerfCounter();
  75958. // Observers
  75959. this._onBeginFrameObserver = null;
  75960. this._onEndFrameObserver = null;
  75961. this._onBeforeShaderCompilationObserver = null;
  75962. this._onAfterShaderCompilationObserver = null;
  75963. }
  75964. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  75965. // Properties
  75966. /**
  75967. * Gets the perf counter used for GPU frame time
  75968. */
  75969. get: function () {
  75970. return this._gpuFrameTime;
  75971. },
  75972. enumerable: true,
  75973. configurable: true
  75974. });
  75975. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  75976. /**
  75977. * Gets the GPU frame time capture status
  75978. */
  75979. get: function () {
  75980. return this._captureGPUFrameTime;
  75981. },
  75982. /**
  75983. * Enable or disable the GPU frame time capture
  75984. */
  75985. set: function (value) {
  75986. var _this = this;
  75987. if (value === this._captureGPUFrameTime) {
  75988. return;
  75989. }
  75990. this._captureGPUFrameTime = value;
  75991. if (value) {
  75992. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  75993. if (!_this._gpuFrameTimeToken) {
  75994. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  75995. }
  75996. });
  75997. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  75998. if (!_this._gpuFrameTimeToken) {
  75999. return;
  76000. }
  76001. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  76002. if (time > -1) {
  76003. _this._gpuFrameTimeToken = null;
  76004. _this._gpuFrameTime.fetchNewFrame();
  76005. _this._gpuFrameTime.addCount(time, true);
  76006. }
  76007. });
  76008. }
  76009. else {
  76010. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  76011. this._onBeginFrameObserver = null;
  76012. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  76013. this._onEndFrameObserver = null;
  76014. }
  76015. },
  76016. enumerable: true,
  76017. configurable: true
  76018. });
  76019. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  76020. /**
  76021. * Gets the perf counter used for shader compilation time
  76022. */
  76023. get: function () {
  76024. return this._shaderCompilationTime;
  76025. },
  76026. enumerable: true,
  76027. configurable: true
  76028. });
  76029. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  76030. /**
  76031. * Gets the shader compilation time capture status
  76032. */
  76033. get: function () {
  76034. return this._captureShaderCompilationTime;
  76035. },
  76036. /**
  76037. * Enable or disable the shader compilation time capture
  76038. */
  76039. set: function (value) {
  76040. var _this = this;
  76041. if (value === this._captureShaderCompilationTime) {
  76042. return;
  76043. }
  76044. this._captureShaderCompilationTime = value;
  76045. if (value) {
  76046. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  76047. _this._shaderCompilationTime.fetchNewFrame();
  76048. _this._shaderCompilationTime.beginMonitoring();
  76049. });
  76050. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  76051. _this._shaderCompilationTime.endMonitoring();
  76052. });
  76053. }
  76054. else {
  76055. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  76056. this._onBeforeShaderCompilationObserver = null;
  76057. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  76058. this._onAfterShaderCompilationObserver = null;
  76059. }
  76060. },
  76061. enumerable: true,
  76062. configurable: true
  76063. });
  76064. EngineInstrumentation.prototype.dispose = function () {
  76065. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  76066. this._onBeginFrameObserver = null;
  76067. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  76068. this._onEndFrameObserver = null;
  76069. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  76070. this._onBeforeShaderCompilationObserver = null;
  76071. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  76072. this._onAfterShaderCompilationObserver = null;
  76073. this.engine = null;
  76074. };
  76075. return EngineInstrumentation;
  76076. }());
  76077. BABYLON.EngineInstrumentation = EngineInstrumentation;
  76078. })(BABYLON || (BABYLON = {}));
  76079. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  76080. var BABYLON;
  76081. (function (BABYLON) {
  76082. /**
  76083. * This class can be used to get instrumentation data from a Babylon engine
  76084. */
  76085. var SceneInstrumentation = /** @class */ (function () {
  76086. function SceneInstrumentation(scene) {
  76087. var _this = this;
  76088. this.scene = scene;
  76089. this._captureActiveMeshesEvaluationTime = false;
  76090. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  76091. this._captureRenderTargetsRenderTime = false;
  76092. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  76093. this._captureFrameTime = false;
  76094. this._frameTime = new BABYLON.PerfCounter();
  76095. this._captureRenderTime = false;
  76096. this._renderTime = new BABYLON.PerfCounter();
  76097. this._captureInterFrameTime = false;
  76098. this._interFrameTime = new BABYLON.PerfCounter();
  76099. this._captureParticlesRenderTime = false;
  76100. this._particlesRenderTime = new BABYLON.PerfCounter();
  76101. this._captureSpritesRenderTime = false;
  76102. this._spritesRenderTime = new BABYLON.PerfCounter();
  76103. this._capturePhysicsTime = false;
  76104. this._physicsTime = new BABYLON.PerfCounter();
  76105. this._captureAnimationsTime = false;
  76106. this._animationsTime = new BABYLON.PerfCounter();
  76107. // Observers
  76108. this._onBeforeActiveMeshesEvaluationObserver = null;
  76109. this._onAfterActiveMeshesEvaluationObserver = null;
  76110. this._onBeforeRenderTargetsRenderObserver = null;
  76111. this._onAfterRenderTargetsRenderObserver = null;
  76112. this._onAfterRenderObserver = null;
  76113. this._onBeforeDrawPhaseObserver = null;
  76114. this._onAfterDrawPhaseObserver = null;
  76115. this._onBeforeAnimationsObserver = null;
  76116. this._onBeforeParticlesRenderingObserver = null;
  76117. this._onAfterParticlesRenderingObserver = null;
  76118. this._onBeforeSpritesRenderingObserver = null;
  76119. this._onAfterSpritesRenderingObserver = null;
  76120. this._onBeforePhysicsObserver = null;
  76121. this._onAfterPhysicsObserver = null;
  76122. this._onAfterAnimationsObserver = null;
  76123. // Before render
  76124. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  76125. if (_this._captureActiveMeshesEvaluationTime) {
  76126. _this._activeMeshesEvaluationTime.fetchNewFrame();
  76127. }
  76128. if (_this._captureRenderTargetsRenderTime) {
  76129. _this._renderTargetsRenderTime.fetchNewFrame();
  76130. }
  76131. if (_this._captureFrameTime) {
  76132. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  76133. _this._frameTime.beginMonitoring();
  76134. }
  76135. if (_this._captureInterFrameTime) {
  76136. _this._interFrameTime.endMonitoring();
  76137. }
  76138. if (_this._captureParticlesRenderTime) {
  76139. _this._particlesRenderTime.fetchNewFrame();
  76140. }
  76141. if (_this._captureSpritesRenderTime) {
  76142. _this._spritesRenderTime.fetchNewFrame();
  76143. }
  76144. if (_this._captureAnimationsTime) {
  76145. _this._animationsTime.beginMonitoring();
  76146. }
  76147. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  76148. });
  76149. // After render
  76150. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  76151. if (_this._captureFrameTime) {
  76152. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  76153. _this._frameTime.endMonitoring();
  76154. }
  76155. if (_this._captureRenderTime) {
  76156. _this._renderTime.endMonitoring(false);
  76157. }
  76158. if (_this._captureInterFrameTime) {
  76159. _this._interFrameTime.beginMonitoring();
  76160. }
  76161. });
  76162. }
  76163. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  76164. // Properties
  76165. /**
  76166. * Gets the perf counter used for active meshes evaluation time
  76167. */
  76168. get: function () {
  76169. return this._activeMeshesEvaluationTime;
  76170. },
  76171. enumerable: true,
  76172. configurable: true
  76173. });
  76174. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  76175. /**
  76176. * Gets the active meshes evaluation time capture status
  76177. */
  76178. get: function () {
  76179. return this._captureActiveMeshesEvaluationTime;
  76180. },
  76181. /**
  76182. * Enable or disable the active meshes evaluation time capture
  76183. */
  76184. set: function (value) {
  76185. var _this = this;
  76186. if (value === this._captureActiveMeshesEvaluationTime) {
  76187. return;
  76188. }
  76189. this._captureActiveMeshesEvaluationTime = value;
  76190. if (value) {
  76191. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  76192. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  76193. _this._activeMeshesEvaluationTime.beginMonitoring();
  76194. });
  76195. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  76196. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  76197. _this._activeMeshesEvaluationTime.endMonitoring();
  76198. });
  76199. }
  76200. else {
  76201. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  76202. this._onBeforeActiveMeshesEvaluationObserver = null;
  76203. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  76204. this._onAfterActiveMeshesEvaluationObserver = null;
  76205. }
  76206. },
  76207. enumerable: true,
  76208. configurable: true
  76209. });
  76210. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  76211. /**
  76212. * Gets the perf counter used for render targets render time
  76213. */
  76214. get: function () {
  76215. return this._renderTargetsRenderTime;
  76216. },
  76217. enumerable: true,
  76218. configurable: true
  76219. });
  76220. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  76221. /**
  76222. * Gets the render targets render time capture status
  76223. */
  76224. get: function () {
  76225. return this._captureRenderTargetsRenderTime;
  76226. },
  76227. /**
  76228. * Enable or disable the render targets render time capture
  76229. */
  76230. set: function (value) {
  76231. var _this = this;
  76232. if (value === this._captureRenderTargetsRenderTime) {
  76233. return;
  76234. }
  76235. this._captureRenderTargetsRenderTime = value;
  76236. if (value) {
  76237. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  76238. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  76239. _this._renderTargetsRenderTime.beginMonitoring();
  76240. });
  76241. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  76242. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  76243. _this._renderTargetsRenderTime.endMonitoring(false);
  76244. });
  76245. }
  76246. else {
  76247. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  76248. this._onBeforeRenderTargetsRenderObserver = null;
  76249. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  76250. this._onAfterRenderTargetsRenderObserver = null;
  76251. }
  76252. },
  76253. enumerable: true,
  76254. configurable: true
  76255. });
  76256. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  76257. /**
  76258. * Gets the perf counter used for particles render time
  76259. */
  76260. get: function () {
  76261. return this._particlesRenderTime;
  76262. },
  76263. enumerable: true,
  76264. configurable: true
  76265. });
  76266. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  76267. /**
  76268. * Gets the particles render time capture status
  76269. */
  76270. get: function () {
  76271. return this._captureParticlesRenderTime;
  76272. },
  76273. /**
  76274. * Enable or disable the particles render time capture
  76275. */
  76276. set: function (value) {
  76277. var _this = this;
  76278. if (value === this._captureParticlesRenderTime) {
  76279. return;
  76280. }
  76281. this._captureParticlesRenderTime = value;
  76282. if (value) {
  76283. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  76284. BABYLON.Tools.StartPerformanceCounter("Particles");
  76285. _this._particlesRenderTime.beginMonitoring();
  76286. });
  76287. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  76288. BABYLON.Tools.EndPerformanceCounter("Particles");
  76289. _this._particlesRenderTime.endMonitoring(false);
  76290. });
  76291. }
  76292. else {
  76293. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  76294. this._onBeforeParticlesRenderingObserver = null;
  76295. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  76296. this._onAfterParticlesRenderingObserver = null;
  76297. }
  76298. },
  76299. enumerable: true,
  76300. configurable: true
  76301. });
  76302. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  76303. /**
  76304. * Gets the perf counter used for sprites render time
  76305. */
  76306. get: function () {
  76307. return this._spritesRenderTime;
  76308. },
  76309. enumerable: true,
  76310. configurable: true
  76311. });
  76312. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  76313. /**
  76314. * Gets the sprites render time capture status
  76315. */
  76316. get: function () {
  76317. return this._captureSpritesRenderTime;
  76318. },
  76319. /**
  76320. * Enable or disable the sprites render time capture
  76321. */
  76322. set: function (value) {
  76323. var _this = this;
  76324. if (value === this._captureSpritesRenderTime) {
  76325. return;
  76326. }
  76327. this._captureSpritesRenderTime = value;
  76328. if (value) {
  76329. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  76330. BABYLON.Tools.StartPerformanceCounter("Sprites");
  76331. _this._spritesRenderTime.beginMonitoring();
  76332. });
  76333. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  76334. BABYLON.Tools.EndPerformanceCounter("Sprites");
  76335. _this._spritesRenderTime.endMonitoring(false);
  76336. });
  76337. }
  76338. else {
  76339. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  76340. this._onBeforeSpritesRenderingObserver = null;
  76341. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  76342. this._onAfterSpritesRenderingObserver = null;
  76343. }
  76344. },
  76345. enumerable: true,
  76346. configurable: true
  76347. });
  76348. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  76349. /**
  76350. * Gets the perf counter used for physics time
  76351. */
  76352. get: function () {
  76353. return this._physicsTime;
  76354. },
  76355. enumerable: true,
  76356. configurable: true
  76357. });
  76358. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  76359. /**
  76360. * Gets the physics time capture status
  76361. */
  76362. get: function () {
  76363. return this._capturePhysicsTime;
  76364. },
  76365. /**
  76366. * Enable or disable the physics time capture
  76367. */
  76368. set: function (value) {
  76369. var _this = this;
  76370. if (value === this._capturePhysicsTime) {
  76371. return;
  76372. }
  76373. this._capturePhysicsTime = value;
  76374. if (value) {
  76375. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  76376. BABYLON.Tools.StartPerformanceCounter("Physics");
  76377. _this._physicsTime.beginMonitoring();
  76378. });
  76379. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  76380. BABYLON.Tools.EndPerformanceCounter("Physics");
  76381. _this._physicsTime.endMonitoring();
  76382. });
  76383. }
  76384. else {
  76385. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  76386. this._onBeforePhysicsObserver = null;
  76387. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  76388. this._onAfterPhysicsObserver = null;
  76389. }
  76390. },
  76391. enumerable: true,
  76392. configurable: true
  76393. });
  76394. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  76395. /**
  76396. * Gets the perf counter used for animations time
  76397. */
  76398. get: function () {
  76399. return this._animationsTime;
  76400. },
  76401. enumerable: true,
  76402. configurable: true
  76403. });
  76404. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  76405. /**
  76406. * Gets the animations time capture status
  76407. */
  76408. get: function () {
  76409. return this._captureAnimationsTime;
  76410. },
  76411. /**
  76412. * Enable or disable the animations time capture
  76413. */
  76414. set: function (value) {
  76415. var _this = this;
  76416. if (value === this._captureAnimationsTime) {
  76417. return;
  76418. }
  76419. this._captureAnimationsTime = value;
  76420. if (value) {
  76421. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  76422. _this._animationsTime.endMonitoring();
  76423. });
  76424. }
  76425. else {
  76426. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  76427. this._onAfterAnimationsObserver = null;
  76428. }
  76429. },
  76430. enumerable: true,
  76431. configurable: true
  76432. });
  76433. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  76434. /**
  76435. * Gets the perf counter used for frame time capture
  76436. */
  76437. get: function () {
  76438. return this._frameTime;
  76439. },
  76440. enumerable: true,
  76441. configurable: true
  76442. });
  76443. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  76444. /**
  76445. * Gets the frame time capture status
  76446. */
  76447. get: function () {
  76448. return this._captureFrameTime;
  76449. },
  76450. /**
  76451. * Enable or disable the frame time capture
  76452. */
  76453. set: function (value) {
  76454. this._captureFrameTime = value;
  76455. },
  76456. enumerable: true,
  76457. configurable: true
  76458. });
  76459. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  76460. /**
  76461. * Gets the perf counter used for inter-frames time capture
  76462. */
  76463. get: function () {
  76464. return this._interFrameTime;
  76465. },
  76466. enumerable: true,
  76467. configurable: true
  76468. });
  76469. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  76470. /**
  76471. * Gets the inter-frames time capture status
  76472. */
  76473. get: function () {
  76474. return this._captureInterFrameTime;
  76475. },
  76476. /**
  76477. * Enable or disable the inter-frames time capture
  76478. */
  76479. set: function (value) {
  76480. this._captureInterFrameTime = value;
  76481. },
  76482. enumerable: true,
  76483. configurable: true
  76484. });
  76485. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  76486. /**
  76487. * Gets the perf counter used for render time capture
  76488. */
  76489. get: function () {
  76490. return this._renderTime;
  76491. },
  76492. enumerable: true,
  76493. configurable: true
  76494. });
  76495. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  76496. /**
  76497. * Gets the render time capture status
  76498. */
  76499. get: function () {
  76500. return this._captureRenderTime;
  76501. },
  76502. /**
  76503. * Enable or disable the render time capture
  76504. */
  76505. set: function (value) {
  76506. var _this = this;
  76507. if (value === this._captureRenderTime) {
  76508. return;
  76509. }
  76510. this._captureRenderTime = value;
  76511. if (value) {
  76512. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  76513. _this._renderTime.beginMonitoring();
  76514. BABYLON.Tools.StartPerformanceCounter("Main render");
  76515. });
  76516. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  76517. _this._renderTime.endMonitoring(false);
  76518. BABYLON.Tools.EndPerformanceCounter("Main render");
  76519. });
  76520. }
  76521. else {
  76522. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  76523. this._onBeforeDrawPhaseObserver = null;
  76524. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  76525. this._onAfterDrawPhaseObserver = null;
  76526. }
  76527. },
  76528. enumerable: true,
  76529. configurable: true
  76530. });
  76531. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  76532. /**
  76533. * Gets the perf counter used for frame time capture
  76534. */
  76535. get: function () {
  76536. return this.scene.getEngine()._drawCalls;
  76537. },
  76538. enumerable: true,
  76539. configurable: true
  76540. });
  76541. SceneInstrumentation.prototype.dispose = function () {
  76542. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  76543. this._onAfterRenderObserver = null;
  76544. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  76545. this._onBeforeActiveMeshesEvaluationObserver = null;
  76546. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  76547. this._onAfterActiveMeshesEvaluationObserver = null;
  76548. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  76549. this._onBeforeRenderTargetsRenderObserver = null;
  76550. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  76551. this._onAfterRenderTargetsRenderObserver = null;
  76552. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  76553. this._onBeforeAnimationsObserver = null;
  76554. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  76555. this._onBeforeParticlesRenderingObserver = null;
  76556. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  76557. this._onAfterParticlesRenderingObserver = null;
  76558. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  76559. this._onBeforeSpritesRenderingObserver = null;
  76560. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  76561. this._onAfterSpritesRenderingObserver = null;
  76562. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  76563. this._onBeforeDrawPhaseObserver = null;
  76564. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  76565. this._onAfterDrawPhaseObserver = null;
  76566. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  76567. this._onBeforePhysicsObserver = null;
  76568. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  76569. this._onAfterPhysicsObserver = null;
  76570. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  76571. this._onAfterAnimationsObserver = null;
  76572. this.scene = null;
  76573. };
  76574. return SceneInstrumentation;
  76575. }());
  76576. BABYLON.SceneInstrumentation = SceneInstrumentation;
  76577. })(BABYLON || (BABYLON = {}));
  76578. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  76579. var BABYLON;
  76580. (function (BABYLON) {
  76581. var _TimeToken = /** @class */ (function () {
  76582. function _TimeToken() {
  76583. this._timeElapsedQueryEnded = false;
  76584. }
  76585. return _TimeToken;
  76586. }());
  76587. BABYLON._TimeToken = _TimeToken;
  76588. })(BABYLON || (BABYLON = {}));
  76589. //# sourceMappingURL=babylon.timeToken.js.map
  76590. var BABYLON;
  76591. (function (BABYLON) {
  76592. /**
  76593. * Background material defines definition.
  76594. */
  76595. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  76596. __extends(BackgroundMaterialDefines, _super);
  76597. /**
  76598. * Constructor of the defines.
  76599. */
  76600. function BackgroundMaterialDefines() {
  76601. var _this = _super.call(this) || this;
  76602. /**
  76603. * True if the diffuse texture is in use.
  76604. */
  76605. _this.DIFFUSE = false;
  76606. /**
  76607. * The direct UV channel to use.
  76608. */
  76609. _this.DIFFUSEDIRECTUV = 0;
  76610. /**
  76611. * True if the diffuse texture is in gamma space.
  76612. */
  76613. _this.GAMMADIFFUSE = false;
  76614. /**
  76615. * True if the diffuse texture has opacity in the alpha channel.
  76616. */
  76617. _this.DIFFUSEHASALPHA = false;
  76618. /**
  76619. * True if you want the material to fade to transparent at grazing angle.
  76620. */
  76621. _this.OPACITYFRESNEL = false;
  76622. /**
  76623. * True if an extra blur needs to be added in the reflection.
  76624. */
  76625. _this.REFLECTIONBLUR = false;
  76626. /**
  76627. * True if you want the material to fade to reflection at grazing angle.
  76628. */
  76629. _this.REFLECTIONFRESNEL = false;
  76630. /**
  76631. * True if you want the material to falloff as far as you move away from the scene center.
  76632. */
  76633. _this.REFLECTIONFALLOFF = false;
  76634. /**
  76635. * False if the current Webgl implementation does not support the texture lod extension.
  76636. */
  76637. _this.TEXTURELODSUPPORT = false;
  76638. /**
  76639. * True to ensure the data are premultiplied.
  76640. */
  76641. _this.PREMULTIPLYALPHA = false;
  76642. /**
  76643. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  76644. */
  76645. _this.USERGBCOLOR = false;
  76646. /**
  76647. * True to add noise in order to reduce the banding effect.
  76648. */
  76649. _this.NOISE = false;
  76650. // Image Processing Configuration.
  76651. _this.IMAGEPROCESSING = false;
  76652. _this.VIGNETTE = false;
  76653. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  76654. _this.VIGNETTEBLENDMODEOPAQUE = false;
  76655. _this.TONEMAPPING = false;
  76656. _this.CONTRAST = false;
  76657. _this.COLORCURVES = false;
  76658. _this.COLORGRADING = false;
  76659. _this.COLORGRADING3D = false;
  76660. _this.SAMPLER3DGREENDEPTH = false;
  76661. _this.SAMPLER3DBGRMAP = false;
  76662. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  76663. _this.EXPOSURE = false;
  76664. // Reflection.
  76665. _this.REFLECTION = false;
  76666. _this.REFLECTIONMAP_3D = false;
  76667. _this.REFLECTIONMAP_SPHERICAL = false;
  76668. _this.REFLECTIONMAP_PLANAR = false;
  76669. _this.REFLECTIONMAP_CUBIC = false;
  76670. _this.REFLECTIONMAP_PROJECTION = false;
  76671. _this.REFLECTIONMAP_SKYBOX = false;
  76672. _this.REFLECTIONMAP_EXPLICIT = false;
  76673. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  76674. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  76675. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  76676. _this.INVERTCUBICMAP = false;
  76677. _this.REFLECTIONMAP_OPPOSITEZ = false;
  76678. _this.LODINREFLECTIONALPHA = false;
  76679. _this.GAMMAREFLECTION = false;
  76680. // Default BJS.
  76681. _this.MAINUV1 = false;
  76682. _this.MAINUV2 = false;
  76683. _this.UV1 = false;
  76684. _this.UV2 = false;
  76685. _this.CLIPPLANE = false;
  76686. _this.POINTSIZE = false;
  76687. _this.FOG = false;
  76688. _this.NORMAL = false;
  76689. _this.NUM_BONE_INFLUENCERS = 0;
  76690. _this.BonesPerMesh = 0;
  76691. _this.INSTANCES = false;
  76692. _this.SHADOWFLOAT = false;
  76693. _this.rebuild();
  76694. return _this;
  76695. }
  76696. return BackgroundMaterialDefines;
  76697. }(BABYLON.MaterialDefines));
  76698. /**
  76699. * Background material used to create an efficient environement around your scene.
  76700. */
  76701. var BackgroundMaterial = /** @class */ (function (_super) {
  76702. __extends(BackgroundMaterial, _super);
  76703. /**
  76704. * constructor
  76705. * @param name The name of the material
  76706. * @param scene The scene to add the material to
  76707. */
  76708. function BackgroundMaterial(name, scene) {
  76709. var _this = _super.call(this, name, scene) || this;
  76710. _this.primaryColor = BABYLON.Color3.White();
  76711. _this.primaryLevel = 1;
  76712. _this.secondaryColor = BABYLON.Color3.Gray();
  76713. _this.secondaryLevel = 1;
  76714. _this.tertiaryColor = BABYLON.Color3.Black();
  76715. _this.tertiaryLevel = 1;
  76716. _this.reflectionTexture = null;
  76717. _this.reflectionBlur = 0;
  76718. _this.diffuseTexture = null;
  76719. /**
  76720. * Specify the list of lights casting shadow on the material.
  76721. * All scene shadow lights will be included if null.
  76722. */
  76723. _this._shadowLights = null;
  76724. _this.shadowLights = null;
  76725. _this.shadowBlurScale = 1;
  76726. _this.shadowLevel = 0;
  76727. _this.sceneCenter = BABYLON.Vector3.Zero();
  76728. _this.opacityFresnel = true;
  76729. _this.reflectionFresnel = false;
  76730. _this.reflectionFalloffDistance = 0.0;
  76731. _this.reflectionAmount = 1.0;
  76732. _this.reflectionReflectance0 = 0.05;
  76733. _this.reflectionReflectance90 = 0.5;
  76734. _this.useRGBColor = true;
  76735. _this.enableNoise = false;
  76736. /**
  76737. * Number of Simultaneous lights allowed on the material.
  76738. */
  76739. _this._maxSimultaneousLights = 4;
  76740. _this.maxSimultaneousLights = 4;
  76741. /**
  76742. * Keep track of the image processing observer to allow dispose and replace.
  76743. */
  76744. _this._imageProcessingObserver = null;
  76745. // Temp values kept as cache in the material.
  76746. _this._renderTargets = new BABYLON.SmartArray(16);
  76747. _this._reflectionControls = BABYLON.Vector4.Zero();
  76748. // Setup the default processing configuration to the scene.
  76749. _this._attachImageProcessingConfiguration(null);
  76750. _this.getRenderTargetTextures = function () {
  76751. _this._renderTargets.reset();
  76752. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  76753. _this._renderTargets.push(_this._diffuseTexture);
  76754. }
  76755. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  76756. _this._renderTargets.push(_this._reflectionTexture);
  76757. }
  76758. return _this._renderTargets;
  76759. };
  76760. return _this;
  76761. }
  76762. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  76763. /**
  76764. * Sets the reflection reflectance fresnel values according to the default standard
  76765. * empirically know to work well :-)
  76766. */
  76767. set: function (value) {
  76768. var reflectionWeight = value;
  76769. if (reflectionWeight < 0.5) {
  76770. reflectionWeight = reflectionWeight * 2.0;
  76771. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  76772. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  76773. }
  76774. else {
  76775. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  76776. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  76777. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  76778. }
  76779. },
  76780. enumerable: true,
  76781. configurable: true
  76782. });
  76783. /**
  76784. * Attaches a new image processing configuration to the PBR Material.
  76785. * @param configuration (if null the scene configuration will be use)
  76786. */
  76787. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  76788. var _this = this;
  76789. if (configuration === this._imageProcessingConfiguration) {
  76790. return;
  76791. }
  76792. // Detaches observer.
  76793. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76794. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76795. }
  76796. // Pick the scene configuration if needed.
  76797. if (!configuration) {
  76798. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  76799. }
  76800. else {
  76801. this._imageProcessingConfiguration = configuration;
  76802. }
  76803. // Attaches observer.
  76804. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  76805. _this._markAllSubMeshesAsImageProcessingDirty();
  76806. });
  76807. };
  76808. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  76809. /**
  76810. * Gets the image processing configuration used either in this material.
  76811. */
  76812. get: function () {
  76813. return this._imageProcessingConfiguration;
  76814. },
  76815. /**
  76816. * Sets the Default image processing configuration used either in the this material.
  76817. *
  76818. * If sets to null, the scene one is in use.
  76819. */
  76820. set: function (value) {
  76821. this._attachImageProcessingConfiguration(value);
  76822. // Ensure the effect will be rebuilt.
  76823. this._markAllSubMeshesAsTexturesDirty();
  76824. },
  76825. enumerable: true,
  76826. configurable: true
  76827. });
  76828. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  76829. /**
  76830. * Gets wether the color curves effect is enabled.
  76831. */
  76832. get: function () {
  76833. return this.imageProcessingConfiguration.colorCurvesEnabled;
  76834. },
  76835. /**
  76836. * Sets wether the color curves effect is enabled.
  76837. */
  76838. set: function (value) {
  76839. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  76840. },
  76841. enumerable: true,
  76842. configurable: true
  76843. });
  76844. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  76845. /**
  76846. * Gets wether the color grading effect is enabled.
  76847. */
  76848. get: function () {
  76849. return this.imageProcessingConfiguration.colorGradingEnabled;
  76850. },
  76851. /**
  76852. * Gets wether the color grading effect is enabled.
  76853. */
  76854. set: function (value) {
  76855. this.imageProcessingConfiguration.colorGradingEnabled = value;
  76856. },
  76857. enumerable: true,
  76858. configurable: true
  76859. });
  76860. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  76861. /**
  76862. * Gets wether tonemapping is enabled or not.
  76863. */
  76864. get: function () {
  76865. return this._imageProcessingConfiguration.toneMappingEnabled;
  76866. },
  76867. /**
  76868. * Sets wether tonemapping is enabled or not
  76869. */
  76870. set: function (value) {
  76871. this._imageProcessingConfiguration.toneMappingEnabled = value;
  76872. },
  76873. enumerable: true,
  76874. configurable: true
  76875. });
  76876. ;
  76877. ;
  76878. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  76879. /**
  76880. * The camera exposure used on this material.
  76881. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  76882. * This corresponds to a photographic exposure.
  76883. */
  76884. get: function () {
  76885. return this._imageProcessingConfiguration.exposure;
  76886. },
  76887. /**
  76888. * The camera exposure used on this material.
  76889. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  76890. * This corresponds to a photographic exposure.
  76891. */
  76892. set: function (value) {
  76893. this._imageProcessingConfiguration.exposure = value;
  76894. },
  76895. enumerable: true,
  76896. configurable: true
  76897. });
  76898. ;
  76899. ;
  76900. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  76901. /**
  76902. * Gets The camera contrast used on this material.
  76903. */
  76904. get: function () {
  76905. return this._imageProcessingConfiguration.contrast;
  76906. },
  76907. /**
  76908. * Sets The camera contrast used on this material.
  76909. */
  76910. set: function (value) {
  76911. this._imageProcessingConfiguration.contrast = value;
  76912. },
  76913. enumerable: true,
  76914. configurable: true
  76915. });
  76916. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  76917. /**
  76918. * Gets the Color Grading 2D Lookup Texture.
  76919. */
  76920. get: function () {
  76921. return this._imageProcessingConfiguration.colorGradingTexture;
  76922. },
  76923. /**
  76924. * Sets the Color Grading 2D Lookup Texture.
  76925. */
  76926. set: function (value) {
  76927. this.imageProcessingConfiguration.colorGradingTexture = value;
  76928. },
  76929. enumerable: true,
  76930. configurable: true
  76931. });
  76932. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  76933. /**
  76934. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  76935. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  76936. * 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;
  76937. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  76938. */
  76939. get: function () {
  76940. return this.imageProcessingConfiguration.colorCurves;
  76941. },
  76942. /**
  76943. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  76944. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  76945. * 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;
  76946. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  76947. */
  76948. set: function (value) {
  76949. this.imageProcessingConfiguration.colorCurves = value;
  76950. },
  76951. enumerable: true,
  76952. configurable: true
  76953. });
  76954. /**
  76955. * The entire material has been created in order to prevent overdraw.
  76956. * @returns false
  76957. */
  76958. BackgroundMaterial.prototype.needAlphaTesting = function () {
  76959. return true;
  76960. };
  76961. /**
  76962. * The entire material has been created in order to prevent overdraw.
  76963. * @returns true if blending is enable
  76964. */
  76965. BackgroundMaterial.prototype.needAlphaBlending = function () {
  76966. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  76967. };
  76968. /**
  76969. * Checks wether the material is ready to be rendered for a given mesh.
  76970. * @param mesh The mesh to render
  76971. * @param subMesh The submesh to check against
  76972. * @param useInstances Specify wether or not the material is used with instances
  76973. */
  76974. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  76975. var _this = this;
  76976. if (useInstances === void 0) { useInstances = false; }
  76977. if (subMesh.effect && this.isFrozen) {
  76978. if (this._wasPreviouslyReady) {
  76979. return true;
  76980. }
  76981. }
  76982. if (!subMesh._materialDefines) {
  76983. subMesh._materialDefines = new BackgroundMaterialDefines();
  76984. }
  76985. var scene = this.getScene();
  76986. var defines = subMesh._materialDefines;
  76987. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  76988. if (defines._renderId === scene.getRenderId()) {
  76989. return true;
  76990. }
  76991. }
  76992. var engine = scene.getEngine();
  76993. // Lights
  76994. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  76995. defines._needNormals = true;
  76996. // Textures
  76997. if (defines._areTexturesDirty) {
  76998. defines._needUVs = false;
  76999. if (scene.texturesEnabled) {
  77000. if (scene.getEngine().getCaps().textureLOD) {
  77001. defines.TEXTURELODSUPPORT = true;
  77002. }
  77003. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  77004. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  77005. return false;
  77006. }
  77007. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  77008. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  77009. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  77010. defines.OPACITYFRESNEL = this._opacityFresnel;
  77011. }
  77012. else {
  77013. defines.DIFFUSE = false;
  77014. defines.DIFFUSEHASALPHA = false;
  77015. defines.GAMMADIFFUSE = false;
  77016. defines.OPACITYFRESNEL = false;
  77017. }
  77018. var reflectionTexture = this._reflectionTexture;
  77019. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  77020. if (!reflectionTexture.isReadyOrNotBlocking()) {
  77021. return false;
  77022. }
  77023. defines.REFLECTION = true;
  77024. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  77025. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  77026. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  77027. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  77028. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  77029. defines.INVERTCUBICMAP = true;
  77030. }
  77031. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  77032. switch (reflectionTexture.coordinatesMode) {
  77033. case BABYLON.Texture.CUBIC_MODE:
  77034. case BABYLON.Texture.INVCUBIC_MODE:
  77035. defines.REFLECTIONMAP_CUBIC = true;
  77036. break;
  77037. case BABYLON.Texture.EXPLICIT_MODE:
  77038. defines.REFLECTIONMAP_EXPLICIT = true;
  77039. break;
  77040. case BABYLON.Texture.PLANAR_MODE:
  77041. defines.REFLECTIONMAP_PLANAR = true;
  77042. break;
  77043. case BABYLON.Texture.PROJECTION_MODE:
  77044. defines.REFLECTIONMAP_PROJECTION = true;
  77045. break;
  77046. case BABYLON.Texture.SKYBOX_MODE:
  77047. defines.REFLECTIONMAP_SKYBOX = true;
  77048. break;
  77049. case BABYLON.Texture.SPHERICAL_MODE:
  77050. defines.REFLECTIONMAP_SPHERICAL = true;
  77051. break;
  77052. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  77053. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  77054. break;
  77055. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  77056. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  77057. break;
  77058. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  77059. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  77060. break;
  77061. }
  77062. if (this.reflectionFresnel) {
  77063. defines.REFLECTIONFRESNEL = true;
  77064. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  77065. this._reflectionControls.x = this.reflectionAmount;
  77066. this._reflectionControls.y = this.reflectionReflectance0;
  77067. this._reflectionControls.z = this.reflectionReflectance90;
  77068. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  77069. }
  77070. else {
  77071. defines.REFLECTIONFRESNEL = false;
  77072. defines.REFLECTIONFALLOFF = false;
  77073. }
  77074. }
  77075. else {
  77076. defines.REFLECTION = false;
  77077. defines.REFLECTIONFALLOFF = false;
  77078. defines.REFLECTIONBLUR = false;
  77079. defines.REFLECTIONMAP_3D = false;
  77080. defines.REFLECTIONMAP_SPHERICAL = false;
  77081. defines.REFLECTIONMAP_PLANAR = false;
  77082. defines.REFLECTIONMAP_CUBIC = false;
  77083. defines.REFLECTIONMAP_PROJECTION = false;
  77084. defines.REFLECTIONMAP_SKYBOX = false;
  77085. defines.REFLECTIONMAP_EXPLICIT = false;
  77086. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  77087. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  77088. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  77089. defines.INVERTCUBICMAP = false;
  77090. defines.REFLECTIONMAP_OPPOSITEZ = false;
  77091. defines.LODINREFLECTIONALPHA = false;
  77092. defines.GAMMAREFLECTION = false;
  77093. }
  77094. }
  77095. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  77096. defines.USERGBCOLOR = this._useRGBColor;
  77097. defines.NOISE = this._enableNoise;
  77098. }
  77099. if (defines._areImageProcessingDirty) {
  77100. if (!this._imageProcessingConfiguration.isReady()) {
  77101. return false;
  77102. }
  77103. this._imageProcessingConfiguration.prepareDefines(defines);
  77104. }
  77105. // Misc.
  77106. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  77107. // Values that need to be evaluated on every frame
  77108. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  77109. // Attribs
  77110. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  77111. if (mesh) {
  77112. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  77113. mesh.createNormals(true);
  77114. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  77115. }
  77116. }
  77117. }
  77118. // Get correct effect
  77119. if (defines.isDirty) {
  77120. defines.markAsProcessed();
  77121. scene.resetCachedMaterial();
  77122. // Fallbacks
  77123. var fallbacks = new BABYLON.EffectFallbacks();
  77124. if (defines.FOG) {
  77125. fallbacks.addFallback(0, "FOG");
  77126. }
  77127. if (defines.POINTSIZE) {
  77128. fallbacks.addFallback(1, "POINTSIZE");
  77129. }
  77130. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  77131. if (defines.NUM_BONE_INFLUENCERS > 0) {
  77132. fallbacks.addCPUSkinningFallback(0, mesh);
  77133. }
  77134. //Attributes
  77135. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77136. if (defines.NORMAL) {
  77137. attribs.push(BABYLON.VertexBuffer.NormalKind);
  77138. }
  77139. if (defines.UV1) {
  77140. attribs.push(BABYLON.VertexBuffer.UVKind);
  77141. }
  77142. if (defines.UV2) {
  77143. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77144. }
  77145. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  77146. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  77147. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  77148. "vFogInfos", "vFogColor", "pointSize",
  77149. "vClipPlane", "mBones",
  77150. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  77151. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  77152. "shadowLevel", "alpha",
  77153. "vBackgroundCenter", "vReflectionControl",
  77154. "vDiffuseInfos", "diffuseMatrix",
  77155. ];
  77156. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  77157. var uniformBuffers = ["Material", "Scene"];
  77158. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  77159. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  77160. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  77161. uniformsNames: uniforms,
  77162. uniformBuffersNames: uniformBuffers,
  77163. samplers: samplers,
  77164. defines: defines,
  77165. maxSimultaneousLights: this._maxSimultaneousLights
  77166. });
  77167. var onCompiled = function (effect) {
  77168. if (_this.onCompiled) {
  77169. _this.onCompiled(effect);
  77170. }
  77171. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  77172. };
  77173. var join = defines.toString();
  77174. subMesh.setEffect(scene.getEngine().createEffect("background", {
  77175. attributes: attribs,
  77176. uniformsNames: uniforms,
  77177. uniformBuffersNames: uniformBuffers,
  77178. samplers: samplers,
  77179. defines: join,
  77180. fallbacks: fallbacks,
  77181. onCompiled: onCompiled,
  77182. onError: this.onError,
  77183. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  77184. }, engine), defines);
  77185. this.buildUniformLayout();
  77186. }
  77187. if (!subMesh.effect || !subMesh.effect.isReady()) {
  77188. return false;
  77189. }
  77190. defines._renderId = scene.getRenderId();
  77191. this._wasPreviouslyReady = true;
  77192. return true;
  77193. };
  77194. /**
  77195. * Build the uniform buffer used in the material.
  77196. */
  77197. BackgroundMaterial.prototype.buildUniformLayout = function () {
  77198. // Order is important !
  77199. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  77200. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  77201. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  77202. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  77203. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  77204. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  77205. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  77206. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  77207. this._uniformBuffer.addUniform("pointSize", 1);
  77208. this._uniformBuffer.addUniform("shadowLevel", 1);
  77209. this._uniformBuffer.addUniform("alpha", 1);
  77210. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  77211. this._uniformBuffer.addUniform("vReflectionControl", 4);
  77212. this._uniformBuffer.create();
  77213. };
  77214. /**
  77215. * Unbind the material.
  77216. */
  77217. BackgroundMaterial.prototype.unbind = function () {
  77218. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  77219. this._uniformBuffer.setTexture("diffuseSampler", null);
  77220. }
  77221. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  77222. this._uniformBuffer.setTexture("reflectionSampler", null);
  77223. }
  77224. _super.prototype.unbind.call(this);
  77225. };
  77226. /**
  77227. * Bind only the world matrix to the material.
  77228. * @param world The world matrix to bind.
  77229. */
  77230. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  77231. this._activeEffect.setMatrix("world", world);
  77232. };
  77233. /**
  77234. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  77235. * @param world The world matrix to bind.
  77236. * @param subMesh The submesh to bind for.
  77237. */
  77238. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  77239. var scene = this.getScene();
  77240. var defines = subMesh._materialDefines;
  77241. if (!defines) {
  77242. return;
  77243. }
  77244. var effect = subMesh.effect;
  77245. if (!effect) {
  77246. return;
  77247. }
  77248. this._activeEffect = effect;
  77249. // Matrices
  77250. this.bindOnlyWorldMatrix(world);
  77251. // Bones
  77252. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  77253. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  77254. if (mustRebind) {
  77255. this._uniformBuffer.bindToEffect(effect, "Material");
  77256. this.bindViewProjection(effect);
  77257. var reflectionTexture = this._reflectionTexture;
  77258. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  77259. // Texture uniforms
  77260. if (scene.texturesEnabled) {
  77261. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  77262. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  77263. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  77264. }
  77265. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  77266. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  77267. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  77268. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  77269. }
  77270. }
  77271. if (this.shadowLevel > 0) {
  77272. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  77273. }
  77274. this._uniformBuffer.updateFloat("alpha", this.alpha);
  77275. // Point size
  77276. if (this.pointsCloud) {
  77277. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  77278. }
  77279. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  77280. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  77281. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  77282. }
  77283. // Textures
  77284. if (scene.texturesEnabled) {
  77285. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  77286. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  77287. }
  77288. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  77289. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  77290. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  77291. }
  77292. else if (!defines.REFLECTIONBLUR) {
  77293. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  77294. }
  77295. else {
  77296. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  77297. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  77298. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  77299. }
  77300. if (defines.REFLECTIONFRESNEL) {
  77301. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  77302. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  77303. }
  77304. }
  77305. }
  77306. // Clip plane
  77307. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  77308. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  77309. }
  77310. if (mustRebind || !this.isFrozen) {
  77311. if (scene.lightsEnabled) {
  77312. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  77313. }
  77314. // View
  77315. this.bindView(effect);
  77316. // Fog
  77317. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  77318. // image processing
  77319. this._imageProcessingConfiguration.bind(this._activeEffect);
  77320. }
  77321. this._uniformBuffer.update();
  77322. this._afterBind(mesh);
  77323. };
  77324. /**
  77325. * Dispose the material.
  77326. * @forceDisposeEffect Force disposal of the associated effect.
  77327. * @forceDisposeTextures Force disposal of the associated textures.
  77328. */
  77329. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  77330. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  77331. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  77332. if (forceDisposeTextures) {
  77333. if (this.diffuseTexture) {
  77334. this.diffuseTexture.dispose();
  77335. }
  77336. if (this.reflectionTexture) {
  77337. this.reflectionTexture.dispose();
  77338. }
  77339. }
  77340. this._renderTargets.dispose();
  77341. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77342. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77343. }
  77344. _super.prototype.dispose.call(this, forceDisposeEffect);
  77345. };
  77346. /**
  77347. * Clones the material.
  77348. * @name The cloned name.
  77349. * @returns The cloned material.
  77350. */
  77351. BackgroundMaterial.prototype.clone = function (name) {
  77352. var _this = this;
  77353. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  77354. };
  77355. /**
  77356. * Serializes the current material to its JSON representation.
  77357. * @returns The JSON representation.
  77358. */
  77359. BackgroundMaterial.prototype.serialize = function () {
  77360. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77361. serializationObject.customType = "BABYLON.BackgroundMaterial";
  77362. return serializationObject;
  77363. };
  77364. /**
  77365. * Gets the class name of the material
  77366. * @returns "BackgroundMaterial"
  77367. */
  77368. BackgroundMaterial.prototype.getClassName = function () {
  77369. return "BackgroundMaterial";
  77370. };
  77371. /**
  77372. * Parse a JSON input to create back a background material.
  77373. * @param source
  77374. * @param scene
  77375. * @param rootUrl
  77376. * @returns the instantiated BackgroundMaterial.
  77377. */
  77378. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  77379. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  77380. };
  77381. /**
  77382. * Standard reflectance value at parallel view angle.
  77383. */
  77384. BackgroundMaterial.standardReflectance0 = 0.05;
  77385. /**
  77386. * Standard reflectance value at grazing angle.
  77387. */
  77388. BackgroundMaterial.standardReflectance90 = 0.5;
  77389. __decorate([
  77390. BABYLON.serializeAsColor3()
  77391. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  77392. __decorate([
  77393. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  77394. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  77395. __decorate([
  77396. BABYLON.serialize()
  77397. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  77398. __decorate([
  77399. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  77400. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  77401. __decorate([
  77402. BABYLON.serializeAsColor3()
  77403. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  77404. __decorate([
  77405. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  77406. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  77407. __decorate([
  77408. BABYLON.serialize()
  77409. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  77410. __decorate([
  77411. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  77412. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  77413. __decorate([
  77414. BABYLON.serializeAsColor3()
  77415. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  77416. __decorate([
  77417. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  77418. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  77419. __decorate([
  77420. BABYLON.serialize()
  77421. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  77422. __decorate([
  77423. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  77424. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  77425. __decorate([
  77426. BABYLON.serializeAsTexture()
  77427. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  77428. __decorate([
  77429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77430. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  77431. __decorate([
  77432. BABYLON.serialize()
  77433. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  77434. __decorate([
  77435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77436. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  77437. __decorate([
  77438. BABYLON.serializeAsTexture()
  77439. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  77440. __decorate([
  77441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77442. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  77443. __decorate([
  77444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77445. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  77446. __decorate([
  77447. BABYLON.serialize()
  77448. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  77449. __decorate([
  77450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77451. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  77452. __decorate([
  77453. BABYLON.serialize()
  77454. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  77455. __decorate([
  77456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77457. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  77458. __decorate([
  77459. BABYLON.serializeAsVector3()
  77460. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  77461. __decorate([
  77462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77463. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  77464. __decorate([
  77465. BABYLON.serialize()
  77466. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  77467. __decorate([
  77468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77469. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  77470. __decorate([
  77471. BABYLON.serialize()
  77472. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  77473. __decorate([
  77474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77475. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  77476. __decorate([
  77477. BABYLON.serialize()
  77478. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  77479. __decorate([
  77480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77481. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  77482. __decorate([
  77483. BABYLON.serialize()
  77484. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  77485. __decorate([
  77486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77487. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  77488. __decorate([
  77489. BABYLON.serialize()
  77490. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  77491. __decorate([
  77492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77493. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  77494. __decorate([
  77495. BABYLON.serialize()
  77496. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  77497. __decorate([
  77498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77499. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  77500. __decorate([
  77501. BABYLON.serialize()
  77502. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  77503. __decorate([
  77504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77505. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  77506. __decorate([
  77507. BABYLON.serialize()
  77508. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  77509. __decorate([
  77510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77511. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  77512. __decorate([
  77513. BABYLON.serialize()
  77514. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  77515. __decorate([
  77516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77517. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  77518. __decorate([
  77519. BABYLON.serializeAsImageProcessingConfiguration()
  77520. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  77521. return BackgroundMaterial;
  77522. }(BABYLON.PushMaterial));
  77523. BABYLON.BackgroundMaterial = BackgroundMaterial;
  77524. })(BABYLON || (BABYLON = {}));
  77525. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  77526. var __assign = (this && this.__assign) || Object.assign || function(t) {
  77527. for (var s, i = 1, n = arguments.length; i < n; i++) {
  77528. s = arguments[i];
  77529. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  77530. t[p] = s[p];
  77531. }
  77532. return t;
  77533. };
  77534. var BABYLON;
  77535. (function (BABYLON) {
  77536. /**
  77537. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  77538. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  77539. * It also helps with the default setup of your imageProcessing configuration.
  77540. */
  77541. var EnvironmentHelper = /** @class */ (function () {
  77542. /**
  77543. * constructor
  77544. * @param options
  77545. * @param scene The scene to add the material to
  77546. */
  77547. function EnvironmentHelper(options, scene) {
  77548. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  77549. this._scene = scene;
  77550. this._setupBackground();
  77551. this._setupImageProcessing();
  77552. }
  77553. /**
  77554. * Creates the default options for the helper.
  77555. */
  77556. EnvironmentHelper._getDefaultOptions = function () {
  77557. return {
  77558. createGround: true,
  77559. groundSize: 15,
  77560. groundTexture: this._groundTextureCDNUrl,
  77561. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  77562. groundOpacity: 0.9,
  77563. enableGroundShadow: true,
  77564. groundShadowLevel: 0.5,
  77565. enableGroundMirror: false,
  77566. groundMirrorSizeRatio: 0.3,
  77567. groundMirrorBlurKernel: 64,
  77568. groundMirrorAmount: 1,
  77569. groundMirrorFresnelWeight: 1,
  77570. groundMirrorFallOffDistance: 0,
  77571. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  77572. createSkybox: true,
  77573. skyboxSize: 20,
  77574. skyboxTexture: this._skyboxTextureCDNUrl,
  77575. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  77576. backgroundYRotation: 0,
  77577. sizeAuto: true,
  77578. rootPosition: BABYLON.Vector3.Zero(),
  77579. setupImageProcessing: true,
  77580. environmentTexture: this._environmentTextureCDNUrl,
  77581. cameraExposure: 0.8,
  77582. cameraContrast: 1.2,
  77583. toneMappingEnabled: true,
  77584. };
  77585. };
  77586. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  77587. /**
  77588. * Gets the root mesh created by the helper.
  77589. */
  77590. get: function () {
  77591. return this._rootMesh;
  77592. },
  77593. enumerable: true,
  77594. configurable: true
  77595. });
  77596. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  77597. /**
  77598. * Gets the skybox created by the helper.
  77599. */
  77600. get: function () {
  77601. return this._skybox;
  77602. },
  77603. enumerable: true,
  77604. configurable: true
  77605. });
  77606. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  77607. /**
  77608. * Gets the skybox texture created by the helper.
  77609. */
  77610. get: function () {
  77611. return this._skyboxTexture;
  77612. },
  77613. enumerable: true,
  77614. configurable: true
  77615. });
  77616. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  77617. /**
  77618. * Gets the skybox material created by the helper.
  77619. */
  77620. get: function () {
  77621. return this._skyboxMaterial;
  77622. },
  77623. enumerable: true,
  77624. configurable: true
  77625. });
  77626. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  77627. /**
  77628. * Gets the ground mesh created by the helper.
  77629. */
  77630. get: function () {
  77631. return this._ground;
  77632. },
  77633. enumerable: true,
  77634. configurable: true
  77635. });
  77636. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  77637. /**
  77638. * Gets the ground texture created by the helper.
  77639. */
  77640. get: function () {
  77641. return this._groundTexture;
  77642. },
  77643. enumerable: true,
  77644. configurable: true
  77645. });
  77646. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  77647. /**
  77648. * Gets the ground mirror created by the helper.
  77649. */
  77650. get: function () {
  77651. return this._groundMirror;
  77652. },
  77653. enumerable: true,
  77654. configurable: true
  77655. });
  77656. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  77657. /**
  77658. * Gets the ground mirror render list to helps pushing the meshes
  77659. * you wish in the ground reflection.
  77660. */
  77661. get: function () {
  77662. if (this._groundMirror) {
  77663. return this._groundMirror.renderList;
  77664. }
  77665. return null;
  77666. },
  77667. enumerable: true,
  77668. configurable: true
  77669. });
  77670. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  77671. /**
  77672. * Gets the ground material created by the helper.
  77673. */
  77674. get: function () {
  77675. return this._groundMaterial;
  77676. },
  77677. enumerable: true,
  77678. configurable: true
  77679. });
  77680. /**
  77681. * Updates the background according to the new options
  77682. * @param options
  77683. */
  77684. EnvironmentHelper.prototype.updateOptions = function (options) {
  77685. var newOptions = __assign({}, this._options, options);
  77686. if (this._ground && !newOptions.createGround) {
  77687. this._ground.dispose();
  77688. this._ground = null;
  77689. }
  77690. if (this._groundMaterial && !newOptions.createGround) {
  77691. this._groundMaterial.dispose();
  77692. this._groundMaterial = null;
  77693. }
  77694. if (this._options.groundTexture && !newOptions.groundTexture && this._groundTexture) {
  77695. this._groundTexture.dispose();
  77696. this._groundTexture = null;
  77697. }
  77698. if (this._skybox && !newOptions.createSkybox) {
  77699. this._skybox.dispose();
  77700. this._skybox = null;
  77701. }
  77702. if (this._skyboxMaterial && !newOptions.createSkybox) {
  77703. this._skyboxMaterial.dispose();
  77704. this._skyboxMaterial = null;
  77705. }
  77706. if (this._options.skyboxTexture && !newOptions.skyboxTexture && this._skyboxTexture) {
  77707. this._skyboxTexture.dispose();
  77708. this._skyboxTexture = null;
  77709. }
  77710. if (this._groundMirror && !newOptions.enableGroundMirror) {
  77711. this._groundMirror.dispose();
  77712. this._groundMirror = null;
  77713. }
  77714. if (this._options.environmentTexture && !newOptions.environmentTexture && this._scene.environmentTexture) {
  77715. this._scene.environmentTexture.dispose();
  77716. }
  77717. this._options = newOptions;
  77718. this._setupBackground();
  77719. this._setupImageProcessing();
  77720. };
  77721. /**
  77722. * Sets the primary color of all the available elements.
  77723. * @param color
  77724. */
  77725. EnvironmentHelper.prototype.setMainColor = function (color) {
  77726. if (this.groundMaterial) {
  77727. this.groundMaterial.primaryColor = color;
  77728. }
  77729. if (this.skyboxMaterial) {
  77730. this.skyboxMaterial.primaryColor = color;
  77731. }
  77732. if (this.groundMirror) {
  77733. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  77734. }
  77735. };
  77736. /**
  77737. * Setup the image processing according to the specified options.
  77738. */
  77739. EnvironmentHelper.prototype._setupImageProcessing = function () {
  77740. if (this._options.setupImageProcessing) {
  77741. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  77742. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  77743. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  77744. this._setupEnvironmentTexture();
  77745. }
  77746. };
  77747. /**
  77748. * Setup the environment texture according to the specified options.
  77749. */
  77750. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  77751. if (this._scene.environmentTexture) {
  77752. return;
  77753. }
  77754. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  77755. this._scene.environmentTexture = this._options.environmentTexture;
  77756. return;
  77757. }
  77758. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  77759. this._scene.environmentTexture = environmentTexture;
  77760. };
  77761. /**
  77762. * Setup the background according to the specified options.
  77763. */
  77764. EnvironmentHelper.prototype._setupBackground = function () {
  77765. if (!this._rootMesh) {
  77766. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  77767. }
  77768. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  77769. var sceneSize = this._getSceneSize();
  77770. if (this._options.createGround) {
  77771. this._setupGround(sceneSize);
  77772. this._setupGroundMaterial();
  77773. this._setupGroundDiffuseTexture();
  77774. if (this._options.enableGroundMirror) {
  77775. this._setupGroundMirrorTexture(sceneSize);
  77776. }
  77777. this._setupMirrorInGroundMaterial();
  77778. }
  77779. if (this._options.createSkybox) {
  77780. this._setupSkybox(sceneSize);
  77781. this._setupSkyboxMaterial();
  77782. this._setupSkyboxReflectionTexture();
  77783. }
  77784. this._rootMesh.position.x = sceneSize.rootPosition.x;
  77785. this._rootMesh.position.z = sceneSize.rootPosition.z;
  77786. this._rootMesh.position.y = sceneSize.rootPosition.y;
  77787. };
  77788. /**
  77789. * Get the scene sizes according to the setup.
  77790. */
  77791. EnvironmentHelper.prototype._getSceneSize = function () {
  77792. var groundSize = this._options.groundSize;
  77793. var skyboxSize = this._options.skyboxSize;
  77794. var rootPosition = this._options.rootPosition;
  77795. var sceneExtends = this._scene.getWorldExtends();
  77796. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  77797. var bias = 0.0001;
  77798. if (this._options.sizeAuto) {
  77799. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  77800. this._scene.activeCamera.upperRadiusLimit) {
  77801. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  77802. }
  77803. if (this._scene.activeCamera) {
  77804. bias = (this._scene.activeCamera.maxZ - this._scene.activeCamera.minZ) / 10000;
  77805. }
  77806. var sceneDiagonalLenght = sceneDiagonal.length();
  77807. if (sceneDiagonalLenght > groundSize) {
  77808. groundSize = sceneDiagonalLenght * 2;
  77809. }
  77810. // 10 % bigger.
  77811. groundSize *= 1.1;
  77812. skyboxSize *= 1.5;
  77813. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  77814. rootPosition.y = sceneExtends.min.y - bias;
  77815. }
  77816. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  77817. };
  77818. /**
  77819. * Setup the ground according to the specified options.
  77820. */
  77821. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  77822. if (!this._ground) {
  77823. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  77824. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  77825. this._ground.parent = this._rootMesh;
  77826. }
  77827. this._ground.receiveShadows = this._options.enableGroundShadow;
  77828. };
  77829. /**
  77830. * Setup the ground material according to the specified options.
  77831. */
  77832. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  77833. if (!this._groundMaterial) {
  77834. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  77835. }
  77836. this._groundMaterial.alpha = this._options.groundOpacity;
  77837. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  77838. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  77839. this._groundMaterial.primaryLevel = 1;
  77840. this._groundMaterial.primaryColor = this._options.groundColor;
  77841. this._groundMaterial.secondaryLevel = 0;
  77842. this._groundMaterial.tertiaryLevel = 0;
  77843. this._groundMaterial.useRGBColor = false;
  77844. this._groundMaterial.enableNoise = true;
  77845. if (this._ground) {
  77846. this._ground.material = this._groundMaterial;
  77847. }
  77848. };
  77849. /**
  77850. * Setup the ground diffuse texture according to the specified options.
  77851. */
  77852. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  77853. if (!this._groundMaterial) {
  77854. return;
  77855. }
  77856. if (this._groundTexture) {
  77857. return;
  77858. }
  77859. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  77860. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  77861. return;
  77862. }
  77863. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  77864. diffuseTexture.gammaSpace = false;
  77865. diffuseTexture.hasAlpha = true;
  77866. this._groundMaterial.diffuseTexture = diffuseTexture;
  77867. };
  77868. /**
  77869. * Setup the ground mirror texture according to the specified options.
  77870. */
  77871. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  77872. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77873. if (!this._groundMirror) {
  77874. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  77875. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  77876. this._groundMirror.anisotropicFilteringLevel = 1;
  77877. this._groundMirror.wrapU = wrapping;
  77878. this._groundMirror.wrapV = wrapping;
  77879. this._groundMirror.gammaSpace = false;
  77880. if (this._groundMirror.renderList) {
  77881. for (var i = 0; i < this._scene.meshes.length; i++) {
  77882. var mesh = this._scene.meshes[i];
  77883. if (mesh !== this._ground &&
  77884. mesh !== this._skybox &&
  77885. mesh !== this._rootMesh) {
  77886. this._groundMirror.renderList.push(mesh);
  77887. }
  77888. }
  77889. }
  77890. }
  77891. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  77892. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  77893. };
  77894. /**
  77895. * Setup the ground to receive the mirror texture.
  77896. */
  77897. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  77898. if (this._groundMaterial) {
  77899. this._groundMaterial.reflectionTexture = this._groundMirror;
  77900. this._groundMaterial.reflectionFresnel = true;
  77901. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  77902. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  77903. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  77904. }
  77905. };
  77906. /**
  77907. * Setup the skybox according to the specified options.
  77908. */
  77909. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  77910. if (!this._skybox) {
  77911. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  77912. }
  77913. this._skybox.parent = this._rootMesh;
  77914. };
  77915. /**
  77916. * Setup the skybox material according to the specified options.
  77917. */
  77918. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  77919. if (!this._skybox) {
  77920. return;
  77921. }
  77922. if (!this._skyboxMaterial) {
  77923. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  77924. }
  77925. this._skyboxMaterial.useRGBColor = false;
  77926. this._skyboxMaterial.primaryLevel = 1;
  77927. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  77928. this._skyboxMaterial.secondaryLevel = 0;
  77929. this._skyboxMaterial.tertiaryLevel = 0;
  77930. this._skyboxMaterial.enableNoise = true;
  77931. this._skybox.material = this._skyboxMaterial;
  77932. };
  77933. /**
  77934. * Setup the skybox reflection texture according to the specified options.
  77935. */
  77936. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  77937. if (!this._skyboxMaterial) {
  77938. return;
  77939. }
  77940. if (this._skyboxTexture) {
  77941. return;
  77942. }
  77943. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  77944. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  77945. return;
  77946. }
  77947. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  77948. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  77949. this._skyboxTexture.gammaSpace = false;
  77950. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  77951. };
  77952. /**
  77953. * Dispose all the elements created by the Helper.
  77954. */
  77955. EnvironmentHelper.prototype.dispose = function () {
  77956. if (this._groundMaterial) {
  77957. this._groundMaterial.dispose(true, true);
  77958. }
  77959. if (this._skyboxMaterial) {
  77960. this._skyboxMaterial.dispose(true, true);
  77961. }
  77962. this._rootMesh.dispose(true);
  77963. };
  77964. /**
  77965. * Default ground texture URL.
  77966. */
  77967. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  77968. /**
  77969. * Default skybox texture URL.
  77970. */
  77971. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  77972. /**
  77973. * Default environment texture URL.
  77974. */
  77975. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  77976. return EnvironmentHelper;
  77977. }());
  77978. BABYLON.EnvironmentHelper = EnvironmentHelper;
  77979. })(BABYLON || (BABYLON = {}));
  77980. //# sourceMappingURL=babylon.environmentHelper.js.map
  77981. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture2D(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  77982. 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.rgb+=mix(-0.5/255.0,0.5/255.0,rand);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  77983. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  77984. var BABYLON;
  77985. (function (BABYLON) {
  77986. var GridMaterialDefines = /** @class */ (function (_super) {
  77987. __extends(GridMaterialDefines, _super);
  77988. function GridMaterialDefines() {
  77989. var _this = _super.call(this) || this;
  77990. _this.TRANSPARENT = false;
  77991. _this.FOG = false;
  77992. _this.PREMULTIPLYALPHA = false;
  77993. _this.rebuild();
  77994. return _this;
  77995. }
  77996. return GridMaterialDefines;
  77997. }(BABYLON.MaterialDefines));
  77998. /**
  77999. * The grid materials allows you to wrap any shape with a grid.
  78000. * Colors are customizable.
  78001. */
  78002. var GridMaterial = /** @class */ (function (_super) {
  78003. __extends(GridMaterial, _super);
  78004. /**
  78005. * constructor
  78006. * @param name The name given to the material in order to identify it afterwards.
  78007. * @param scene The scene the material is used in.
  78008. */
  78009. function GridMaterial(name, scene) {
  78010. var _this = _super.call(this, name, scene) || this;
  78011. /**
  78012. * Main color of the grid (e.g. between lines)
  78013. */
  78014. _this.mainColor = BABYLON.Color3.Black();
  78015. /**
  78016. * Color of the grid lines.
  78017. */
  78018. _this.lineColor = BABYLON.Color3.Teal();
  78019. /**
  78020. * The scale of the grid compared to unit.
  78021. */
  78022. _this.gridRatio = 1.0;
  78023. /**
  78024. * Allows setting an offset for the grid lines.
  78025. */
  78026. _this.gridOffset = BABYLON.Vector3.Zero();
  78027. /**
  78028. * The frequency of thicker lines.
  78029. */
  78030. _this.majorUnitFrequency = 10;
  78031. /**
  78032. * The visibility of minor units in the grid.
  78033. */
  78034. _this.minorUnitVisibility = 0.33;
  78035. /**
  78036. * The grid opacity outside of the lines.
  78037. */
  78038. _this.opacity = 1.0;
  78039. /**
  78040. * Determine RBG output is premultiplied by alpha value.
  78041. */
  78042. _this.preMultiplyAlpha = false;
  78043. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  78044. return _this;
  78045. }
  78046. /**
  78047. * Returns wehter or not the grid requires alpha blending.
  78048. */
  78049. GridMaterial.prototype.needAlphaBlending = function () {
  78050. return this.opacity < 1.0;
  78051. };
  78052. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  78053. return this.needAlphaBlending();
  78054. };
  78055. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  78056. if (this.isFrozen) {
  78057. if (this._wasPreviouslyReady && subMesh.effect) {
  78058. return true;
  78059. }
  78060. }
  78061. if (!subMesh._materialDefines) {
  78062. subMesh._materialDefines = new GridMaterialDefines();
  78063. }
  78064. var defines = subMesh._materialDefines;
  78065. var scene = this.getScene();
  78066. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  78067. if (this._renderId === scene.getRenderId()) {
  78068. return true;
  78069. }
  78070. }
  78071. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  78072. defines.TRANSPARENT = !defines.TRANSPARENT;
  78073. defines.markAsUnprocessed();
  78074. }
  78075. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  78076. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  78077. defines.markAsUnprocessed();
  78078. }
  78079. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  78080. // Get correct effect
  78081. if (defines.isDirty) {
  78082. defines.markAsProcessed();
  78083. scene.resetCachedMaterial();
  78084. // Attributes
  78085. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78086. // Defines
  78087. var join = defines.toString();
  78088. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  78089. }
  78090. if (!subMesh.effect || !subMesh.effect.isReady()) {
  78091. return false;
  78092. }
  78093. this._renderId = scene.getRenderId();
  78094. this._wasPreviouslyReady = true;
  78095. return true;
  78096. };
  78097. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  78098. var scene = this.getScene();
  78099. var defines = subMesh._materialDefines;
  78100. if (!defines) {
  78101. return;
  78102. }
  78103. var effect = subMesh.effect;
  78104. if (!effect) {
  78105. return;
  78106. }
  78107. this._activeEffect = effect;
  78108. // Matrices
  78109. this.bindOnlyWorldMatrix(world);
  78110. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  78111. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  78112. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  78113. // Uniforms
  78114. if (this._mustRebind(scene, effect)) {
  78115. this._activeEffect.setColor3("mainColor", this.mainColor);
  78116. this._activeEffect.setColor3("lineColor", this.lineColor);
  78117. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  78118. this._gridControl.x = this.gridRatio;
  78119. this._gridControl.y = Math.round(this.majorUnitFrequency);
  78120. this._gridControl.z = this.minorUnitVisibility;
  78121. this._gridControl.w = this.opacity;
  78122. this._activeEffect.setVector4("gridControl", this._gridControl);
  78123. }
  78124. // Fog
  78125. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  78126. this._afterBind(mesh, this._activeEffect);
  78127. };
  78128. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  78129. _super.prototype.dispose.call(this, forceDisposeEffect);
  78130. };
  78131. GridMaterial.prototype.clone = function (name) {
  78132. var _this = this;
  78133. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  78134. };
  78135. GridMaterial.prototype.serialize = function () {
  78136. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78137. serializationObject.customType = "BABYLON.GridMaterial";
  78138. return serializationObject;
  78139. };
  78140. GridMaterial.prototype.getClassName = function () {
  78141. return "GridMaterial";
  78142. };
  78143. GridMaterial.Parse = function (source, scene, rootUrl) {
  78144. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  78145. };
  78146. __decorate([
  78147. BABYLON.serializeAsColor3()
  78148. ], GridMaterial.prototype, "mainColor", void 0);
  78149. __decorate([
  78150. BABYLON.serializeAsColor3()
  78151. ], GridMaterial.prototype, "lineColor", void 0);
  78152. __decorate([
  78153. BABYLON.serialize()
  78154. ], GridMaterial.prototype, "gridRatio", void 0);
  78155. __decorate([
  78156. BABYLON.serializeAsColor3()
  78157. ], GridMaterial.prototype, "gridOffset", void 0);
  78158. __decorate([
  78159. BABYLON.serialize()
  78160. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  78161. __decorate([
  78162. BABYLON.serialize()
  78163. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  78164. __decorate([
  78165. BABYLON.serialize()
  78166. ], GridMaterial.prototype, "opacity", void 0);
  78167. __decorate([
  78168. BABYLON.serialize()
  78169. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  78170. return GridMaterial;
  78171. }(BABYLON.PushMaterial));
  78172. BABYLON.GridMaterial = GridMaterial;
  78173. })(BABYLON || (BABYLON = {}));
  78174. //# sourceMappingURL=babylon.gridmaterial.js.map
  78175. 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}";
  78176. 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}";
  78177. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  78178. var BABYLON;
  78179. (function (BABYLON) {
  78180. var GLTFLoaderCoordinateSystemMode;
  78181. (function (GLTFLoaderCoordinateSystemMode) {
  78182. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  78183. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  78184. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  78185. // The glTF right-handed data is not transformed in any form and is loaded directly.
  78186. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  78187. // Sets the useRightHandedSystem flag on the scene.
  78188. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  78189. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  78190. var GLTFFileLoader = /** @class */ (function () {
  78191. function GLTFFileLoader() {
  78192. // V2 options
  78193. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  78194. this.compileMaterials = false;
  78195. this.compileShadowGenerators = false;
  78196. this.useClipPlane = false;
  78197. this.name = "gltf";
  78198. this.extensions = {
  78199. ".gltf": { isBinary: false },
  78200. ".glb": { isBinary: true }
  78201. };
  78202. }
  78203. GLTFFileLoader.prototype.dispose = function () {
  78204. if (this._loader) {
  78205. this._loader.dispose();
  78206. }
  78207. };
  78208. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  78209. try {
  78210. var loaderData = GLTFFileLoader._parse(data);
  78211. if (this.onParsed) {
  78212. this.onParsed(loaderData);
  78213. }
  78214. this._loader = this._getLoader(loaderData);
  78215. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  78216. }
  78217. catch (e) {
  78218. onError(e.message);
  78219. }
  78220. };
  78221. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  78222. try {
  78223. var loaderData = GLTFFileLoader._parse(data);
  78224. if (this.onParsed) {
  78225. this.onParsed(loaderData);
  78226. }
  78227. this._loader = this._getLoader(loaderData);
  78228. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  78229. }
  78230. catch (e) {
  78231. onError(e.message);
  78232. }
  78233. };
  78234. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  78235. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  78236. };
  78237. GLTFFileLoader.prototype.createPlugin = function () {
  78238. return new GLTFFileLoader();
  78239. };
  78240. GLTFFileLoader._parse = function (data) {
  78241. if (data instanceof ArrayBuffer) {
  78242. return GLTFFileLoader._parseBinary(data);
  78243. }
  78244. return {
  78245. json: JSON.parse(data),
  78246. bin: null
  78247. };
  78248. };
  78249. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  78250. var loaderVersion = { major: 2, minor: 0 };
  78251. var asset = loaderData.json.asset || {};
  78252. var version = GLTFFileLoader._parseVersion(asset.version);
  78253. if (!version) {
  78254. throw new Error("Invalid version: " + asset.version);
  78255. }
  78256. if (asset.minVersion !== undefined) {
  78257. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  78258. if (!minVersion) {
  78259. throw new Error("Invalid minimum version: " + asset.minVersion);
  78260. }
  78261. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  78262. throw new Error("Incompatible minimum version: " + asset.minVersion);
  78263. }
  78264. }
  78265. var createLoaders = {
  78266. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  78267. 2: GLTFFileLoader.CreateGLTFLoaderV2
  78268. };
  78269. var createLoader = createLoaders[version.major];
  78270. if (!createLoader) {
  78271. throw new Error("Unsupported version: " + asset.version);
  78272. }
  78273. return createLoader(this);
  78274. };
  78275. GLTFFileLoader._parseBinary = function (data) {
  78276. var Binary = {
  78277. Magic: 0x46546C67
  78278. };
  78279. var binaryReader = new BinaryReader(data);
  78280. var magic = binaryReader.readUint32();
  78281. if (magic !== Binary.Magic) {
  78282. throw new Error("Unexpected magic: " + magic);
  78283. }
  78284. var version = binaryReader.readUint32();
  78285. switch (version) {
  78286. case 1: return GLTFFileLoader._parseV1(binaryReader);
  78287. case 2: return GLTFFileLoader._parseV2(binaryReader);
  78288. }
  78289. throw new Error("Unsupported version: " + version);
  78290. };
  78291. GLTFFileLoader._parseV1 = function (binaryReader) {
  78292. var ContentFormat = {
  78293. JSON: 0
  78294. };
  78295. var length = binaryReader.readUint32();
  78296. if (length != binaryReader.getLength()) {
  78297. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  78298. }
  78299. var contentLength = binaryReader.readUint32();
  78300. var contentFormat = binaryReader.readUint32();
  78301. var content;
  78302. switch (contentFormat) {
  78303. case ContentFormat.JSON: {
  78304. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  78305. break;
  78306. }
  78307. default: {
  78308. throw new Error("Unexpected content format: " + contentFormat);
  78309. }
  78310. }
  78311. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  78312. var body = binaryReader.readUint8Array(bytesRemaining);
  78313. return {
  78314. json: content,
  78315. bin: body
  78316. };
  78317. };
  78318. GLTFFileLoader._parseV2 = function (binaryReader) {
  78319. var ChunkFormat = {
  78320. JSON: 0x4E4F534A,
  78321. BIN: 0x004E4942
  78322. };
  78323. var length = binaryReader.readUint32();
  78324. if (length !== binaryReader.getLength()) {
  78325. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  78326. }
  78327. // JSON chunk
  78328. var chunkLength = binaryReader.readUint32();
  78329. var chunkFormat = binaryReader.readUint32();
  78330. if (chunkFormat !== ChunkFormat.JSON) {
  78331. throw new Error("First chunk format is not JSON");
  78332. }
  78333. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  78334. // Look for BIN chunk
  78335. var bin = null;
  78336. while (binaryReader.getPosition() < binaryReader.getLength()) {
  78337. var chunkLength_1 = binaryReader.readUint32();
  78338. var chunkFormat_1 = binaryReader.readUint32();
  78339. switch (chunkFormat_1) {
  78340. case ChunkFormat.JSON: {
  78341. throw new Error("Unexpected JSON chunk");
  78342. }
  78343. case ChunkFormat.BIN: {
  78344. bin = binaryReader.readUint8Array(chunkLength_1);
  78345. break;
  78346. }
  78347. default: {
  78348. // ignore unrecognized chunkFormat
  78349. binaryReader.skipBytes(chunkLength_1);
  78350. break;
  78351. }
  78352. }
  78353. }
  78354. return {
  78355. json: json,
  78356. bin: bin
  78357. };
  78358. };
  78359. GLTFFileLoader._parseVersion = function (version) {
  78360. var match = (version + "").match(/^(\d+)\.(\d+)$/);
  78361. if (!match) {
  78362. return null;
  78363. }
  78364. return {
  78365. major: parseInt(match[1]),
  78366. minor: parseInt(match[2])
  78367. };
  78368. };
  78369. GLTFFileLoader._compareVersion = function (a, b) {
  78370. if (a.major > b.major)
  78371. return 1;
  78372. if (a.major < b.major)
  78373. return -1;
  78374. if (a.minor > b.minor)
  78375. return 1;
  78376. if (a.minor < b.minor)
  78377. return -1;
  78378. return 0;
  78379. };
  78380. GLTFFileLoader._decodeBufferToText = function (buffer) {
  78381. var result = "";
  78382. var length = buffer.byteLength;
  78383. for (var i = 0; i < length; i++) {
  78384. result += String.fromCharCode(buffer[i]);
  78385. }
  78386. return result;
  78387. };
  78388. // V1 options
  78389. GLTFFileLoader.HomogeneousCoordinates = false;
  78390. GLTFFileLoader.IncrementalLoading = true;
  78391. return GLTFFileLoader;
  78392. }());
  78393. BABYLON.GLTFFileLoader = GLTFFileLoader;
  78394. var BinaryReader = /** @class */ (function () {
  78395. function BinaryReader(arrayBuffer) {
  78396. this._arrayBuffer = arrayBuffer;
  78397. this._dataView = new DataView(arrayBuffer);
  78398. this._byteOffset = 0;
  78399. }
  78400. BinaryReader.prototype.getPosition = function () {
  78401. return this._byteOffset;
  78402. };
  78403. BinaryReader.prototype.getLength = function () {
  78404. return this._arrayBuffer.byteLength;
  78405. };
  78406. BinaryReader.prototype.readUint32 = function () {
  78407. var value = this._dataView.getUint32(this._byteOffset, true);
  78408. this._byteOffset += 4;
  78409. return value;
  78410. };
  78411. BinaryReader.prototype.readUint8Array = function (length) {
  78412. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  78413. this._byteOffset += length;
  78414. return value;
  78415. };
  78416. BinaryReader.prototype.skipBytes = function (length) {
  78417. this._byteOffset += length;
  78418. };
  78419. return BinaryReader;
  78420. }());
  78421. if (BABYLON.SceneLoader) {
  78422. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  78423. }
  78424. })(BABYLON || (BABYLON = {}));
  78425. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  78426. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78427. var BABYLON;
  78428. (function (BABYLON) {
  78429. var GLTF1;
  78430. (function (GLTF1) {
  78431. /**
  78432. * Enums
  78433. */
  78434. var EComponentType;
  78435. (function (EComponentType) {
  78436. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  78437. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  78438. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  78439. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  78440. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  78441. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  78442. var EShaderType;
  78443. (function (EShaderType) {
  78444. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  78445. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  78446. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  78447. var EParameterType;
  78448. (function (EParameterType) {
  78449. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  78450. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  78451. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  78452. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  78453. EParameterType[EParameterType["INT"] = 5124] = "INT";
  78454. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  78455. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  78456. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  78457. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  78458. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  78459. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  78460. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  78461. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  78462. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  78463. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  78464. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  78465. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  78466. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  78467. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  78468. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  78469. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  78470. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  78471. var ETextureWrapMode;
  78472. (function (ETextureWrapMode) {
  78473. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  78474. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  78475. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  78476. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  78477. var ETextureFilterType;
  78478. (function (ETextureFilterType) {
  78479. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  78480. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  78481. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  78482. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  78483. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  78484. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  78485. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  78486. var ETextureFormat;
  78487. (function (ETextureFormat) {
  78488. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  78489. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  78490. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  78491. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  78492. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  78493. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  78494. var ECullingType;
  78495. (function (ECullingType) {
  78496. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  78497. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  78498. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  78499. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  78500. var EBlendingFunction;
  78501. (function (EBlendingFunction) {
  78502. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  78503. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  78504. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  78505. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  78506. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  78507. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  78508. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  78509. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  78510. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  78511. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  78512. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  78513. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  78514. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  78515. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  78516. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  78517. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  78518. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78519. })(BABYLON || (BABYLON = {}));
  78520. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  78521. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78522. var BABYLON;
  78523. (function (BABYLON) {
  78524. var GLTF1;
  78525. (function (GLTF1) {
  78526. /**
  78527. * Tokenizer. Used for shaders compatibility
  78528. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  78529. */
  78530. var ETokenType;
  78531. (function (ETokenType) {
  78532. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  78533. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  78534. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  78535. })(ETokenType || (ETokenType = {}));
  78536. var Tokenizer = /** @class */ (function () {
  78537. function Tokenizer(toParse) {
  78538. this._pos = 0;
  78539. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  78540. this._toParse = toParse;
  78541. this._maxPos = toParse.length;
  78542. }
  78543. Tokenizer.prototype.getNextToken = function () {
  78544. if (this.isEnd())
  78545. return ETokenType.END_OF_INPUT;
  78546. this.currentString = this.read();
  78547. this.currentToken = ETokenType.UNKNOWN;
  78548. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  78549. this.currentToken = ETokenType.IDENTIFIER;
  78550. this.currentIdentifier = this.currentString;
  78551. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  78552. this.currentIdentifier += this.currentString;
  78553. this.forward();
  78554. }
  78555. }
  78556. return this.currentToken;
  78557. };
  78558. Tokenizer.prototype.peek = function () {
  78559. return this._toParse[this._pos];
  78560. };
  78561. Tokenizer.prototype.read = function () {
  78562. return this._toParse[this._pos++];
  78563. };
  78564. Tokenizer.prototype.forward = function () {
  78565. this._pos++;
  78566. };
  78567. Tokenizer.prototype.isEnd = function () {
  78568. return this._pos >= this._maxPos;
  78569. };
  78570. return Tokenizer;
  78571. }());
  78572. /**
  78573. * Values
  78574. */
  78575. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  78576. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  78577. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  78578. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  78579. /**
  78580. * Parse
  78581. */
  78582. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  78583. for (var buf in parsedBuffers) {
  78584. var parsedBuffer = parsedBuffers[buf];
  78585. gltfRuntime.buffers[buf] = parsedBuffer;
  78586. gltfRuntime.buffersCount++;
  78587. }
  78588. };
  78589. var parseShaders = function (parsedShaders, gltfRuntime) {
  78590. for (var sha in parsedShaders) {
  78591. var parsedShader = parsedShaders[sha];
  78592. gltfRuntime.shaders[sha] = parsedShader;
  78593. gltfRuntime.shaderscount++;
  78594. }
  78595. };
  78596. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  78597. for (var object in parsedObjects) {
  78598. var parsedObject = parsedObjects[object];
  78599. gltfRuntime[runtimeProperty][object] = parsedObject;
  78600. }
  78601. };
  78602. /**
  78603. * Utils
  78604. */
  78605. var normalizeUVs = function (buffer) {
  78606. if (!buffer) {
  78607. return;
  78608. }
  78609. for (var i = 0; i < buffer.length / 2; i++) {
  78610. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  78611. }
  78612. };
  78613. var getAttribute = function (attributeParameter) {
  78614. if (attributeParameter.semantic === "NORMAL") {
  78615. return "normal";
  78616. }
  78617. else if (attributeParameter.semantic === "POSITION") {
  78618. return "position";
  78619. }
  78620. else if (attributeParameter.semantic === "JOINT") {
  78621. return "matricesIndices";
  78622. }
  78623. else if (attributeParameter.semantic === "WEIGHT") {
  78624. return "matricesWeights";
  78625. }
  78626. else if (attributeParameter.semantic === "COLOR") {
  78627. return "color";
  78628. }
  78629. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  78630. var channel = Number(attributeParameter.semantic.split("_")[1]);
  78631. return "uv" + (channel === 0 ? "" : channel + 1);
  78632. }
  78633. return null;
  78634. };
  78635. /**
  78636. * Loads and creates animations
  78637. */
  78638. var loadAnimations = function (gltfRuntime) {
  78639. for (var anim in gltfRuntime.animations) {
  78640. var animation = gltfRuntime.animations[anim];
  78641. if (!animation.channels || !animation.samplers) {
  78642. continue;
  78643. }
  78644. var lastAnimation = null;
  78645. for (var i = 0; i < animation.channels.length; i++) {
  78646. // Get parameters and load buffers
  78647. var channel = animation.channels[i];
  78648. var sampler = animation.samplers[channel.sampler];
  78649. if (!sampler) {
  78650. continue;
  78651. }
  78652. var inputData = null;
  78653. var outputData = null;
  78654. if (animation.parameters) {
  78655. inputData = animation.parameters[sampler.input];
  78656. outputData = animation.parameters[sampler.output];
  78657. }
  78658. else {
  78659. inputData = sampler.input;
  78660. outputData = sampler.output;
  78661. }
  78662. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  78663. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  78664. var targetID = channel.target.id;
  78665. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  78666. if (targetNode === null) {
  78667. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  78668. }
  78669. if (targetNode === null) {
  78670. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  78671. continue;
  78672. }
  78673. var isBone = targetNode instanceof BABYLON.Bone;
  78674. // Get target path (position, rotation or scaling)
  78675. var targetPath = channel.target.path;
  78676. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  78677. if (targetPathIndex !== -1) {
  78678. targetPath = babylonAnimationPaths[targetPathIndex];
  78679. }
  78680. // Determine animation type
  78681. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  78682. if (!isBone) {
  78683. if (targetPath === "rotationQuaternion") {
  78684. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  78685. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  78686. }
  78687. else {
  78688. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  78689. }
  78690. }
  78691. // Create animation and key frames
  78692. var babylonAnimation = null;
  78693. var keys = [];
  78694. var arrayOffset = 0;
  78695. var modifyKey = false;
  78696. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  78697. babylonAnimation = lastAnimation;
  78698. modifyKey = true;
  78699. }
  78700. if (!modifyKey) {
  78701. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  78702. }
  78703. // For each frame
  78704. for (var j = 0; j < bufferInput.length; j++) {
  78705. var value = null;
  78706. if (targetPath === "rotationQuaternion") {
  78707. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  78708. arrayOffset += 4;
  78709. }
  78710. else {
  78711. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  78712. arrayOffset += 3;
  78713. }
  78714. if (isBone) {
  78715. var bone = targetNode;
  78716. var translation = BABYLON.Vector3.Zero();
  78717. var rotationQuaternion = new BABYLON.Quaternion();
  78718. var scaling = BABYLON.Vector3.Zero();
  78719. // Warning on decompose
  78720. var mat = bone.getBaseMatrix();
  78721. if (modifyKey && lastAnimation) {
  78722. mat = lastAnimation.getKeys()[j].value;
  78723. }
  78724. mat.decompose(scaling, rotationQuaternion, translation);
  78725. if (targetPath === "position") {
  78726. translation = value;
  78727. }
  78728. else if (targetPath === "rotationQuaternion") {
  78729. rotationQuaternion = value;
  78730. }
  78731. else {
  78732. scaling = value;
  78733. }
  78734. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  78735. }
  78736. if (!modifyKey) {
  78737. keys.push({
  78738. frame: bufferInput[j],
  78739. value: value
  78740. });
  78741. }
  78742. else if (lastAnimation) {
  78743. lastAnimation.getKeys()[j].value = value;
  78744. }
  78745. }
  78746. // Finish
  78747. if (!modifyKey && babylonAnimation) {
  78748. babylonAnimation.setKeys(keys);
  78749. targetNode.animations.push(babylonAnimation);
  78750. }
  78751. lastAnimation = babylonAnimation;
  78752. gltfRuntime.scene.stopAnimation(targetNode);
  78753. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  78754. }
  78755. }
  78756. };
  78757. /**
  78758. * Returns the bones transformation matrix
  78759. */
  78760. var configureBoneTransformation = function (node) {
  78761. var mat = null;
  78762. if (node.translation || node.rotation || node.scale) {
  78763. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  78764. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  78765. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  78766. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  78767. }
  78768. else {
  78769. mat = BABYLON.Matrix.FromArray(node.matrix);
  78770. }
  78771. return mat;
  78772. };
  78773. /**
  78774. * Returns the parent bone
  78775. */
  78776. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  78777. // Try to find
  78778. for (var i = 0; i < newSkeleton.bones.length; i++) {
  78779. if (newSkeleton.bones[i].name === jointName) {
  78780. return newSkeleton.bones[i];
  78781. }
  78782. }
  78783. // Not found, search in gltf nodes
  78784. var nodes = gltfRuntime.nodes;
  78785. for (var nde in nodes) {
  78786. var node = nodes[nde];
  78787. if (!node.jointName) {
  78788. continue;
  78789. }
  78790. var children = node.children;
  78791. for (var i = 0; i < children.length; i++) {
  78792. var child = gltfRuntime.nodes[children[i]];
  78793. if (!child.jointName) {
  78794. continue;
  78795. }
  78796. if (child.jointName === jointName) {
  78797. var mat = configureBoneTransformation(node);
  78798. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  78799. bone.id = nde;
  78800. return bone;
  78801. }
  78802. }
  78803. }
  78804. return null;
  78805. };
  78806. /**
  78807. * Returns the appropriate root node
  78808. */
  78809. var getNodeToRoot = function (nodesToRoot, id) {
  78810. for (var i = 0; i < nodesToRoot.length; i++) {
  78811. var nodeToRoot = nodesToRoot[i];
  78812. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  78813. var child = nodeToRoot.node.children[j];
  78814. if (child === id) {
  78815. return nodeToRoot.bone;
  78816. }
  78817. }
  78818. }
  78819. return null;
  78820. };
  78821. /**
  78822. * Returns the node with the joint name
  78823. */
  78824. var getJointNode = function (gltfRuntime, jointName) {
  78825. var nodes = gltfRuntime.nodes;
  78826. var node = nodes[jointName];
  78827. if (node) {
  78828. return {
  78829. node: node,
  78830. id: jointName
  78831. };
  78832. }
  78833. for (var nde in nodes) {
  78834. node = nodes[nde];
  78835. if (node.jointName === jointName) {
  78836. return {
  78837. node: node,
  78838. id: nde
  78839. };
  78840. }
  78841. }
  78842. return null;
  78843. };
  78844. /**
  78845. * Checks if a nodes is in joints
  78846. */
  78847. var nodeIsInJoints = function (skins, id) {
  78848. for (var i = 0; i < skins.jointNames.length; i++) {
  78849. if (skins.jointNames[i] === id) {
  78850. return true;
  78851. }
  78852. }
  78853. return false;
  78854. };
  78855. /**
  78856. * Fills the nodes to root for bones and builds hierarchy
  78857. */
  78858. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  78859. // Creates nodes for root
  78860. for (var nde in gltfRuntime.nodes) {
  78861. var node = gltfRuntime.nodes[nde];
  78862. var id = nde;
  78863. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  78864. continue;
  78865. }
  78866. // Create node to root bone
  78867. var mat = configureBoneTransformation(node);
  78868. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  78869. bone.id = id;
  78870. nodesToRoot.push({ bone: bone, node: node, id: id });
  78871. }
  78872. // Parenting
  78873. for (var i = 0; i < nodesToRoot.length; i++) {
  78874. var nodeToRoot = nodesToRoot[i];
  78875. var children = nodeToRoot.node.children;
  78876. for (var j = 0; j < children.length; j++) {
  78877. var child = null;
  78878. for (var k = 0; k < nodesToRoot.length; k++) {
  78879. if (nodesToRoot[k].id === children[j]) {
  78880. child = nodesToRoot[k];
  78881. break;
  78882. }
  78883. }
  78884. if (child) {
  78885. child.bone._parent = nodeToRoot.bone;
  78886. nodeToRoot.bone.children.push(child.bone);
  78887. }
  78888. }
  78889. }
  78890. };
  78891. /**
  78892. * Imports a skeleton
  78893. */
  78894. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  78895. if (!newSkeleton) {
  78896. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  78897. }
  78898. if (!skins.babylonSkeleton) {
  78899. return newSkeleton;
  78900. }
  78901. // Find the root bones
  78902. var nodesToRoot = [];
  78903. var nodesToRootToAdd = [];
  78904. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  78905. newSkeleton.bones = [];
  78906. // Joints
  78907. for (var i = 0; i < skins.jointNames.length; i++) {
  78908. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  78909. if (!jointNode) {
  78910. continue;
  78911. }
  78912. var node = jointNode.node;
  78913. if (!node) {
  78914. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  78915. continue;
  78916. }
  78917. var id = jointNode.id;
  78918. // Optimize, if the bone already exists...
  78919. var existingBone = gltfRuntime.scene.getBoneByID(id);
  78920. if (existingBone) {
  78921. newSkeleton.bones.push(existingBone);
  78922. continue;
  78923. }
  78924. // Search for parent bone
  78925. var foundBone = false;
  78926. var parentBone = null;
  78927. for (var j = 0; j < i; j++) {
  78928. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  78929. if (!jointNode_1) {
  78930. continue;
  78931. }
  78932. var joint = jointNode_1.node;
  78933. if (!joint) {
  78934. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  78935. continue;
  78936. }
  78937. var children = joint.children;
  78938. if (!children) {
  78939. continue;
  78940. }
  78941. foundBone = false;
  78942. for (var k = 0; k < children.length; k++) {
  78943. if (children[k] === id) {
  78944. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  78945. foundBone = true;
  78946. break;
  78947. }
  78948. }
  78949. if (foundBone) {
  78950. break;
  78951. }
  78952. }
  78953. // Create bone
  78954. var mat = configureBoneTransformation(node);
  78955. if (!parentBone && nodesToRoot.length > 0) {
  78956. parentBone = getNodeToRoot(nodesToRoot, id);
  78957. if (parentBone) {
  78958. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  78959. nodesToRootToAdd.push(parentBone);
  78960. }
  78961. }
  78962. }
  78963. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  78964. bone.id = id;
  78965. }
  78966. // Polish
  78967. var bones = newSkeleton.bones;
  78968. newSkeleton.bones = [];
  78969. for (var i = 0; i < skins.jointNames.length; i++) {
  78970. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  78971. if (!jointNode) {
  78972. continue;
  78973. }
  78974. for (var j = 0; j < bones.length; j++) {
  78975. if (bones[j].id === jointNode.id) {
  78976. newSkeleton.bones.push(bones[j]);
  78977. break;
  78978. }
  78979. }
  78980. }
  78981. newSkeleton.prepare();
  78982. // Finish
  78983. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  78984. newSkeleton.bones.push(nodesToRootToAdd[i]);
  78985. }
  78986. return newSkeleton;
  78987. };
  78988. /**
  78989. * Imports a mesh and its geometries
  78990. */
  78991. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  78992. if (!newMesh) {
  78993. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  78994. newMesh.id = id;
  78995. }
  78996. if (!node.babylonNode) {
  78997. return newMesh;
  78998. }
  78999. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  79000. if (!newMesh.material) {
  79001. newMesh.material = multiMat;
  79002. }
  79003. var vertexData = new BABYLON.VertexData();
  79004. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  79005. var verticesStarts = new Array();
  79006. var verticesCounts = new Array();
  79007. var indexStarts = new Array();
  79008. var indexCounts = new Array();
  79009. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  79010. var meshID = meshes[meshIndex];
  79011. var mesh = gltfRuntime.meshes[meshID];
  79012. if (!mesh) {
  79013. continue;
  79014. }
  79015. // Positions, normals and UVs
  79016. for (var i = 0; i < mesh.primitives.length; i++) {
  79017. // Temporary vertex data
  79018. var tempVertexData = new BABYLON.VertexData();
  79019. var primitive = mesh.primitives[i];
  79020. if (primitive.mode !== 4) {
  79021. // continue;
  79022. }
  79023. var attributes = primitive.attributes;
  79024. var accessor = null;
  79025. var buffer = null;
  79026. // Set positions, normal and uvs
  79027. for (var semantic in attributes) {
  79028. // Link accessor and buffer view
  79029. accessor = gltfRuntime.accessors[attributes[semantic]];
  79030. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  79031. if (semantic === "NORMAL") {
  79032. tempVertexData.normals = new Float32Array(buffer.length);
  79033. tempVertexData.normals.set(buffer);
  79034. }
  79035. else if (semantic === "POSITION") {
  79036. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  79037. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  79038. for (var j = 0; j < buffer.length; j += 4) {
  79039. tempVertexData.positions[j] = buffer[j];
  79040. tempVertexData.positions[j + 1] = buffer[j + 1];
  79041. tempVertexData.positions[j + 2] = buffer[j + 2];
  79042. }
  79043. }
  79044. else {
  79045. tempVertexData.positions = new Float32Array(buffer.length);
  79046. tempVertexData.positions.set(buffer);
  79047. }
  79048. verticesCounts.push(tempVertexData.positions.length);
  79049. }
  79050. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  79051. var channel = Number(semantic.split("_")[1]);
  79052. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  79053. var uvs = new Float32Array(buffer.length);
  79054. uvs.set(buffer);
  79055. normalizeUVs(uvs);
  79056. tempVertexData.set(uvs, uvKind);
  79057. }
  79058. else if (semantic === "JOINT") {
  79059. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  79060. tempVertexData.matricesIndices.set(buffer);
  79061. }
  79062. else if (semantic === "WEIGHT") {
  79063. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  79064. tempVertexData.matricesWeights.set(buffer);
  79065. }
  79066. else if (semantic === "COLOR") {
  79067. tempVertexData.colors = new Float32Array(buffer.length);
  79068. tempVertexData.colors.set(buffer);
  79069. }
  79070. }
  79071. // Indices
  79072. accessor = gltfRuntime.accessors[primitive.indices];
  79073. if (accessor) {
  79074. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  79075. tempVertexData.indices = new Int32Array(buffer.length);
  79076. tempVertexData.indices.set(buffer);
  79077. indexCounts.push(tempVertexData.indices.length);
  79078. }
  79079. else {
  79080. // Set indices on the fly
  79081. var indices = [];
  79082. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  79083. indices.push(j);
  79084. }
  79085. tempVertexData.indices = new Int32Array(indices);
  79086. indexCounts.push(tempVertexData.indices.length);
  79087. }
  79088. vertexData.merge(tempVertexData);
  79089. // Sub material
  79090. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  79091. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  79092. // Update vertices start and index start
  79093. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  79094. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  79095. }
  79096. }
  79097. // Apply geometry
  79098. geometry.setAllVerticesData(vertexData, false);
  79099. newMesh.computeWorldMatrix(true);
  79100. // Apply submeshes
  79101. newMesh.subMeshes = [];
  79102. var index = 0;
  79103. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  79104. var meshID = meshes[meshIndex];
  79105. var mesh = gltfRuntime.meshes[meshID];
  79106. if (!mesh) {
  79107. continue;
  79108. }
  79109. for (var i = 0; i < mesh.primitives.length; i++) {
  79110. if (mesh.primitives[i].mode !== 4) {
  79111. //continue;
  79112. }
  79113. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  79114. index++;
  79115. }
  79116. }
  79117. // Finish
  79118. return newMesh;
  79119. };
  79120. /**
  79121. * Configure node transformation from position, rotation and scaling
  79122. */
  79123. var configureNode = function (newNode, position, rotation, scaling) {
  79124. if (newNode.position) {
  79125. newNode.position = position;
  79126. }
  79127. if (newNode.rotationQuaternion || newNode.rotation) {
  79128. newNode.rotationQuaternion = rotation;
  79129. }
  79130. if (newNode.scaling) {
  79131. newNode.scaling = scaling;
  79132. }
  79133. };
  79134. /**
  79135. * Configures node from transformation matrix
  79136. */
  79137. var configureNodeFromMatrix = function (newNode, node, parent) {
  79138. if (node.matrix) {
  79139. var position = new BABYLON.Vector3(0, 0, 0);
  79140. var rotation = new BABYLON.Quaternion();
  79141. var scaling = new BABYLON.Vector3(0, 0, 0);
  79142. var mat = BABYLON.Matrix.FromArray(node.matrix);
  79143. mat.decompose(scaling, rotation, position);
  79144. configureNode(newNode, position, rotation, scaling);
  79145. }
  79146. else if (node.translation && node.rotation && node.scale) {
  79147. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  79148. }
  79149. newNode.computeWorldMatrix(true);
  79150. };
  79151. /**
  79152. * Imports a node
  79153. */
  79154. var importNode = function (gltfRuntime, node, id, parent) {
  79155. var lastNode = null;
  79156. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  79157. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  79158. return null;
  79159. }
  79160. }
  79161. // Meshes
  79162. if (node.skin) {
  79163. if (node.meshes) {
  79164. var skin = gltfRuntime.skins[node.skin];
  79165. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  79166. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  79167. if (newMesh.skeleton === null && skin.babylonSkeleton) {
  79168. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  79169. if (!skin.babylonSkeleton) {
  79170. skin.babylonSkeleton = newMesh.skeleton;
  79171. }
  79172. }
  79173. lastNode = newMesh;
  79174. }
  79175. }
  79176. else if (node.meshes) {
  79177. /**
  79178. * Improve meshes property
  79179. */
  79180. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  79181. lastNode = newMesh;
  79182. }
  79183. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  79184. var light = gltfRuntime.lights[node.light];
  79185. if (light) {
  79186. if (light.type === "ambient") {
  79187. var ambienLight = light[light.type];
  79188. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  79189. hemiLight.name = node.name || "";
  79190. if (ambienLight.color) {
  79191. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  79192. }
  79193. lastNode = hemiLight;
  79194. }
  79195. else if (light.type === "directional") {
  79196. var directionalLight = light[light.type];
  79197. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  79198. dirLight.name = node.name || "";
  79199. if (directionalLight.color) {
  79200. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  79201. }
  79202. lastNode = dirLight;
  79203. }
  79204. else if (light.type === "point") {
  79205. var pointLight = light[light.type];
  79206. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  79207. ptLight.name = node.name || "";
  79208. if (pointLight.color) {
  79209. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  79210. }
  79211. lastNode = ptLight;
  79212. }
  79213. else if (light.type === "spot") {
  79214. var spotLight = light[light.type];
  79215. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  79216. spLight.name = node.name || "";
  79217. if (spotLight.color) {
  79218. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  79219. }
  79220. if (spotLight.fallOfAngle) {
  79221. spLight.angle = spotLight.fallOfAngle;
  79222. }
  79223. if (spotLight.fallOffExponent) {
  79224. spLight.exponent = spotLight.fallOffExponent;
  79225. }
  79226. lastNode = spLight;
  79227. }
  79228. }
  79229. }
  79230. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  79231. var camera = gltfRuntime.cameras[node.camera];
  79232. if (camera) {
  79233. if (camera.type === "orthographic") {
  79234. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  79235. orthoCamera.name = node.name || "";
  79236. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  79237. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  79238. lastNode = orthoCamera;
  79239. }
  79240. else if (camera.type === "perspective") {
  79241. var perspectiveCamera = camera[camera.type];
  79242. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  79243. persCamera.name = node.name || "";
  79244. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  79245. if (!perspectiveCamera.aspectRatio) {
  79246. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  79247. }
  79248. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  79249. persCamera.maxZ = perspectiveCamera.zfar;
  79250. persCamera.minZ = perspectiveCamera.znear;
  79251. }
  79252. lastNode = persCamera;
  79253. }
  79254. }
  79255. }
  79256. // Empty node
  79257. if (!node.jointName) {
  79258. if (node.babylonNode) {
  79259. return node.babylonNode;
  79260. }
  79261. else if (lastNode === null) {
  79262. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  79263. node.babylonNode = dummy;
  79264. lastNode = dummy;
  79265. }
  79266. }
  79267. if (lastNode !== null) {
  79268. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  79269. configureNodeFromMatrix(lastNode, node, parent);
  79270. }
  79271. else {
  79272. var translation = node.translation || [0, 0, 0];
  79273. var rotation = node.rotation || [0, 0, 0, 1];
  79274. var scale = node.scale || [1, 1, 1];
  79275. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  79276. }
  79277. lastNode.updateCache(true);
  79278. node.babylonNode = lastNode;
  79279. }
  79280. return lastNode;
  79281. };
  79282. /**
  79283. * Traverses nodes and creates them
  79284. */
  79285. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  79286. if (meshIncluded === void 0) { meshIncluded = false; }
  79287. var node = gltfRuntime.nodes[id];
  79288. var newNode = null;
  79289. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  79290. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  79291. meshIncluded = true;
  79292. }
  79293. else {
  79294. meshIncluded = false;
  79295. }
  79296. }
  79297. else {
  79298. meshIncluded = true;
  79299. }
  79300. if (!node.jointName && meshIncluded) {
  79301. newNode = importNode(gltfRuntime, node, id, parent);
  79302. if (newNode !== null) {
  79303. newNode.id = id;
  79304. newNode.parent = parent;
  79305. }
  79306. }
  79307. if (node.children) {
  79308. for (var i = 0; i < node.children.length; i++) {
  79309. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  79310. }
  79311. }
  79312. };
  79313. /**
  79314. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  79315. */
  79316. var postLoad = function (gltfRuntime) {
  79317. // Nodes
  79318. var currentScene = gltfRuntime.currentScene;
  79319. if (currentScene) {
  79320. for (var i = 0; i < currentScene.nodes.length; i++) {
  79321. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  79322. }
  79323. }
  79324. else {
  79325. for (var thing in gltfRuntime.scenes) {
  79326. currentScene = gltfRuntime.scenes[thing];
  79327. for (var i = 0; i < currentScene.nodes.length; i++) {
  79328. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  79329. }
  79330. }
  79331. }
  79332. // Set animations
  79333. loadAnimations(gltfRuntime);
  79334. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  79335. var skeleton = gltfRuntime.scene.skeletons[i];
  79336. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  79337. }
  79338. };
  79339. /**
  79340. * onBind shaderrs callback to set uniforms and matrices
  79341. */
  79342. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  79343. var materialValues = material.values || technique.parameters;
  79344. for (var unif in unTreatedUniforms) {
  79345. var uniform = unTreatedUniforms[unif];
  79346. var type = uniform.type;
  79347. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  79348. if (uniform.semantic && !uniform.source && !uniform.node) {
  79349. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  79350. }
  79351. else if (uniform.semantic && (uniform.source || uniform.node)) {
  79352. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  79353. if (source === null) {
  79354. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  79355. }
  79356. if (source === null) {
  79357. continue;
  79358. }
  79359. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  79360. }
  79361. }
  79362. else {
  79363. var value = materialValues[technique.uniforms[unif]];
  79364. if (!value) {
  79365. continue;
  79366. }
  79367. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  79368. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  79369. if (texture === null || texture === undefined) {
  79370. continue;
  79371. }
  79372. shaderMaterial.getEffect().setTexture(unif, texture);
  79373. }
  79374. else {
  79375. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  79376. }
  79377. }
  79378. }
  79379. onSuccess(shaderMaterial);
  79380. };
  79381. /**
  79382. * Prepare uniforms to send the only one time
  79383. * Loads the appropriate textures
  79384. */
  79385. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  79386. var materialValues = material.values || technique.parameters;
  79387. var techniqueUniforms = technique.uniforms;
  79388. /**
  79389. * Prepare values here (not matrices)
  79390. */
  79391. for (var unif in unTreatedUniforms) {
  79392. var uniform = unTreatedUniforms[unif];
  79393. var type = uniform.type;
  79394. var value = materialValues[techniqueUniforms[unif]];
  79395. if (value === undefined) {
  79396. // In case the value is the same for all materials
  79397. value = uniform.value;
  79398. }
  79399. if (!value) {
  79400. continue;
  79401. }
  79402. var onLoadTexture = function (uniformName) {
  79403. return function (texture) {
  79404. if (uniform.value && uniformName) {
  79405. // Static uniform
  79406. shaderMaterial.setTexture(uniformName, texture);
  79407. delete unTreatedUniforms[uniformName];
  79408. }
  79409. };
  79410. };
  79411. // Texture (sampler2D)
  79412. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  79413. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  79414. }
  79415. else {
  79416. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  79417. // Static uniform
  79418. delete unTreatedUniforms[unif];
  79419. }
  79420. }
  79421. }
  79422. };
  79423. /**
  79424. * Shader compilation failed
  79425. */
  79426. var onShaderCompileError = function (program, shaderMaterial, onError) {
  79427. return function (effect, error) {
  79428. shaderMaterial.dispose(true);
  79429. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  79430. };
  79431. };
  79432. /**
  79433. * Shader compilation success
  79434. */
  79435. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  79436. return function (_) {
  79437. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  79438. shaderMaterial.onBind = function (mesh) {
  79439. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  79440. };
  79441. };
  79442. };
  79443. /**
  79444. * Returns the appropriate uniform if already handled by babylon
  79445. */
  79446. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  79447. for (var unif in technique.uniforms) {
  79448. var uniform = technique.uniforms[unif];
  79449. var uniformParameter = technique.parameters[uniform];
  79450. if (tokenizer.currentIdentifier === unif) {
  79451. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  79452. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  79453. if (transformIndex !== -1) {
  79454. delete unTreatedUniforms[unif];
  79455. return babylonTransforms[transformIndex];
  79456. }
  79457. }
  79458. }
  79459. }
  79460. return tokenizer.currentIdentifier;
  79461. };
  79462. /**
  79463. * All shaders loaded. Create materials one by one
  79464. */
  79465. var importMaterials = function (gltfRuntime) {
  79466. // Create materials
  79467. for (var mat in gltfRuntime.materials) {
  79468. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  79469. }
  79470. };
  79471. /**
  79472. * Implementation of the base glTF spec
  79473. */
  79474. var GLTFLoaderBase = /** @class */ (function () {
  79475. function GLTFLoaderBase() {
  79476. }
  79477. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  79478. var gltfRuntime = {
  79479. extensions: {},
  79480. accessors: {},
  79481. buffers: {},
  79482. bufferViews: {},
  79483. meshes: {},
  79484. lights: {},
  79485. cameras: {},
  79486. nodes: {},
  79487. images: {},
  79488. textures: {},
  79489. shaders: {},
  79490. programs: {},
  79491. samplers: {},
  79492. techniques: {},
  79493. materials: {},
  79494. animations: {},
  79495. skins: {},
  79496. extensionsUsed: [],
  79497. scenes: {},
  79498. buffersCount: 0,
  79499. shaderscount: 0,
  79500. scene: scene,
  79501. rootUrl: rootUrl,
  79502. loadedBufferCount: 0,
  79503. loadedBufferViews: {},
  79504. loadedShaderCount: 0,
  79505. importOnlyMeshes: false,
  79506. dummyNodes: []
  79507. };
  79508. // Parse
  79509. if (parsedData.extensions) {
  79510. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  79511. }
  79512. if (parsedData.extensionsUsed) {
  79513. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  79514. }
  79515. if (parsedData.buffers) {
  79516. parseBuffers(parsedData.buffers, gltfRuntime);
  79517. }
  79518. if (parsedData.bufferViews) {
  79519. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  79520. }
  79521. if (parsedData.accessors) {
  79522. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  79523. }
  79524. if (parsedData.meshes) {
  79525. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  79526. }
  79527. if (parsedData.lights) {
  79528. parseObject(parsedData.lights, "lights", gltfRuntime);
  79529. }
  79530. if (parsedData.cameras) {
  79531. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  79532. }
  79533. if (parsedData.nodes) {
  79534. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  79535. }
  79536. if (parsedData.images) {
  79537. parseObject(parsedData.images, "images", gltfRuntime);
  79538. }
  79539. if (parsedData.textures) {
  79540. parseObject(parsedData.textures, "textures", gltfRuntime);
  79541. }
  79542. if (parsedData.shaders) {
  79543. parseShaders(parsedData.shaders, gltfRuntime);
  79544. }
  79545. if (parsedData.programs) {
  79546. parseObject(parsedData.programs, "programs", gltfRuntime);
  79547. }
  79548. if (parsedData.samplers) {
  79549. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  79550. }
  79551. if (parsedData.techniques) {
  79552. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  79553. }
  79554. if (parsedData.materials) {
  79555. parseObject(parsedData.materials, "materials", gltfRuntime);
  79556. }
  79557. if (parsedData.animations) {
  79558. parseObject(parsedData.animations, "animations", gltfRuntime);
  79559. }
  79560. if (parsedData.skins) {
  79561. parseObject(parsedData.skins, "skins", gltfRuntime);
  79562. }
  79563. if (parsedData.scenes) {
  79564. gltfRuntime.scenes = parsedData.scenes;
  79565. }
  79566. if (parsedData.scene && parsedData.scenes) {
  79567. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  79568. }
  79569. return gltfRuntime;
  79570. };
  79571. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  79572. var buffer = gltfRuntime.buffers[id];
  79573. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  79574. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  79575. }
  79576. else {
  79577. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  79578. if (request) {
  79579. onError(request.status + " " + request.statusText);
  79580. }
  79581. });
  79582. }
  79583. };
  79584. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  79585. var texture = gltfRuntime.textures[id];
  79586. if (!texture || !texture.source) {
  79587. onError("");
  79588. return;
  79589. }
  79590. if (texture.babylonTexture) {
  79591. onSuccess(null);
  79592. return;
  79593. }
  79594. var source = gltfRuntime.images[texture.source];
  79595. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  79596. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  79597. }
  79598. else {
  79599. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  79600. if (request) {
  79601. onError(request.status + " " + request.statusText);
  79602. }
  79603. });
  79604. }
  79605. };
  79606. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  79607. var texture = gltfRuntime.textures[id];
  79608. if (texture.babylonTexture) {
  79609. onSuccess(texture.babylonTexture);
  79610. return;
  79611. }
  79612. var sampler = gltfRuntime.samplers[texture.sampler];
  79613. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  79614. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  79615. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  79616. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  79617. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  79618. var blob = new Blob([buffer]);
  79619. var blobURL = URL.createObjectURL(blob);
  79620. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  79621. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  79622. if (sampler.wrapS !== undefined) {
  79623. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  79624. }
  79625. if (sampler.wrapT !== undefined) {
  79626. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  79627. }
  79628. newTexture.name = id;
  79629. texture.babylonTexture = newTexture;
  79630. onSuccess(newTexture);
  79631. };
  79632. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  79633. var shader = gltfRuntime.shaders[id];
  79634. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  79635. var shaderString = atob(shader.uri.split(",")[1]);
  79636. onSuccess(shaderString);
  79637. }
  79638. else {
  79639. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  79640. if (request) {
  79641. onError(request.status + " " + request.statusText);
  79642. }
  79643. });
  79644. }
  79645. };
  79646. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  79647. var material = gltfRuntime.materials[id];
  79648. if (!material.technique) {
  79649. if (onError) {
  79650. onError("No technique found.");
  79651. }
  79652. return;
  79653. }
  79654. var technique = gltfRuntime.techniques[material.technique];
  79655. if (!technique) {
  79656. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  79657. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  79658. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  79659. onSuccess(defaultMaterial);
  79660. return;
  79661. }
  79662. var program = gltfRuntime.programs[technique.program];
  79663. var states = technique.states;
  79664. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  79665. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  79666. var newVertexShader = "";
  79667. var newPixelShader = "";
  79668. var vertexTokenizer = new Tokenizer(vertexShader);
  79669. var pixelTokenizer = new Tokenizer(pixelShader);
  79670. var unTreatedUniforms = {};
  79671. var uniforms = [];
  79672. var attributes = [];
  79673. var samplers = [];
  79674. // Fill uniform, sampler2D and attributes
  79675. for (var unif in technique.uniforms) {
  79676. var uniform = technique.uniforms[unif];
  79677. var uniformParameter = technique.parameters[uniform];
  79678. unTreatedUniforms[unif] = uniformParameter;
  79679. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  79680. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  79681. if (transformIndex !== -1) {
  79682. uniforms.push(babylonTransforms[transformIndex]);
  79683. delete unTreatedUniforms[unif];
  79684. }
  79685. else {
  79686. uniforms.push(unif);
  79687. }
  79688. }
  79689. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  79690. samplers.push(unif);
  79691. }
  79692. else {
  79693. uniforms.push(unif);
  79694. }
  79695. }
  79696. for (var attr in technique.attributes) {
  79697. var attribute = technique.attributes[attr];
  79698. var attributeParameter = technique.parameters[attribute];
  79699. if (attributeParameter.semantic) {
  79700. attributes.push(getAttribute(attributeParameter));
  79701. }
  79702. }
  79703. // Configure vertex shader
  79704. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  79705. var tokenType = vertexTokenizer.currentToken;
  79706. if (tokenType !== ETokenType.IDENTIFIER) {
  79707. newVertexShader += vertexTokenizer.currentString;
  79708. continue;
  79709. }
  79710. var foundAttribute = false;
  79711. for (var attr in technique.attributes) {
  79712. var attribute = technique.attributes[attr];
  79713. var attributeParameter = technique.parameters[attribute];
  79714. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  79715. newVertexShader += getAttribute(attributeParameter);
  79716. foundAttribute = true;
  79717. break;
  79718. }
  79719. }
  79720. if (foundAttribute) {
  79721. continue;
  79722. }
  79723. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  79724. }
  79725. // Configure pixel shader
  79726. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  79727. var tokenType = pixelTokenizer.currentToken;
  79728. if (tokenType !== ETokenType.IDENTIFIER) {
  79729. newPixelShader += pixelTokenizer.currentString;
  79730. continue;
  79731. }
  79732. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  79733. }
  79734. // Create shader material
  79735. var shaderPath = {
  79736. vertex: program.vertexShader + id,
  79737. fragment: program.fragmentShader + id
  79738. };
  79739. var options = {
  79740. attributes: attributes,
  79741. uniforms: uniforms,
  79742. samplers: samplers,
  79743. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  79744. };
  79745. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  79746. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  79747. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  79748. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  79749. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  79750. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  79751. if (states && states.functions) {
  79752. var functions = states.functions;
  79753. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  79754. shaderMaterial.backFaceCulling = false;
  79755. }
  79756. var blendFunc = functions.blendFuncSeparate;
  79757. if (blendFunc) {
  79758. 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) {
  79759. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  79760. }
  79761. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  79762. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  79763. }
  79764. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  79765. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  79766. }
  79767. 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) {
  79768. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  79769. }
  79770. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  79771. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  79772. }
  79773. 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) {
  79774. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  79775. }
  79776. }
  79777. }
  79778. };
  79779. return GLTFLoaderBase;
  79780. }());
  79781. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  79782. /**
  79783. * glTF V1 Loader
  79784. */
  79785. var GLTFLoader = /** @class */ (function () {
  79786. function GLTFLoader() {
  79787. }
  79788. GLTFLoader.RegisterExtension = function (extension) {
  79789. if (GLTFLoader.Extensions[extension.name]) {
  79790. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  79791. return;
  79792. }
  79793. GLTFLoader.Extensions[extension.name] = extension;
  79794. };
  79795. GLTFLoader.prototype.dispose = function () {
  79796. // do nothing
  79797. };
  79798. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  79799. var _this = this;
  79800. scene.useRightHandedSystem = true;
  79801. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  79802. gltfRuntime.importOnlyMeshes = true;
  79803. if (meshesNames === "") {
  79804. gltfRuntime.importMeshesNames = [];
  79805. }
  79806. else if (typeof meshesNames === "string") {
  79807. gltfRuntime.importMeshesNames = [meshesNames];
  79808. }
  79809. else if (meshesNames && !(meshesNames instanceof Array)) {
  79810. gltfRuntime.importMeshesNames = [meshesNames];
  79811. }
  79812. else {
  79813. gltfRuntime.importMeshesNames = [];
  79814. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  79815. }
  79816. // Create nodes
  79817. _this._createNodes(gltfRuntime);
  79818. var meshes = new Array();
  79819. var skeletons = new Array();
  79820. // Fill arrays of meshes and skeletons
  79821. for (var nde in gltfRuntime.nodes) {
  79822. var node = gltfRuntime.nodes[nde];
  79823. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  79824. meshes.push(node.babylonNode);
  79825. }
  79826. }
  79827. for (var skl in gltfRuntime.skins) {
  79828. var skin = gltfRuntime.skins[skl];
  79829. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  79830. skeletons.push(skin.babylonSkeleton);
  79831. }
  79832. }
  79833. // Load buffers, shaders, materials, etc.
  79834. _this._loadBuffersAsync(gltfRuntime, function () {
  79835. _this._loadShadersAsync(gltfRuntime, function () {
  79836. importMaterials(gltfRuntime);
  79837. postLoad(gltfRuntime);
  79838. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  79839. onSuccess(meshes, [], skeletons);
  79840. }
  79841. });
  79842. }, onProgress);
  79843. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  79844. onSuccess(meshes, [], skeletons);
  79845. }
  79846. }, onError);
  79847. return true;
  79848. };
  79849. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  79850. var _this = this;
  79851. scene.useRightHandedSystem = true;
  79852. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  79853. // Load runtime extensios
  79854. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  79855. // Create nodes
  79856. _this._createNodes(gltfRuntime);
  79857. // Load buffers, shaders, materials, etc.
  79858. _this._loadBuffersAsync(gltfRuntime, function () {
  79859. _this._loadShadersAsync(gltfRuntime, function () {
  79860. importMaterials(gltfRuntime);
  79861. postLoad(gltfRuntime);
  79862. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  79863. onSuccess();
  79864. }
  79865. });
  79866. });
  79867. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  79868. onSuccess();
  79869. }
  79870. }, onError);
  79871. }, onError);
  79872. };
  79873. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  79874. var hasShaders = false;
  79875. var processShader = function (sha, shader) {
  79876. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  79877. gltfRuntime.loadedShaderCount++;
  79878. if (shaderString) {
  79879. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  79880. }
  79881. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  79882. onload();
  79883. }
  79884. }, function () {
  79885. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  79886. });
  79887. };
  79888. for (var sha in gltfRuntime.shaders) {
  79889. hasShaders = true;
  79890. var shader = gltfRuntime.shaders[sha];
  79891. if (shader) {
  79892. processShader.bind(this, sha, shader)();
  79893. }
  79894. else {
  79895. BABYLON.Tools.Error("No shader named: " + sha);
  79896. }
  79897. }
  79898. if (!hasShaders) {
  79899. onload();
  79900. }
  79901. };
  79902. ;
  79903. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  79904. var hasBuffers = false;
  79905. var processBuffer = function (buf, buffer) {
  79906. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  79907. gltfRuntime.loadedBufferCount++;
  79908. if (bufferView) {
  79909. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  79910. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  79911. }
  79912. gltfRuntime.loadedBufferViews[buf] = bufferView;
  79913. }
  79914. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  79915. onLoad();
  79916. }
  79917. }, function () {
  79918. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  79919. });
  79920. };
  79921. for (var buf in gltfRuntime.buffers) {
  79922. hasBuffers = true;
  79923. var buffer = gltfRuntime.buffers[buf];
  79924. if (buffer) {
  79925. processBuffer.bind(this, buf, buffer)();
  79926. }
  79927. else {
  79928. BABYLON.Tools.Error("No buffer named: " + buf);
  79929. }
  79930. }
  79931. if (!hasBuffers) {
  79932. onLoad();
  79933. }
  79934. };
  79935. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  79936. var currentScene = gltfRuntime.currentScene;
  79937. if (currentScene) {
  79938. // Only one scene even if multiple scenes are defined
  79939. for (var i = 0; i < currentScene.nodes.length; i++) {
  79940. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  79941. }
  79942. }
  79943. else {
  79944. // Load all scenes
  79945. for (var thing in gltfRuntime.scenes) {
  79946. currentScene = gltfRuntime.scenes[thing];
  79947. for (var i = 0; i < currentScene.nodes.length; i++) {
  79948. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  79949. }
  79950. }
  79951. }
  79952. };
  79953. GLTFLoader.Extensions = {};
  79954. return GLTFLoader;
  79955. }());
  79956. GLTF1.GLTFLoader = GLTFLoader;
  79957. ;
  79958. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  79959. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  79960. })(BABYLON || (BABYLON = {}));
  79961. //# sourceMappingURL=babylon.glTFLoader.js.map
  79962. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79963. var BABYLON;
  79964. (function (BABYLON) {
  79965. var GLTF1;
  79966. (function (GLTF1) {
  79967. /**
  79968. * Utils functions for GLTF
  79969. */
  79970. var GLTFUtils = /** @class */ (function () {
  79971. function GLTFUtils() {
  79972. }
  79973. /**
  79974. * Sets the given "parameter" matrix
  79975. * @param scene: the {BABYLON.Scene} object
  79976. * @param source: the source node where to pick the matrix
  79977. * @param parameter: the GLTF technique parameter
  79978. * @param uniformName: the name of the shader's uniform
  79979. * @param shaderMaterial: the shader material
  79980. */
  79981. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  79982. var mat = null;
  79983. if (parameter.semantic === "MODEL") {
  79984. mat = source.getWorldMatrix();
  79985. }
  79986. else if (parameter.semantic === "PROJECTION") {
  79987. mat = scene.getProjectionMatrix();
  79988. }
  79989. else if (parameter.semantic === "VIEW") {
  79990. mat = scene.getViewMatrix();
  79991. }
  79992. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  79993. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  79994. }
  79995. else if (parameter.semantic === "MODELVIEW") {
  79996. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  79997. }
  79998. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  79999. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  80000. }
  80001. else if (parameter.semantic === "MODELINVERSE") {
  80002. mat = source.getWorldMatrix().invert();
  80003. }
  80004. else if (parameter.semantic === "VIEWINVERSE") {
  80005. mat = scene.getViewMatrix().invert();
  80006. }
  80007. else if (parameter.semantic === "PROJECTIONINVERSE") {
  80008. mat = scene.getProjectionMatrix().invert();
  80009. }
  80010. else if (parameter.semantic === "MODELVIEWINVERSE") {
  80011. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  80012. }
  80013. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  80014. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  80015. }
  80016. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  80017. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  80018. }
  80019. else {
  80020. debugger;
  80021. }
  80022. if (mat) {
  80023. switch (parameter.type) {
  80024. case GLTF1.EParameterType.FLOAT_MAT2:
  80025. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  80026. break;
  80027. case GLTF1.EParameterType.FLOAT_MAT3:
  80028. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  80029. break;
  80030. case GLTF1.EParameterType.FLOAT_MAT4:
  80031. shaderMaterial.setMatrix(uniformName, mat);
  80032. break;
  80033. default: break;
  80034. }
  80035. }
  80036. };
  80037. /**
  80038. * Sets the given "parameter" matrix
  80039. * @param shaderMaterial: the shader material
  80040. * @param uniform: the name of the shader's uniform
  80041. * @param value: the value of the uniform
  80042. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  80043. */
  80044. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  80045. switch (type) {
  80046. case GLTF1.EParameterType.FLOAT:
  80047. shaderMaterial.setFloat(uniform, value);
  80048. return true;
  80049. case GLTF1.EParameterType.FLOAT_VEC2:
  80050. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  80051. return true;
  80052. case GLTF1.EParameterType.FLOAT_VEC3:
  80053. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  80054. return true;
  80055. case GLTF1.EParameterType.FLOAT_VEC4:
  80056. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  80057. return true;
  80058. default: return false;
  80059. }
  80060. };
  80061. /**
  80062. * If the uri is a base64 string
  80063. * @param uri: the uri to test
  80064. */
  80065. GLTFUtils.IsBase64 = function (uri) {
  80066. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  80067. };
  80068. /**
  80069. * Decode the base64 uri
  80070. * @param uri: the uri to decode
  80071. */
  80072. GLTFUtils.DecodeBase64 = function (uri) {
  80073. var decodedString = atob(uri.split(",")[1]);
  80074. var bufferLength = decodedString.length;
  80075. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  80076. for (var i = 0; i < bufferLength; i++) {
  80077. bufferView[i] = decodedString.charCodeAt(i);
  80078. }
  80079. return bufferView.buffer;
  80080. };
  80081. /**
  80082. * Returns the wrap mode of the texture
  80083. * @param mode: the mode value
  80084. */
  80085. GLTFUtils.GetWrapMode = function (mode) {
  80086. switch (mode) {
  80087. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  80088. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  80089. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  80090. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  80091. }
  80092. };
  80093. /**
  80094. * Returns the byte stride giving an accessor
  80095. * @param accessor: the GLTF accessor objet
  80096. */
  80097. GLTFUtils.GetByteStrideFromType = function (accessor) {
  80098. // Needs this function since "byteStride" isn't requiered in glTF format
  80099. var type = accessor.type;
  80100. switch (type) {
  80101. case "VEC2": return 2;
  80102. case "VEC3": return 3;
  80103. case "VEC4": return 4;
  80104. case "MAT2": return 4;
  80105. case "MAT3": return 9;
  80106. case "MAT4": return 16;
  80107. default: return 1;
  80108. }
  80109. };
  80110. /**
  80111. * Returns the texture filter mode giving a mode value
  80112. * @param mode: the filter mode value
  80113. */
  80114. GLTFUtils.GetTextureFilterMode = function (mode) {
  80115. switch (mode) {
  80116. case GLTF1.ETextureFilterType.LINEAR:
  80117. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  80118. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  80119. case GLTF1.ETextureFilterType.NEAREST:
  80120. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  80121. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  80122. }
  80123. };
  80124. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  80125. var byteOffset = bufferView.byteOffset + byteOffset;
  80126. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  80127. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  80128. throw new Error("Buffer access is out of range");
  80129. }
  80130. var buffer = loadedBufferView.buffer;
  80131. byteOffset += loadedBufferView.byteOffset;
  80132. switch (componentType) {
  80133. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  80134. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  80135. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  80136. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  80137. default: return new Float32Array(buffer, byteOffset, byteLength);
  80138. }
  80139. };
  80140. /**
  80141. * Returns a buffer from its accessor
  80142. * @param gltfRuntime: the GLTF runtime
  80143. * @param accessor: the GLTF accessor
  80144. */
  80145. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  80146. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  80147. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  80148. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  80149. };
  80150. /**
  80151. * Decodes a buffer view into a string
  80152. * @param view: the buffer view
  80153. */
  80154. GLTFUtils.DecodeBufferToText = function (view) {
  80155. var result = "";
  80156. var length = view.byteLength;
  80157. for (var i = 0; i < length; ++i) {
  80158. result += String.fromCharCode(view[i]);
  80159. }
  80160. return result;
  80161. };
  80162. /**
  80163. * Returns the default material of gltf. Related to
  80164. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  80165. * @param scene: the Babylon.js scene
  80166. */
  80167. GLTFUtils.GetDefaultMaterial = function (scene) {
  80168. if (!GLTFUtils._DefaultMaterial) {
  80169. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  80170. "precision highp float;",
  80171. "",
  80172. "uniform mat4 worldView;",
  80173. "uniform mat4 projection;",
  80174. "",
  80175. "attribute vec3 position;",
  80176. "",
  80177. "void main(void)",
  80178. "{",
  80179. " gl_Position = projection * worldView * vec4(position, 1.0);",
  80180. "}"
  80181. ].join("\n");
  80182. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  80183. "precision highp float;",
  80184. "",
  80185. "uniform vec4 u_emission;",
  80186. "",
  80187. "void main(void)",
  80188. "{",
  80189. " gl_FragColor = u_emission;",
  80190. "}"
  80191. ].join("\n");
  80192. var shaderPath = {
  80193. vertex: "GLTFDefaultMaterial",
  80194. fragment: "GLTFDefaultMaterial"
  80195. };
  80196. var options = {
  80197. attributes: ["position"],
  80198. uniforms: ["worldView", "projection", "u_emission"],
  80199. samplers: new Array(),
  80200. needAlphaBlending: false
  80201. };
  80202. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  80203. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  80204. }
  80205. return GLTFUtils._DefaultMaterial;
  80206. };
  80207. // The GLTF default material
  80208. GLTFUtils._DefaultMaterial = null;
  80209. return GLTFUtils;
  80210. }());
  80211. GLTF1.GLTFUtils = GLTFUtils;
  80212. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  80213. })(BABYLON || (BABYLON = {}));
  80214. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  80215. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80216. var BABYLON;
  80217. (function (BABYLON) {
  80218. var GLTF1;
  80219. (function (GLTF1) {
  80220. var GLTFLoaderExtension = /** @class */ (function () {
  80221. function GLTFLoaderExtension(name) {
  80222. this._name = name;
  80223. }
  80224. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  80225. get: function () {
  80226. return this._name;
  80227. },
  80228. enumerable: true,
  80229. configurable: true
  80230. });
  80231. /**
  80232. * Defines an override for loading the runtime
  80233. * Return true to stop further extensions from loading the runtime
  80234. */
  80235. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  80236. return false;
  80237. };
  80238. /**
  80239. * Defines an onverride for creating gltf runtime
  80240. * Return true to stop further extensions from creating the runtime
  80241. */
  80242. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  80243. return false;
  80244. };
  80245. /**
  80246. * Defines an override for loading buffers
  80247. * Return true to stop further extensions from loading this buffer
  80248. */
  80249. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  80250. return false;
  80251. };
  80252. /**
  80253. * Defines an override for loading texture buffers
  80254. * Return true to stop further extensions from loading this texture data
  80255. */
  80256. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  80257. return false;
  80258. };
  80259. /**
  80260. * Defines an override for creating textures
  80261. * Return true to stop further extensions from loading this texture
  80262. */
  80263. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  80264. return false;
  80265. };
  80266. /**
  80267. * Defines an override for loading shader strings
  80268. * Return true to stop further extensions from loading this shader data
  80269. */
  80270. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  80271. return false;
  80272. };
  80273. /**
  80274. * Defines an override for loading materials
  80275. * Return true to stop further extensions from loading this material
  80276. */
  80277. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  80278. return false;
  80279. };
  80280. // ---------
  80281. // Utilities
  80282. // ---------
  80283. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  80284. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  80285. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  80286. }, function () {
  80287. setTimeout(function () {
  80288. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  80289. });
  80290. });
  80291. };
  80292. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  80293. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  80294. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  80295. }, function () {
  80296. setTimeout(function () {
  80297. onSuccess();
  80298. });
  80299. });
  80300. };
  80301. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  80302. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  80303. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  80304. }, function () {
  80305. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  80306. });
  80307. };
  80308. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  80309. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  80310. };
  80311. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  80312. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  80313. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  80314. }, function () {
  80315. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  80316. });
  80317. };
  80318. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  80319. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  80320. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  80321. }, function () {
  80322. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  80323. });
  80324. };
  80325. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  80326. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  80327. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  80328. }, function () {
  80329. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  80330. });
  80331. };
  80332. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  80333. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  80334. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  80335. }, function () {
  80336. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  80337. });
  80338. };
  80339. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  80340. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  80341. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  80342. if (func(loaderExtension)) {
  80343. return;
  80344. }
  80345. }
  80346. defaultFunc();
  80347. };
  80348. return GLTFLoaderExtension;
  80349. }());
  80350. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  80351. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  80352. })(BABYLON || (BABYLON = {}));
  80353. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  80354. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80355. var BABYLON;
  80356. (function (BABYLON) {
  80357. var GLTF1;
  80358. (function (GLTF1) {
  80359. var BinaryExtensionBufferName = "binary_glTF";
  80360. ;
  80361. ;
  80362. var GLTFBinaryExtension = /** @class */ (function (_super) {
  80363. __extends(GLTFBinaryExtension, _super);
  80364. function GLTFBinaryExtension() {
  80365. return _super.call(this, "KHR_binary_glTF") || this;
  80366. }
  80367. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  80368. var extensionsUsed = data.json.extensionsUsed;
  80369. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  80370. return false;
  80371. }
  80372. this._bin = data.bin;
  80373. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  80374. return true;
  80375. };
  80376. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  80377. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  80378. return false;
  80379. }
  80380. if (id !== BinaryExtensionBufferName) {
  80381. return false;
  80382. }
  80383. onSuccess(this._bin);
  80384. return true;
  80385. };
  80386. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  80387. var texture = gltfRuntime.textures[id];
  80388. var source = gltfRuntime.images[texture.source];
  80389. if (!source.extensions || !(this.name in source.extensions)) {
  80390. return false;
  80391. }
  80392. var sourceExt = source.extensions[this.name];
  80393. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  80394. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  80395. onSuccess(buffer);
  80396. return true;
  80397. };
  80398. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  80399. var shader = gltfRuntime.shaders[id];
  80400. if (!shader.extensions || !(this.name in shader.extensions)) {
  80401. return false;
  80402. }
  80403. var binaryExtensionShader = shader.extensions[this.name];
  80404. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  80405. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  80406. setTimeout(function () {
  80407. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  80408. onSuccess(shaderString);
  80409. });
  80410. return true;
  80411. };
  80412. return GLTFBinaryExtension;
  80413. }(GLTF1.GLTFLoaderExtension));
  80414. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  80415. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  80416. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  80417. })(BABYLON || (BABYLON = {}));
  80418. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  80419. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80420. var BABYLON;
  80421. (function (BABYLON) {
  80422. var GLTF1;
  80423. (function (GLTF1) {
  80424. ;
  80425. ;
  80426. ;
  80427. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  80428. __extends(GLTFMaterialsCommonExtension, _super);
  80429. function GLTFMaterialsCommonExtension() {
  80430. return _super.call(this, "KHR_materials_common") || this;
  80431. }
  80432. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  80433. if (!gltfRuntime.extensions)
  80434. return false;
  80435. var extension = gltfRuntime.extensions[this.name];
  80436. if (!extension)
  80437. return false;
  80438. // Create lights
  80439. var lights = extension.lights;
  80440. if (lights) {
  80441. for (var thing in lights) {
  80442. var light = lights[thing];
  80443. switch (light.type) {
  80444. case "ambient":
  80445. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  80446. var ambient = light.ambient;
  80447. if (ambient) {
  80448. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  80449. }
  80450. break;
  80451. case "point":
  80452. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  80453. var point = light.point;
  80454. if (point) {
  80455. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  80456. }
  80457. break;
  80458. case "directional":
  80459. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  80460. var directional = light.directional;
  80461. if (directional) {
  80462. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  80463. }
  80464. break;
  80465. case "spot":
  80466. var spot = light.spot;
  80467. if (spot) {
  80468. 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);
  80469. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  80470. }
  80471. break;
  80472. default:
  80473. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  80474. break;
  80475. }
  80476. }
  80477. }
  80478. return false;
  80479. };
  80480. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  80481. var material = gltfRuntime.materials[id];
  80482. if (!material || !material.extensions)
  80483. return false;
  80484. var extension = material.extensions[this.name];
  80485. if (!extension)
  80486. return false;
  80487. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  80488. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  80489. if (extension.technique === "CONSTANT") {
  80490. standardMaterial.disableLighting = true;
  80491. }
  80492. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  80493. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  80494. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  80495. // Ambient
  80496. if (typeof extension.values.ambient === "string") {
  80497. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  80498. }
  80499. else {
  80500. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  80501. }
  80502. // Diffuse
  80503. if (typeof extension.values.diffuse === "string") {
  80504. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  80505. }
  80506. else {
  80507. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  80508. }
  80509. // Emission
  80510. if (typeof extension.values.emission === "string") {
  80511. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  80512. }
  80513. else {
  80514. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  80515. }
  80516. // Specular
  80517. if (typeof extension.values.specular === "string") {
  80518. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  80519. }
  80520. else {
  80521. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  80522. }
  80523. return true;
  80524. };
  80525. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  80526. // Create buffer from texture url
  80527. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  80528. // Create texture from buffer
  80529. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  80530. }, onError);
  80531. };
  80532. return GLTFMaterialsCommonExtension;
  80533. }(GLTF1.GLTFLoaderExtension));
  80534. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  80535. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  80536. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  80537. })(BABYLON || (BABYLON = {}));
  80538. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  80539. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80540. var BABYLON;
  80541. (function (BABYLON) {
  80542. var GLTF2;
  80543. (function (GLTF2) {
  80544. /**
  80545. * Enums
  80546. */
  80547. var EComponentType;
  80548. (function (EComponentType) {
  80549. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  80550. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  80551. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  80552. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  80553. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  80554. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  80555. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  80556. var EMeshPrimitiveMode;
  80557. (function (EMeshPrimitiveMode) {
  80558. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  80559. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  80560. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  80561. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  80562. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  80563. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  80564. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  80565. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  80566. var ETextureMagFilter;
  80567. (function (ETextureMagFilter) {
  80568. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  80569. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  80570. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  80571. var ETextureMinFilter;
  80572. (function (ETextureMinFilter) {
  80573. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  80574. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  80575. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  80576. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  80577. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  80578. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  80579. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  80580. var ETextureWrapMode;
  80581. (function (ETextureWrapMode) {
  80582. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  80583. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  80584. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  80585. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  80586. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  80587. })(BABYLON || (BABYLON = {}));
  80588. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  80589. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80590. var BABYLON;
  80591. (function (BABYLON) {
  80592. var GLTF2;
  80593. (function (GLTF2) {
  80594. var GLTFLoaderTracker = /** @class */ (function () {
  80595. function GLTFLoaderTracker(onComplete) {
  80596. this._pendingCount = 0;
  80597. this._callback = onComplete;
  80598. }
  80599. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  80600. this._pendingCount++;
  80601. };
  80602. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  80603. if (--this._pendingCount === 0) {
  80604. this._callback();
  80605. }
  80606. };
  80607. return GLTFLoaderTracker;
  80608. }());
  80609. var GLTFLoader = /** @class */ (function () {
  80610. function GLTFLoader(parent) {
  80611. this._disposed = false;
  80612. this._renderReady = false;
  80613. this._requests = new Array();
  80614. this._renderReadyObservable = new BABYLON.Observable();
  80615. // Count of pending work that needs to complete before the asset is rendered.
  80616. this._renderPendingCount = 0;
  80617. // Count of pending work that needs to complete before the loader is disposed.
  80618. this._loaderPendingCount = 0;
  80619. this._loaderTrackers = new Array();
  80620. this._parent = parent;
  80621. if (!GLTFLoader._progressEventFactory) {
  80622. if (typeof window["ProgressEvent"] === "function") {
  80623. GLTFLoader._progressEventFactory = GLTFLoader._createProgressEventByConstructor;
  80624. }
  80625. else {
  80626. GLTFLoader._progressEventFactory = GLTFLoader._createProgressEventByDocument;
  80627. }
  80628. }
  80629. }
  80630. GLTFLoader.RegisterExtension = function (extension) {
  80631. if (GLTFLoader.Extensions[extension.name]) {
  80632. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  80633. return;
  80634. }
  80635. GLTFLoader.Extensions[extension.name] = extension;
  80636. // Keep the order of registration so that extensions registered first are called first.
  80637. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  80638. };
  80639. GLTFLoader._createProgressEventByConstructor = function (name, data) {
  80640. return new ProgressEvent(name, data);
  80641. };
  80642. GLTFLoader._createProgressEventByDocument = function (name, data) {
  80643. var event = document.createEvent("ProgressEvent");
  80644. event.initProgressEvent(name, false, false, data.lengthComputable, data.loaded, data.total);
  80645. return event;
  80646. };
  80647. GLTFLoader.prototype.dispose = function () {
  80648. if (this._disposed) {
  80649. return;
  80650. }
  80651. this._disposed = true;
  80652. // Abort requests that are not complete
  80653. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  80654. var request = _a[_i];
  80655. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  80656. request.abort();
  80657. }
  80658. }
  80659. // Revoke object urls created during load
  80660. if (this._gltf.textures) {
  80661. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  80662. var texture = _c[_b];
  80663. if (texture.url) {
  80664. URL.revokeObjectURL(texture.url);
  80665. }
  80666. }
  80667. }
  80668. };
  80669. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  80670. var _this = this;
  80671. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  80672. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  80673. }, onProgress, onError);
  80674. };
  80675. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  80676. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  80677. };
  80678. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  80679. var _this = this;
  80680. this._tryCatchOnError(function () {
  80681. _this._loadData(data);
  80682. _this._babylonScene = scene;
  80683. _this._rootUrl = rootUrl;
  80684. _this._successCallback = onSuccess;
  80685. _this._progressCallback = onProgress;
  80686. _this._errorCallback = onError;
  80687. _this._addPendingData(_this);
  80688. _this._loadDefaultScene(nodeNames);
  80689. _this._loadAnimations();
  80690. _this._removePendingData(_this);
  80691. });
  80692. };
  80693. GLTFLoader.prototype._onProgress = function () {
  80694. if (!this._progressCallback) {
  80695. return;
  80696. }
  80697. var loaded = 0;
  80698. var total = 0;
  80699. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  80700. var request = _a[_i];
  80701. if (!request._loaded || !request._total) {
  80702. return;
  80703. }
  80704. loaded += request._loaded;
  80705. total += request._total;
  80706. }
  80707. this._progressCallback(GLTFLoader._progressEventFactory("GLTFLoaderProgress", {
  80708. lengthComputable: true,
  80709. loaded: loaded,
  80710. total: total
  80711. }));
  80712. };
  80713. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  80714. if (this._renderReady) {
  80715. func();
  80716. }
  80717. else {
  80718. this._renderReadyObservable.add(func);
  80719. }
  80720. };
  80721. GLTFLoader.prototype._onRenderReady = function () {
  80722. this._rootNode.babylonMesh.setEnabled(true);
  80723. this._startAnimations();
  80724. this._successCallback();
  80725. this._renderReadyObservable.notifyObservers(this);
  80726. };
  80727. GLTFLoader.prototype._onComplete = function () {
  80728. if (this._parent.onComplete) {
  80729. this._parent.onComplete();
  80730. }
  80731. this.dispose();
  80732. };
  80733. GLTFLoader.prototype._loadData = function (data) {
  80734. this._gltf = data.json;
  80735. // Assign the index of each object for convinience.
  80736. GLTFLoader._AssignIndices(this._gltf.accessors);
  80737. GLTFLoader._AssignIndices(this._gltf.animations);
  80738. GLTFLoader._AssignIndices(this._gltf.buffers);
  80739. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  80740. GLTFLoader._AssignIndices(this._gltf.images);
  80741. GLTFLoader._AssignIndices(this._gltf.materials);
  80742. GLTFLoader._AssignIndices(this._gltf.meshes);
  80743. GLTFLoader._AssignIndices(this._gltf.nodes);
  80744. GLTFLoader._AssignIndices(this._gltf.scenes);
  80745. GLTFLoader._AssignIndices(this._gltf.skins);
  80746. GLTFLoader._AssignIndices(this._gltf.textures);
  80747. if (data.bin) {
  80748. var buffers = this._gltf.buffers;
  80749. if (buffers && buffers[0] && !buffers[0].uri) {
  80750. var binaryBuffer = buffers[0];
  80751. if (binaryBuffer.byteLength != data.bin.byteLength) {
  80752. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  80753. }
  80754. binaryBuffer.loadedData = data.bin;
  80755. }
  80756. else {
  80757. BABYLON.Tools.Warn("Unexpected BIN chunk");
  80758. }
  80759. }
  80760. };
  80761. GLTFLoader.prototype._getMeshes = function () {
  80762. var meshes = new Array();
  80763. // Root mesh is always first.
  80764. meshes.push(this._rootNode.babylonMesh);
  80765. var nodes = this._gltf.nodes;
  80766. if (nodes) {
  80767. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  80768. var node = nodes_1[_i];
  80769. if (node.babylonMesh) {
  80770. meshes.push(node.babylonMesh);
  80771. }
  80772. }
  80773. }
  80774. return meshes;
  80775. };
  80776. GLTFLoader.prototype._getSkeletons = function () {
  80777. var skeletons = new Array();
  80778. var skins = this._gltf.skins;
  80779. if (skins) {
  80780. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  80781. var skin = skins_1[_i];
  80782. if (skin.babylonSkeleton) {
  80783. skeletons.push(skin.babylonSkeleton);
  80784. }
  80785. }
  80786. }
  80787. return skeletons;
  80788. };
  80789. GLTFLoader.prototype._getAnimationTargets = function () {
  80790. var targets = new Array();
  80791. var animations = this._gltf.animations;
  80792. if (animations) {
  80793. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  80794. var animation = animations_1[_i];
  80795. targets.push.apply(targets, animation.targets);
  80796. }
  80797. }
  80798. return targets;
  80799. };
  80800. GLTFLoader.prototype._startAnimations = function () {
  80801. for (var _i = 0, _a = this._getAnimationTargets(); _i < _a.length; _i++) {
  80802. var target = _a[_i];
  80803. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  80804. }
  80805. };
  80806. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  80807. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  80808. if (!scene) {
  80809. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  80810. }
  80811. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  80812. };
  80813. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  80814. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  80815. switch (this._parent.coordinateSystemMode) {
  80816. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  80817. if (!this._babylonScene.useRightHandedSystem) {
  80818. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  80819. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  80820. }
  80821. break;
  80822. }
  80823. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH: {
  80824. // do nothing
  80825. break;
  80826. }
  80827. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  80828. this._babylonScene.useRightHandedSystem = true;
  80829. break;
  80830. }
  80831. default: {
  80832. BABYLON.Tools.Error("Invalid coordinate system mode " + this._parent.coordinateSystemMode);
  80833. return;
  80834. }
  80835. }
  80836. if (this._parent.onMeshLoaded) {
  80837. this._parent.onMeshLoaded(this._rootNode.babylonMesh);
  80838. }
  80839. var nodeIndices = scene.nodes;
  80840. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  80841. node.parent = parentNode;
  80842. return true;
  80843. }, this._rootNode);
  80844. if (nodeNames) {
  80845. if (!(nodeNames instanceof Array)) {
  80846. nodeNames = [nodeNames];
  80847. }
  80848. var filteredNodeIndices_1 = new Array();
  80849. this._traverseNodes(context, nodeIndices, function (node) {
  80850. if (nodeNames.indexOf(node.name) !== -1) {
  80851. filteredNodeIndices_1.push(node.index);
  80852. return false;
  80853. }
  80854. return true;
  80855. }, this._rootNode);
  80856. nodeIndices = filteredNodeIndices_1;
  80857. }
  80858. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  80859. var index = nodeIndices_1[_i];
  80860. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  80861. if (!node) {
  80862. throw new Error(context + ": Failed to find node " + index);
  80863. }
  80864. this._loadNode("#/nodes/" + index, node);
  80865. }
  80866. // Disable the root mesh until the asset is ready to render.
  80867. this._rootNode.babylonMesh.setEnabled(false);
  80868. };
  80869. GLTFLoader.prototype._loadNode = function (context, node) {
  80870. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  80871. return;
  80872. }
  80873. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  80874. node.babylonMesh.hasVertexAlpha = true;
  80875. this._loadTransform(node);
  80876. if (node.mesh != null) {
  80877. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  80878. if (!mesh) {
  80879. throw new Error(context + ": Failed to find mesh " + node.mesh);
  80880. }
  80881. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  80882. }
  80883. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  80884. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  80885. node.babylonAnimationTargets.push(node.babylonMesh);
  80886. if (node.skin != null) {
  80887. var skin = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  80888. if (!skin) {
  80889. throw new Error(context + ": Failed to find skin " + node.skin);
  80890. }
  80891. node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin);
  80892. }
  80893. if (node.camera != null) {
  80894. // TODO: handle cameras
  80895. }
  80896. if (node.children) {
  80897. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  80898. var index = _a[_i];
  80899. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  80900. if (!childNode) {
  80901. throw new Error(context + ": Failed to find child node " + index);
  80902. }
  80903. this._loadNode("#/nodes/" + index, childNode);
  80904. }
  80905. }
  80906. if (this._parent.onMeshLoaded) {
  80907. this._parent.onMeshLoaded(node.babylonMesh);
  80908. }
  80909. };
  80910. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  80911. var _this = this;
  80912. var primitives = mesh.primitives;
  80913. if (!primitives || primitives.length === 0) {
  80914. throw new Error(context + ": Primitives are missing");
  80915. }
  80916. this._createMorphTargets(context, node, mesh);
  80917. this._loadAllVertexDataAsync(context, mesh, function () {
  80918. _this._loadMorphTargets(context, node, mesh);
  80919. var vertexData = new BABYLON.VertexData();
  80920. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  80921. var primitive = primitives_1[_i];
  80922. vertexData.merge(primitive.vertexData);
  80923. }
  80924. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  80925. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  80926. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  80927. node.babylonMesh.subMeshes = [];
  80928. var verticesStart = 0;
  80929. var indicesStart = 0;
  80930. for (var index = 0; index < primitives.length; index++) {
  80931. var vertexData_1 = primitives[index].vertexData;
  80932. var verticesCount = vertexData_1.positions.length;
  80933. var indicesCount = vertexData_1.indices.length;
  80934. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  80935. verticesStart += verticesCount;
  80936. indicesStart += indicesCount;
  80937. }
  80938. ;
  80939. });
  80940. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  80941. node.babylonMesh.material = multiMaterial;
  80942. var subMaterials = multiMaterial.subMaterials;
  80943. var _loop_1 = function (index) {
  80944. var primitive = primitives[index];
  80945. if (primitive.material == null) {
  80946. subMaterials[index] = this_1._getDefaultMaterial();
  80947. }
  80948. else {
  80949. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  80950. if (!material) {
  80951. throw new Error(context + ": Failed to find material " + primitive.material);
  80952. }
  80953. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  80954. if (isNew && _this._parent.onMaterialLoaded) {
  80955. _this._parent.onMaterialLoaded(babylonMaterial);
  80956. }
  80957. subMaterials[index] = babylonMaterial;
  80958. });
  80959. }
  80960. };
  80961. var this_1 = this;
  80962. for (var index = 0; index < primitives.length; index++) {
  80963. _loop_1(index);
  80964. }
  80965. ;
  80966. };
  80967. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  80968. var primitives = mesh.primitives;
  80969. var numRemainingPrimitives = primitives.length;
  80970. var _loop_2 = function (index) {
  80971. var primitive = primitives[index];
  80972. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  80973. primitive.vertexData = vertexData;
  80974. if (--numRemainingPrimitives === 0) {
  80975. onSuccess();
  80976. }
  80977. });
  80978. };
  80979. var this_2 = this;
  80980. for (var index = 0; index < primitives.length; index++) {
  80981. _loop_2(index);
  80982. }
  80983. };
  80984. /**
  80985. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  80986. * @param {ArrayBufferView} data
  80987. * @param {IGLTFAccessor} accessor
  80988. */
  80989. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  80990. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  80991. return data;
  80992. }
  80993. var buffer = data;
  80994. var factor = 1;
  80995. switch (accessor.componentType) {
  80996. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  80997. factor = 1 / 255;
  80998. break;
  80999. }
  81000. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  81001. factor = 1 / 65535;
  81002. break;
  81003. }
  81004. default: {
  81005. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  81006. }
  81007. }
  81008. var result = new Float32Array(accessor.count * 2);
  81009. for (var i = 0; i < result.length; ++i) {
  81010. result[i] = buffer[i] * factor;
  81011. }
  81012. return result;
  81013. };
  81014. /**
  81015. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  81016. * @param {ArrayBufferView} data
  81017. * @param {IGLTFAccessor} accessor
  81018. */
  81019. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  81020. var colorComponentCount = GLTFLoader._GetNumComponents(accessor.type);
  81021. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  81022. return data;
  81023. }
  81024. var buffer = data;
  81025. var factor = 1;
  81026. switch (accessor.componentType) {
  81027. case GLTF2.EComponentType.FLOAT: {
  81028. factor = 1;
  81029. break;
  81030. }
  81031. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  81032. factor = 1 / 255;
  81033. break;
  81034. }
  81035. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  81036. factor = 1 / 65535;
  81037. break;
  81038. }
  81039. default: {
  81040. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  81041. }
  81042. }
  81043. var result = new Float32Array(accessor.count * 4);
  81044. if (colorComponentCount === 4) {
  81045. for (var i = 0; i < result.length; ++i) {
  81046. result[i] = buffer[i] * factor;
  81047. }
  81048. }
  81049. else {
  81050. var offset = 0;
  81051. for (var i = 0; i < result.length; ++i) {
  81052. if ((i + 1) % 4 === 0) {
  81053. result[i] = 1;
  81054. }
  81055. else {
  81056. result[i] = buffer[offset++] * factor;
  81057. }
  81058. }
  81059. }
  81060. return result;
  81061. };
  81062. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  81063. var _this = this;
  81064. var attributes = primitive.attributes;
  81065. if (!attributes) {
  81066. throw new Error(context + ": Attributes are missing");
  81067. }
  81068. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  81069. // TODO: handle other primitive modes
  81070. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  81071. }
  81072. var vertexData = new BABYLON.VertexData();
  81073. var numRemainingAttributes = Object.keys(attributes).length;
  81074. var _loop_3 = function (attribute) {
  81075. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  81076. if (!accessor) {
  81077. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  81078. }
  81079. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  81080. switch (attribute) {
  81081. case "POSITION": {
  81082. vertexData.positions = data;
  81083. break;
  81084. }
  81085. case "NORMAL": {
  81086. vertexData.normals = data;
  81087. break;
  81088. }
  81089. case "TANGENT": {
  81090. vertexData.tangents = data;
  81091. break;
  81092. }
  81093. case "TEXCOORD_0": {
  81094. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  81095. break;
  81096. }
  81097. case "TEXCOORD_1": {
  81098. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  81099. break;
  81100. }
  81101. case "JOINTS_0": {
  81102. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  81103. break;
  81104. }
  81105. case "WEIGHTS_0": {
  81106. //TODO: need to add support for normalized weights.
  81107. vertexData.matricesWeights = data;
  81108. break;
  81109. }
  81110. case "COLOR_0": {
  81111. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  81112. break;
  81113. }
  81114. default: {
  81115. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  81116. break;
  81117. }
  81118. }
  81119. if (--numRemainingAttributes === 0) {
  81120. if (primitive.indices == null) {
  81121. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  81122. for (var i = 0; i < vertexData.indices.length; i++) {
  81123. vertexData.indices[i] = i;
  81124. }
  81125. onSuccess(vertexData);
  81126. }
  81127. else {
  81128. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  81129. if (!indicesAccessor) {
  81130. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  81131. }
  81132. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  81133. vertexData.indices = data;
  81134. onSuccess(vertexData);
  81135. });
  81136. }
  81137. }
  81138. });
  81139. };
  81140. var this_3 = this;
  81141. for (var attribute in attributes) {
  81142. _loop_3(attribute);
  81143. }
  81144. };
  81145. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  81146. var primitives = mesh.primitives;
  81147. var targets = primitives[0].targets;
  81148. if (!targets) {
  81149. return;
  81150. }
  81151. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  81152. var primitive = primitives_2[_i];
  81153. if (!primitive.targets || primitive.targets.length != targets.length) {
  81154. throw new Error(context + ": All primitives are required to list the same number of targets");
  81155. }
  81156. }
  81157. var morphTargetManager = new BABYLON.MorphTargetManager();
  81158. node.babylonMesh.morphTargetManager = morphTargetManager;
  81159. for (var index = 0; index < targets.length; index++) {
  81160. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  81161. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  81162. }
  81163. };
  81164. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  81165. var morphTargetManager = node.babylonMesh.morphTargetManager;
  81166. if (!morphTargetManager) {
  81167. return;
  81168. }
  81169. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  81170. var numTargets = morphTargetManager.numTargets;
  81171. for (var index = 0; index < numTargets; index++) {
  81172. var vertexData = new BABYLON.VertexData();
  81173. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  81174. var primitive = _a[_i];
  81175. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  81176. }
  81177. if (!vertexData.positions) {
  81178. throw new Error(context + ": Positions are missing");
  81179. }
  81180. var target = morphTargetManager.getTarget(index);
  81181. target.setPositions(vertexData.positions);
  81182. target.setNormals(vertexData.normals);
  81183. target.setTangents(vertexData.tangents);
  81184. }
  81185. });
  81186. };
  81187. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  81188. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  81189. var _loop_4 = function (primitive) {
  81190. var targets = primitive.targets;
  81191. primitive.targetsVertexData = new Array(targets.length);
  81192. var _loop_5 = function (index) {
  81193. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  81194. primitive.targetsVertexData[index] = vertexData;
  81195. if (--numRemainingTargets === 0) {
  81196. onSuccess();
  81197. }
  81198. });
  81199. };
  81200. for (var index = 0; index < targets.length; index++) {
  81201. _loop_5(index);
  81202. }
  81203. };
  81204. var this_4 = this;
  81205. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  81206. var primitive = _a[_i];
  81207. _loop_4(primitive);
  81208. }
  81209. };
  81210. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  81211. var targetVertexData = new BABYLON.VertexData();
  81212. var numRemainingAttributes = Object.keys(attributes).length;
  81213. var _loop_6 = function (attribute) {
  81214. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  81215. if (!accessor) {
  81216. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  81217. }
  81218. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  81219. // glTF stores morph target information as deltas while babylon.js expects the final data.
  81220. // As a result we have to add the original data to the delta to calculate the final data.
  81221. var values = data;
  81222. switch (attribute) {
  81223. case "POSITION": {
  81224. for (var i = 0; i < values.length; i++) {
  81225. values[i] += vertexData.positions[i];
  81226. }
  81227. targetVertexData.positions = values;
  81228. break;
  81229. }
  81230. case "NORMAL": {
  81231. for (var i = 0; i < values.length; i++) {
  81232. values[i] += vertexData.normals[i];
  81233. }
  81234. targetVertexData.normals = values;
  81235. break;
  81236. }
  81237. case "TANGENT": {
  81238. // Tangent data for morph targets is stored as xyz delta.
  81239. // The vertexData.tangent is stored as xyzw.
  81240. // So we need to skip every fourth vertexData.tangent.
  81241. for (var i = 0, j = 0; i < values.length; i++, j++) {
  81242. values[i] += vertexData.tangents[j];
  81243. if ((i + 1) % 3 == 0) {
  81244. j++;
  81245. }
  81246. }
  81247. targetVertexData.tangents = values;
  81248. break;
  81249. }
  81250. default: {
  81251. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  81252. break;
  81253. }
  81254. }
  81255. if (--numRemainingAttributes === 0) {
  81256. onSuccess(targetVertexData);
  81257. }
  81258. });
  81259. };
  81260. var this_5 = this;
  81261. for (var attribute in attributes) {
  81262. _loop_6(attribute);
  81263. }
  81264. };
  81265. GLTFLoader.prototype._loadTransform = function (node) {
  81266. var position = BABYLON.Vector3.Zero();
  81267. var rotation = BABYLON.Quaternion.Identity();
  81268. var scaling = BABYLON.Vector3.One();
  81269. if (node.matrix) {
  81270. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  81271. matrix.decompose(scaling, rotation, position);
  81272. }
  81273. else {
  81274. if (node.translation)
  81275. position = BABYLON.Vector3.FromArray(node.translation);
  81276. if (node.rotation)
  81277. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  81278. if (node.scale)
  81279. scaling = BABYLON.Vector3.FromArray(node.scale);
  81280. }
  81281. node.babylonMesh.position = position;
  81282. node.babylonMesh.rotationQuaternion = rotation;
  81283. node.babylonMesh.scaling = scaling;
  81284. };
  81285. GLTFLoader.prototype._loadSkin = function (context, skin) {
  81286. var _this = this;
  81287. var skeletonId = "skeleton" + skin.index;
  81288. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  81289. if (skin.inverseBindMatrices == null) {
  81290. this._loadBones(context, skin, null);
  81291. }
  81292. else {
  81293. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  81294. if (!accessor) {
  81295. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  81296. }
  81297. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  81298. _this._loadBones(context, skin, data);
  81299. });
  81300. }
  81301. return skin.babylonSkeleton;
  81302. };
  81303. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  81304. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  81305. node.babylonBones = node.babylonBones || {};
  81306. node.babylonBones[skin.index] = babylonBone;
  81307. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  81308. node.babylonAnimationTargets.push(babylonBone);
  81309. return babylonBone;
  81310. };
  81311. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  81312. var babylonBones = {};
  81313. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  81314. var index = _a[_i];
  81315. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  81316. if (!node) {
  81317. throw new Error(context + ": Failed to find joint " + index);
  81318. }
  81319. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  81320. }
  81321. };
  81322. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  81323. var babylonBone = babylonBones[node.index];
  81324. if (babylonBone) {
  81325. return babylonBone;
  81326. }
  81327. var boneIndex = skin.joints.indexOf(node.index);
  81328. var baseMatrix = BABYLON.Matrix.Identity();
  81329. if (inverseBindMatrixData && boneIndex !== -1) {
  81330. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  81331. baseMatrix.invertToRef(baseMatrix);
  81332. }
  81333. var babylonParentBone = null;
  81334. if (node.index !== skin.skeleton && node.parent && node.parent !== this._rootNode) {
  81335. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  81336. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  81337. }
  81338. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  81339. babylonBones[node.index] = babylonBone;
  81340. return babylonBone;
  81341. };
  81342. GLTFLoader.prototype._getNodeMatrix = function (node) {
  81343. return node.matrix ?
  81344. BABYLON.Matrix.FromArray(node.matrix) :
  81345. 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());
  81346. };
  81347. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  81348. if (parentNode === void 0) { parentNode = null; }
  81349. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  81350. var index = indices_1[_i];
  81351. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  81352. if (!node) {
  81353. throw new Error(context + ": Failed to find node " + index);
  81354. }
  81355. this._traverseNode(context, node, action, parentNode);
  81356. }
  81357. };
  81358. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  81359. if (parentNode === void 0) { parentNode = null; }
  81360. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  81361. return;
  81362. }
  81363. if (!action(node, parentNode)) {
  81364. return;
  81365. }
  81366. if (node.children) {
  81367. this._traverseNodes(context, node.children, action, node);
  81368. }
  81369. };
  81370. GLTFLoader.prototype._loadAnimations = function () {
  81371. var animations = this._gltf.animations;
  81372. if (!animations) {
  81373. return;
  81374. }
  81375. for (var index = 0; index < animations.length; index++) {
  81376. var animation = animations[index];
  81377. this._loadAnimation("#/animations/" + index, animation);
  81378. }
  81379. };
  81380. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  81381. animation.targets = [];
  81382. for (var index = 0; index < animation.channels.length; index++) {
  81383. var channel = GLTFLoader._GetProperty(animation.channels, index);
  81384. if (!channel) {
  81385. throw new Error(context + ": Failed to find channel " + index);
  81386. }
  81387. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  81388. if (!sampler) {
  81389. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  81390. }
  81391. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  81392. }
  81393. };
  81394. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  81395. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  81396. if (!targetNode) {
  81397. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  81398. }
  81399. var targetPath;
  81400. var animationType;
  81401. switch (channel.target.path) {
  81402. case "translation": {
  81403. targetPath = "position";
  81404. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  81405. break;
  81406. }
  81407. case "rotation": {
  81408. targetPath = "rotationQuaternion";
  81409. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  81410. break;
  81411. }
  81412. case "scale": {
  81413. targetPath = "scaling";
  81414. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  81415. break;
  81416. }
  81417. case "weights": {
  81418. targetPath = "influence";
  81419. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  81420. break;
  81421. }
  81422. default: {
  81423. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  81424. }
  81425. }
  81426. var inputData;
  81427. var outputData;
  81428. var checkSuccess = function () {
  81429. if (!inputData || !outputData) {
  81430. return;
  81431. }
  81432. var outputBufferOffset = 0;
  81433. var getNextOutputValue;
  81434. switch (targetPath) {
  81435. case "position": {
  81436. getNextOutputValue = function () {
  81437. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  81438. outputBufferOffset += 3;
  81439. return value;
  81440. };
  81441. break;
  81442. }
  81443. case "rotationQuaternion": {
  81444. getNextOutputValue = function () {
  81445. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  81446. outputBufferOffset += 4;
  81447. return value;
  81448. };
  81449. break;
  81450. }
  81451. case "scaling": {
  81452. getNextOutputValue = function () {
  81453. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  81454. outputBufferOffset += 3;
  81455. return value;
  81456. };
  81457. break;
  81458. }
  81459. case "influence": {
  81460. getNextOutputValue = function () {
  81461. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  81462. var value = new Array(numTargets);
  81463. for (var i = 0; i < numTargets; i++) {
  81464. value[i] = outputData[outputBufferOffset++];
  81465. }
  81466. return value;
  81467. };
  81468. break;
  81469. }
  81470. }
  81471. var getNextKey;
  81472. switch (sampler.interpolation) {
  81473. case "LINEAR": {
  81474. getNextKey = function (frameIndex) { return ({
  81475. frame: inputData[frameIndex],
  81476. value: getNextOutputValue()
  81477. }); };
  81478. break;
  81479. }
  81480. case "CUBICSPLINE": {
  81481. getNextKey = function (frameIndex) { return ({
  81482. frame: inputData[frameIndex],
  81483. inTangent: getNextOutputValue(),
  81484. value: getNextOutputValue(),
  81485. outTangent: getNextOutputValue()
  81486. }); };
  81487. break;
  81488. }
  81489. default: {
  81490. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  81491. }
  81492. }
  81493. ;
  81494. var keys = new Array(inputData.length);
  81495. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  81496. keys[frameIndex] = getNextKey(frameIndex);
  81497. }
  81498. if (targetPath === "influence") {
  81499. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  81500. var _loop_7 = function (targetIndex) {
  81501. var morphTarget = morphTargetManager.getTarget(targetIndex);
  81502. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  81503. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  81504. babylonAnimation.setKeys(keys.map(function (key) { return ({
  81505. frame: key.frame,
  81506. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  81507. value: key.value[targetIndex],
  81508. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  81509. }); }));
  81510. morphTarget.animations.push(babylonAnimation);
  81511. animation.targets.push(morphTarget);
  81512. };
  81513. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  81514. _loop_7(targetIndex);
  81515. }
  81516. }
  81517. else {
  81518. var animationName = animation.name || "anim" + animation.index;
  81519. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  81520. babylonAnimation.setKeys(keys);
  81521. if (targetNode.babylonAnimationTargets) {
  81522. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  81523. var target = _a[_i];
  81524. target.animations.push(babylonAnimation.clone());
  81525. animation.targets.push(target);
  81526. }
  81527. }
  81528. }
  81529. };
  81530. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  81531. if (!inputAccessor) {
  81532. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  81533. }
  81534. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  81535. inputData = data;
  81536. checkSuccess();
  81537. });
  81538. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  81539. if (!outputAccessor) {
  81540. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  81541. }
  81542. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  81543. outputData = data;
  81544. checkSuccess();
  81545. });
  81546. };
  81547. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  81548. var _this = this;
  81549. this._addPendingData(buffer);
  81550. if (buffer.loadedData) {
  81551. onSuccess(buffer.loadedData);
  81552. this._removePendingData(buffer);
  81553. }
  81554. else if (buffer.loadedObservable) {
  81555. buffer.loadedObservable.add(function (buffer) {
  81556. onSuccess(buffer.loadedData);
  81557. _this._removePendingData(buffer);
  81558. });
  81559. }
  81560. else {
  81561. if (!buffer.uri) {
  81562. throw new Error(context + ": Uri is missing");
  81563. }
  81564. buffer.loadedObservable = new BABYLON.Observable();
  81565. buffer.loadedObservable.add(function (buffer) {
  81566. onSuccess(buffer.loadedData);
  81567. _this._removePendingData(buffer);
  81568. });
  81569. this._loadUriAsync(context, buffer.uri, function (data) {
  81570. buffer.loadedData = data;
  81571. buffer.loadedObservable.notifyObservers(buffer);
  81572. buffer.loadedObservable = undefined;
  81573. });
  81574. }
  81575. };
  81576. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  81577. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  81578. if (!buffer) {
  81579. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  81580. }
  81581. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  81582. var data;
  81583. try {
  81584. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  81585. }
  81586. catch (e) {
  81587. throw new Error(context + ": " + e.message);
  81588. }
  81589. onSuccess(data);
  81590. });
  81591. };
  81592. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  81593. var _this = this;
  81594. if (accessor.sparse) {
  81595. throw new Error(context + ": Sparse accessors are not currently supported");
  81596. }
  81597. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  81598. if (!bufferView) {
  81599. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  81600. }
  81601. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  81602. var numComponents = GLTFLoader._GetNumComponents(accessor.type);
  81603. if (numComponents === 0) {
  81604. throw new Error(context + ": Invalid type " + accessor.type);
  81605. }
  81606. var data;
  81607. var byteOffset = accessor.byteOffset || 0;
  81608. var byteStride = bufferView.byteStride;
  81609. try {
  81610. switch (accessor.componentType) {
  81611. case GLTF2.EComponentType.BYTE: {
  81612. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  81613. break;
  81614. }
  81615. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  81616. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  81617. break;
  81618. }
  81619. case GLTF2.EComponentType.SHORT: {
  81620. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  81621. break;
  81622. }
  81623. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  81624. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  81625. break;
  81626. }
  81627. case GLTF2.EComponentType.UNSIGNED_INT: {
  81628. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  81629. break;
  81630. }
  81631. case GLTF2.EComponentType.FLOAT: {
  81632. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  81633. break;
  81634. }
  81635. default: {
  81636. throw new Error(context + ": Invalid component type " + accessor.componentType);
  81637. }
  81638. }
  81639. }
  81640. catch (e) {
  81641. throw new Error(context + ": " + e);
  81642. }
  81643. onSuccess(data);
  81644. });
  81645. };
  81646. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  81647. byteOffset += data.byteOffset;
  81648. var targetLength = count * numComponents;
  81649. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  81650. return new typedArray(data.buffer, byteOffset, targetLength);
  81651. }
  81652. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  81653. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  81654. var targetBuffer = new typedArray(targetLength);
  81655. var sourceIndex = 0;
  81656. var targetIndex = 0;
  81657. while (targetIndex < targetLength) {
  81658. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  81659. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  81660. targetIndex++;
  81661. }
  81662. sourceIndex += elementStride;
  81663. }
  81664. return targetBuffer;
  81665. };
  81666. GLTFLoader.prototype._addPendingData = function (data) {
  81667. if (!this._renderReady) {
  81668. this._renderPendingCount++;
  81669. }
  81670. this._addLoaderPendingData(data);
  81671. };
  81672. GLTFLoader.prototype._removePendingData = function (data) {
  81673. var _this = this;
  81674. if (!this._renderReady) {
  81675. if (--this._renderPendingCount === 0) {
  81676. this._addLoaderPendingData(this);
  81677. this._compileMaterialsAsync(function () {
  81678. _this._compileShadowGeneratorsAsync(function () {
  81679. _this._removeLoaderPendingData(_this);
  81680. _this._renderReady = true;
  81681. _this._onRenderReady();
  81682. });
  81683. });
  81684. }
  81685. }
  81686. this._removeLoaderPendingData(data);
  81687. };
  81688. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  81689. this._loaderPendingCount++;
  81690. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  81691. var tracker = _a[_i];
  81692. tracker._addPendingData(data);
  81693. }
  81694. };
  81695. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  81696. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  81697. var tracker = _a[_i];
  81698. tracker._removePendingData(data);
  81699. }
  81700. if (--this._loaderPendingCount === 0) {
  81701. this._onComplete();
  81702. }
  81703. };
  81704. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  81705. var _this = this;
  81706. var tracker = new GLTFLoaderTracker(function () {
  81707. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  81708. onComplete();
  81709. });
  81710. this._loaderTrackers.push(tracker);
  81711. this._addLoaderPendingData(tracker);
  81712. action();
  81713. this._removeLoaderPendingData(tracker);
  81714. };
  81715. GLTFLoader.prototype._getDefaultMaterial = function () {
  81716. if (!this._defaultMaterial) {
  81717. var id = "__gltf_default";
  81718. var material = this._babylonScene.getMaterialByName(id);
  81719. if (!material) {
  81720. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  81721. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  81722. material.metallic = 1;
  81723. material.roughness = 1;
  81724. }
  81725. this._defaultMaterial = material;
  81726. }
  81727. return this._defaultMaterial;
  81728. };
  81729. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  81730. var babylonMaterial = material.babylonMaterial;
  81731. // Ensure metallic workflow
  81732. babylonMaterial.metallic = 1;
  81733. babylonMaterial.roughness = 1;
  81734. var properties = material.pbrMetallicRoughness;
  81735. if (!properties) {
  81736. return;
  81737. }
  81738. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  81739. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  81740. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  81741. if (properties.baseColorTexture) {
  81742. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  81743. if (!texture) {
  81744. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  81745. }
  81746. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  81747. }
  81748. if (properties.metallicRoughnessTexture) {
  81749. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  81750. if (!texture) {
  81751. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  81752. }
  81753. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  81754. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  81755. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  81756. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  81757. }
  81758. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  81759. };
  81760. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  81761. if (material.babylonMaterial) {
  81762. assign(material.babylonMaterial, false);
  81763. return;
  81764. }
  81765. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  81766. return;
  81767. }
  81768. this._createPbrMaterial(material);
  81769. this._loadMaterialBaseProperties(context, material);
  81770. this._loadMaterialMetallicRoughnessProperties(context, material);
  81771. assign(material.babylonMaterial, true);
  81772. };
  81773. GLTFLoader.prototype._createPbrMaterial = function (material) {
  81774. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  81775. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  81776. material.babylonMaterial = babylonMaterial;
  81777. };
  81778. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  81779. var babylonMaterial = material.babylonMaterial;
  81780. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  81781. if (material.doubleSided) {
  81782. babylonMaterial.backFaceCulling = false;
  81783. babylonMaterial.twoSidedLighting = true;
  81784. }
  81785. if (material.normalTexture) {
  81786. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  81787. if (!texture) {
  81788. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  81789. }
  81790. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  81791. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  81792. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  81793. if (material.normalTexture.scale != null) {
  81794. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  81795. }
  81796. }
  81797. if (material.occlusionTexture) {
  81798. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  81799. if (!texture) {
  81800. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  81801. }
  81802. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  81803. babylonMaterial.useAmbientInGrayScale = true;
  81804. if (material.occlusionTexture.strength != null) {
  81805. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  81806. }
  81807. }
  81808. if (material.emissiveTexture) {
  81809. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  81810. if (!texture) {
  81811. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  81812. }
  81813. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  81814. }
  81815. };
  81816. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  81817. var babylonMaterial = material.babylonMaterial;
  81818. var alphaMode = material.alphaMode || "OPAQUE";
  81819. switch (alphaMode) {
  81820. case "OPAQUE": {
  81821. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  81822. break;
  81823. }
  81824. case "MASK": {
  81825. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  81826. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  81827. if (colorFactor) {
  81828. if (colorFactor[3] == 0) {
  81829. babylonMaterial.alphaCutOff = 1;
  81830. }
  81831. else {
  81832. babylonMaterial.alphaCutOff /= colorFactor[3];
  81833. }
  81834. }
  81835. if (babylonMaterial.albedoTexture) {
  81836. babylonMaterial.albedoTexture.hasAlpha = true;
  81837. }
  81838. break;
  81839. }
  81840. case "BLEND": {
  81841. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  81842. if (colorFactor) {
  81843. babylonMaterial.alpha = colorFactor[3];
  81844. }
  81845. if (babylonMaterial.albedoTexture) {
  81846. babylonMaterial.albedoTexture.hasAlpha = true;
  81847. babylonMaterial.useAlphaFromAlbedoTexture = true;
  81848. }
  81849. break;
  81850. }
  81851. default: {
  81852. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  81853. }
  81854. }
  81855. };
  81856. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  81857. var _this = this;
  81858. var sampler = (texture.sampler == null ? {} : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  81859. if (!sampler) {
  81860. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  81861. }
  81862. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  81863. var samplingMode = GLTFLoader._GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  81864. this._addPendingData(texture);
  81865. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  81866. _this._tryCatchOnError(function () {
  81867. _this._removePendingData(texture);
  81868. });
  81869. }, function (message) {
  81870. _this._tryCatchOnError(function () {
  81871. throw new Error(context + ": " + message);
  81872. });
  81873. });
  81874. if (texture.url) {
  81875. babylonTexture.updateURL(texture.url);
  81876. }
  81877. else if (texture.dataReadyObservable) {
  81878. texture.dataReadyObservable.add(function (texture) {
  81879. babylonTexture.updateURL(texture.url);
  81880. });
  81881. }
  81882. else {
  81883. texture.dataReadyObservable = new BABYLON.Observable();
  81884. texture.dataReadyObservable.add(function (texture) {
  81885. babylonTexture.updateURL(texture.url);
  81886. });
  81887. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  81888. if (!image_1) {
  81889. throw new Error(context + ": Failed to find source " + texture.source);
  81890. }
  81891. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  81892. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  81893. texture.dataReadyObservable.notifyObservers(texture);
  81894. texture.dataReadyObservable = undefined;
  81895. });
  81896. }
  81897. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  81898. babylonTexture.wrapU = GLTFLoader._GetTextureWrapMode(sampler.wrapS);
  81899. babylonTexture.wrapV = GLTFLoader._GetTextureWrapMode(sampler.wrapT);
  81900. babylonTexture.name = texture.name || "texture" + texture.index;
  81901. if (this._parent.onTextureLoaded) {
  81902. this._parent.onTextureLoaded(babylonTexture);
  81903. }
  81904. return babylonTexture;
  81905. };
  81906. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  81907. if (image.uri) {
  81908. this._loadUriAsync(context, image.uri, onSuccess);
  81909. }
  81910. else {
  81911. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  81912. if (!bufferView) {
  81913. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  81914. }
  81915. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  81916. }
  81917. };
  81918. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  81919. var _this = this;
  81920. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  81921. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  81922. return;
  81923. }
  81924. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  81925. throw new Error(context + ": Uri '" + uri + "' is invalid");
  81926. }
  81927. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  81928. _this._tryCatchOnError(function () {
  81929. onSuccess(new Uint8Array(data));
  81930. });
  81931. }, function (event) {
  81932. _this._tryCatchOnError(function () {
  81933. if (request && !_this._renderReady) {
  81934. request._loaded = event.loaded;
  81935. request._total = event.total;
  81936. _this._onProgress();
  81937. }
  81938. });
  81939. }, this._babylonScene.database, true, function (request) {
  81940. _this._tryCatchOnError(function () {
  81941. throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  81942. });
  81943. });
  81944. if (request) {
  81945. request._loaded = null;
  81946. request._total = null;
  81947. this._requests.push(request);
  81948. }
  81949. };
  81950. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  81951. if (this._disposed) {
  81952. return;
  81953. }
  81954. try {
  81955. handler();
  81956. }
  81957. catch (e) {
  81958. BABYLON.Tools.Error("glTF Loader: " + e.message);
  81959. if (this._errorCallback) {
  81960. this._errorCallback(e.message);
  81961. }
  81962. this.dispose();
  81963. }
  81964. };
  81965. GLTFLoader._AssignIndices = function (array) {
  81966. if (array) {
  81967. for (var index = 0; index < array.length; index++) {
  81968. array[index].index = index;
  81969. }
  81970. }
  81971. };
  81972. GLTFLoader._GetProperty = function (array, index) {
  81973. if (!array || index == undefined || !array[index]) {
  81974. return null;
  81975. }
  81976. return array[index];
  81977. };
  81978. GLTFLoader._GetTextureWrapMode = function (mode) {
  81979. // Set defaults if undefined
  81980. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  81981. switch (mode) {
  81982. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  81983. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  81984. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  81985. default:
  81986. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  81987. return BABYLON.Texture.WRAP_ADDRESSMODE;
  81988. }
  81989. };
  81990. GLTFLoader._GetTextureSamplingMode = function (magFilter, minFilter) {
  81991. // Set defaults if undefined
  81992. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  81993. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  81994. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  81995. switch (minFilter) {
  81996. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  81997. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  81998. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  81999. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  82000. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  82001. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  82002. default:
  82003. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  82004. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  82005. }
  82006. }
  82007. else {
  82008. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  82009. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  82010. }
  82011. switch (minFilter) {
  82012. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  82013. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  82014. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  82015. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  82016. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  82017. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  82018. default:
  82019. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  82020. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  82021. }
  82022. }
  82023. };
  82024. GLTFLoader._GetNumComponents = function (type) {
  82025. switch (type) {
  82026. case "SCALAR": return 1;
  82027. case "VEC2": return 2;
  82028. case "VEC3": return 3;
  82029. case "VEC4": return 4;
  82030. case "MAT2": return 4;
  82031. case "MAT3": return 9;
  82032. case "MAT4": return 16;
  82033. }
  82034. return 0;
  82035. };
  82036. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  82037. var _this = this;
  82038. if (!this._parent.compileMaterials) {
  82039. onSuccess();
  82040. return;
  82041. }
  82042. if (this._parent.useClipPlane) {
  82043. babylonMaterial.forceCompilation(babylonMesh, function () {
  82044. babylonMaterial.forceCompilation(babylonMesh, function () {
  82045. _this._tryCatchOnError(onSuccess);
  82046. }, { clipPlane: true });
  82047. });
  82048. }
  82049. else {
  82050. babylonMaterial.forceCompilation(babylonMesh, function () {
  82051. _this._tryCatchOnError(onSuccess);
  82052. });
  82053. }
  82054. };
  82055. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  82056. if (!this._parent.compileMaterials || !this._gltf.materials) {
  82057. onSuccess();
  82058. return;
  82059. }
  82060. var meshes = this._getMeshes();
  82061. var remaining = 0;
  82062. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  82063. var mesh = meshes_1[_i];
  82064. if (mesh.material instanceof BABYLON.MultiMaterial) {
  82065. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  82066. var subMaterial = _b[_a];
  82067. if (subMaterial) {
  82068. remaining++;
  82069. }
  82070. }
  82071. }
  82072. }
  82073. if (remaining === 0) {
  82074. onSuccess();
  82075. return;
  82076. }
  82077. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  82078. var mesh = meshes_2[_c];
  82079. if (mesh.material instanceof BABYLON.MultiMaterial) {
  82080. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  82081. var subMaterial = _e[_d];
  82082. if (subMaterial) {
  82083. this._compileMaterialAsync(subMaterial, mesh, function () {
  82084. if (--remaining === 0) {
  82085. onSuccess();
  82086. }
  82087. });
  82088. }
  82089. }
  82090. }
  82091. }
  82092. };
  82093. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  82094. var _this = this;
  82095. if (!this._parent.compileShadowGenerators) {
  82096. onSuccess();
  82097. return;
  82098. }
  82099. var lights = this._babylonScene.lights;
  82100. var remaining = 0;
  82101. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  82102. var light = lights_1[_i];
  82103. var generator = light.getShadowGenerator();
  82104. if (generator) {
  82105. remaining++;
  82106. }
  82107. }
  82108. if (remaining === 0) {
  82109. onSuccess();
  82110. return;
  82111. }
  82112. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  82113. var light = lights_2[_a];
  82114. var generator = light.getShadowGenerator();
  82115. if (generator) {
  82116. generator.forceCompilation(function () {
  82117. if (--remaining === 0) {
  82118. _this._tryCatchOnError(onSuccess);
  82119. }
  82120. });
  82121. }
  82122. }
  82123. };
  82124. GLTFLoader.Extensions = {};
  82125. return GLTFLoader;
  82126. }());
  82127. GLTF2.GLTFLoader = GLTFLoader;
  82128. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  82129. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  82130. })(BABYLON || (BABYLON = {}));
  82131. //# sourceMappingURL=babylon.glTFLoader.js.map
  82132. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82133. var BABYLON;
  82134. (function (BABYLON) {
  82135. var GLTF2;
  82136. (function (GLTF2) {
  82137. /**
  82138. * Utils functions for GLTF
  82139. */
  82140. var GLTFUtils = /** @class */ (function () {
  82141. function GLTFUtils() {
  82142. }
  82143. /**
  82144. * If the uri is a base64 string
  82145. * @param uri: the uri to test
  82146. */
  82147. GLTFUtils.IsBase64 = function (uri) {
  82148. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  82149. };
  82150. /**
  82151. * Decode the base64 uri
  82152. * @param uri: the uri to decode
  82153. */
  82154. GLTFUtils.DecodeBase64 = function (uri) {
  82155. var decodedString = atob(uri.split(",")[1]);
  82156. var bufferLength = decodedString.length;
  82157. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  82158. for (var i = 0; i < bufferLength; i++) {
  82159. bufferView[i] = decodedString.charCodeAt(i);
  82160. }
  82161. return bufferView.buffer;
  82162. };
  82163. GLTFUtils.ValidateUri = function (uri) {
  82164. return (uri.indexOf("..") === -1);
  82165. };
  82166. return GLTFUtils;
  82167. }());
  82168. GLTF2.GLTFUtils = GLTFUtils;
  82169. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  82170. })(BABYLON || (BABYLON = {}));
  82171. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  82172. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82173. var BABYLON;
  82174. (function (BABYLON) {
  82175. var GLTF2;
  82176. (function (GLTF2) {
  82177. var GLTFLoaderExtension = /** @class */ (function () {
  82178. function GLTFLoaderExtension() {
  82179. this.enabled = true;
  82180. }
  82181. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  82182. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  82183. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  82184. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  82185. var _this = this;
  82186. if (!property.extensions) {
  82187. return false;
  82188. }
  82189. var extension = property.extensions[this.name];
  82190. if (!extension) {
  82191. return false;
  82192. }
  82193. // Clear out the extension before executing the action to avoid recursing into the same property.
  82194. property.extensions[this.name] = undefined;
  82195. action(context + "extensions/" + this.name, extension, function () {
  82196. // Restore the extension after completing the action.
  82197. property.extensions[_this.name] = extension;
  82198. });
  82199. return true;
  82200. };
  82201. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  82202. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  82203. };
  82204. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  82205. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  82206. };
  82207. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  82208. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  82209. };
  82210. GLTFLoaderExtension._ApplyExtensions = function (action) {
  82211. var extensions = GLTFLoaderExtension._Extensions;
  82212. if (!extensions) {
  82213. return false;
  82214. }
  82215. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  82216. var extension = extensions_1[_i];
  82217. if (extension.enabled && action(extension)) {
  82218. return true;
  82219. }
  82220. }
  82221. return false;
  82222. };
  82223. //
  82224. // Utilities
  82225. //
  82226. GLTFLoaderExtension._Extensions = [];
  82227. return GLTFLoaderExtension;
  82228. }());
  82229. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  82230. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  82231. })(BABYLON || (BABYLON = {}));
  82232. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  82233. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  82234. var BABYLON;
  82235. (function (BABYLON) {
  82236. var GLTF2;
  82237. (function (GLTF2) {
  82238. var Extensions;
  82239. (function (Extensions) {
  82240. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  82241. var MSFTLOD = /** @class */ (function (_super) {
  82242. __extends(MSFTLOD, _super);
  82243. function MSFTLOD() {
  82244. var _this = _super !== null && _super.apply(this, arguments) || this;
  82245. /**
  82246. * Specify the minimal delay between LODs in ms (default = 250)
  82247. */
  82248. _this.Delay = 250;
  82249. return _this;
  82250. }
  82251. Object.defineProperty(MSFTLOD.prototype, "name", {
  82252. get: function () {
  82253. return "MSFT_lod";
  82254. },
  82255. enumerable: true,
  82256. configurable: true
  82257. });
  82258. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  82259. return this._loadExtension(context, node, function (context, extension, onComplete) {
  82260. for (var i = extension.ids.length - 1; i >= 0; i--) {
  82261. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  82262. if (!lodNode) {
  82263. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  82264. }
  82265. loader._traverseNode(context, lodNode, action, parentNode);
  82266. }
  82267. loader._traverseNode(context, node, action, parentNode);
  82268. onComplete();
  82269. });
  82270. };
  82271. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  82272. var _this = this;
  82273. return this._loadExtension(context, node, function (context, extension, onComplete) {
  82274. var nodes = [node];
  82275. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  82276. var index = _a[_i];
  82277. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  82278. if (!lodNode) {
  82279. throw new Error(context + ": Failed to find node " + index);
  82280. }
  82281. nodes.push(lodNode);
  82282. }
  82283. loader._addLoaderPendingData(node);
  82284. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  82285. loader._removeLoaderPendingData(node);
  82286. onComplete();
  82287. });
  82288. });
  82289. };
  82290. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  82291. var _this = this;
  82292. loader._whenAction(function () {
  82293. loader._loadNode(context, nodes[index]);
  82294. }, function () {
  82295. if (index !== nodes.length - 1) {
  82296. var previousNode = nodes[index + 1];
  82297. previousNode.babylonMesh.setEnabled(false);
  82298. }
  82299. if (index === 0) {
  82300. onComplete();
  82301. return;
  82302. }
  82303. setTimeout(function () {
  82304. loader._tryCatchOnError(function () {
  82305. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  82306. });
  82307. }, _this.Delay);
  82308. });
  82309. };
  82310. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  82311. var _this = this;
  82312. return this._loadExtension(context, material, function (context, extension, onComplete) {
  82313. var materials = [material];
  82314. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  82315. var index = _a[_i];
  82316. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  82317. if (!lodMaterial) {
  82318. throw new Error(context + ": Failed to find material " + index);
  82319. }
  82320. materials.push(lodMaterial);
  82321. }
  82322. loader._addLoaderPendingData(material);
  82323. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  82324. loader._removeLoaderPendingData(material);
  82325. onComplete();
  82326. });
  82327. });
  82328. };
  82329. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  82330. var _this = this;
  82331. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  82332. if (index === materials.length - 1) {
  82333. assign(babylonMaterial, isNew);
  82334. // Load the next LOD when the loader is ready to render.
  82335. loader._executeWhenRenderReady(function () {
  82336. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  82337. });
  82338. }
  82339. else {
  82340. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  82341. assign(babylonMaterial, isNew);
  82342. if (index === 0) {
  82343. onComplete();
  82344. }
  82345. else {
  82346. setTimeout(function () {
  82347. loader._tryCatchOnError(function () {
  82348. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  82349. });
  82350. }, _this.Delay);
  82351. }
  82352. });
  82353. }
  82354. });
  82355. };
  82356. return MSFTLOD;
  82357. }(GLTF2.GLTFLoaderExtension));
  82358. Extensions.MSFTLOD = MSFTLOD;
  82359. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  82360. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  82361. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  82362. })(BABYLON || (BABYLON = {}));
  82363. //# sourceMappingURL=MSFT_lod.js.map
  82364. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  82365. var BABYLON;
  82366. (function (BABYLON) {
  82367. var GLTF2;
  82368. (function (GLTF2) {
  82369. var Extensions;
  82370. (function (Extensions) {
  82371. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  82372. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  82373. function KHRMaterialsPbrSpecularGlossiness() {
  82374. return _super !== null && _super.apply(this, arguments) || this;
  82375. }
  82376. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  82377. get: function () {
  82378. return "KHR_materials_pbrSpecularGlossiness";
  82379. },
  82380. enumerable: true,
  82381. configurable: true
  82382. });
  82383. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  82384. var _this = this;
  82385. return this._loadExtension(context, material, function (context, extension, onComplete) {
  82386. loader._createPbrMaterial(material);
  82387. loader._loadMaterialBaseProperties(context, material);
  82388. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  82389. assign(material.babylonMaterial, true);
  82390. onComplete();
  82391. });
  82392. };
  82393. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  82394. var babylonMaterial = material.babylonMaterial;
  82395. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  82396. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  82397. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  82398. if (properties.diffuseTexture) {
  82399. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  82400. if (!texture) {
  82401. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  82402. }
  82403. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  82404. }
  82405. if (properties.specularGlossinessTexture) {
  82406. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  82407. if (!texture) {
  82408. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  82409. }
  82410. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  82411. babylonMaterial.reflectivityTexture.hasAlpha = true;
  82412. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  82413. }
  82414. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  82415. };
  82416. return KHRMaterialsPbrSpecularGlossiness;
  82417. }(GLTF2.GLTFLoaderExtension));
  82418. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  82419. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  82420. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  82421. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  82422. })(BABYLON || (BABYLON = {}));
  82423. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  82424. (function universalModuleDefinition(root, factory) {
  82425. var f = factory();
  82426. if (root && root["BABYLON"]) {
  82427. return;
  82428. }
  82429. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  82430. globalObject["BABYLON"] = f;
  82431. if(typeof exports === 'object' && typeof module === 'object')
  82432. module.exports = f;
  82433. else if(typeof define === 'function' && define.amd)
  82434. define(["BABYLON"], factory);
  82435. else if(typeof exports === 'object')
  82436. exports["BABYLON"] = f;
  82437. else {
  82438. root["BABYLON"] = f;
  82439. }
  82440. })(this, function() {
  82441. return BABYLON;
  82442. });